Build a User Management App with Next.js
Explore drop-in UI components for your Supabase app.
UI components built on shadcn/ui that connect to Supabase via a single command.
Explore ComponentsThis tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:
- Supabase Database - a Postgres database for storing your user data and Row Level Security so data is protected and users can only access their own information.
- Supabase Auth - allow users to sign up and log in.
- Supabase Storage - allow users to upload a profile photo.

If you get stuck while working through this guide, you can find the full example on GitHub.
Project setup#
Before you start building you need to set up the Database and API. You can do this by starting a new Project in Supabase and then creating a "schema" inside the database.
Create a project#
- Create a new project in the Supabase Dashboard.
- Enter your project details.
- Wait for the new database to launch.
Set up the database schema#
Now set up the database schema. You can use the "User Management Starter" quickstart in the SQL Editor, or you can copy/paste the SQL from below and run it.
- Go to the SQL Editor page in the Dashboard.
- Click User Management Starter under the Community > Quickstarts tab.
- Click Run.
You can pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.
1supabase link --project-ref <project-id>2# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>3supabase db pullGet API details#
Now that you've created some database tables, you are ready to insert data using the auto-generated API.
To do this, you need to get the Project URL and key from the project Connect dialog.
Read the API keys docs for a full explanation of all key types and their uses.
Changes to API keys
Supabase is changing the way keys work to improve project security and developer experience. You can read the full announcement on GitHub.
The older anon and service_role keys will work until the end of 2026 but we strongly encourage switching to and using the new publishable (sb_publishable_xxx) and secret (sb_secret_xxx) keys now.
In most cases, you can get keys from the Project's Connect dialog, but if you want a specific key, you can find them in the Settings > API Keys section of the Dashboard.
- For legacy keys, copy the
anonkey for client-side operations and theservice_rolekey for server-side operations from the Legacy API Keys tab. - For new keys, open the API Keys tab, if you don't have a publishable key already, click Create new API Keys, and copy the value from the Publishable key section.
Building the app#
Start building the Next.js app from scratch.
Initialize a Next.js app#
Use create-next-app to initialize an app called supabase-nextjs:
1npx create-next-app@latest --ts --use-npm supabase-nextjs2cd supabase-nextjsInstall supabase-js:
1npm install @supabase/supabase-jsSave the environment variables in a .env.local file at the root of the project, and paste the API URL and the key that you copied earlier.
The application exposes these variables in the browser, and that's fine as Supabase enables Row Level Security by default on all tables.
1NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL2NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=YOUR_SUPABASE_PUBLISHABLE_KEYApp styling (optional)#
An optional step is to update the CSS file app/globals.css to make the app look better.
You can find the full contents of this file in the example repository.
Supabase Server-Side Auth package#
Next.js is a versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and proxy edge-functions.
To better integrate with the framework, we've created the @supabase/ssr package for Server-Side Auth. It has all the functionalities to quickly configure your Supabase project to use cookies for storing user sessions. Read the Next.js Server-Side Auth guide for more information.
Install the package for Next.js.
1npm install @supabase/ssrSupabase utilities#
There are two different types of clients in Supabase:
- Client Component client - To access Supabase from Client Components, which run in the browser.
- Server Component client - To access Supabase from Server Components, Server Actions, and Route Handlers, which run only on the server.
We recommend creating the following utilities files for creating clients, and organize them within lib/supabase at the root of the project.
Create a client.ts and a server.ts with the following code for client-side Supabase and server-side Supabase, respectively.
1import { createBrowserClient } from '@supabase/ssr'23export function createClient() {4 // Create a supabase client on the browser with project's credentials5 return createBrowserClient(6 process.env.NEXT_PUBLIC_SUPABASE_URL!,7 process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!8 )9}Next.js proxy#
Since Server Components can't write cookies, you need Proxy to refresh expired Auth tokens and store them.
You accomplish this by:
- Refreshing the Auth token with the call to
supabase.auth.getClaims. - Passing the refreshed Auth token to Server Components through
request.cookies.set, so they don't attempt to refresh the same token themselves. - Passing the refreshed Auth token to the browser, so it replaces the old token. This is done with
response.cookies.set.
You could also add a matcher, so that the Proxy only runs on routes that access Supabase. For more information, read the Next.js matcher documentation.
Be careful when protecting pages. The server gets the user session from the cookies, which anyone can spoof.
The Supabase Auth SDK contains three different functions for authenticating user access to applications:
Summary of the methods#
- Use
getClaimsto protect pages and user data. It reads the access token from storage and verifies it. Locally via the WebCrypto API and a cached JWKS endpoint when the project uses asymmetric signing keys (the default for new projects), or by callinggetUsersolely to validate when symmetric keys are in use. The returned claims always come from decoding the JWT, not from a user lookup. getUsermakes a network call to the project's Auth instance to get the user record, which includes the most up-to-date information about the user at the cost of a network call.getSessionwhen you need the raw session (the access token, refresh token, and expiry). For example to forward the access token to another service. The session is loaded directly from local storage and isn't re-validated against the Auth server, so the embedded user object shouldn't be trusted on its own when storage is shared with the client (cookies, request headers). To verify identity, validate the access token withgetClaims, or callgetUserfor a fresh, server-confirmed user record.
In summary: use getClaims to verify identity (typically for protecting pages and data), getUser when you need an up-to-date user record from the Auth server, and getSession when you need the access or refresh token directly, but don't rely on the user object it returns for authorization decisions.
Create a proxy.ts file at the project root and another one within the lib/supabase folder. The lib/supabase file contains the logic for updating the session. The proxy.ts file uses this, which is a Next.js convention.
1import { type NextRequest } from 'next/server'2import { updateSession } from '@/lib/supabase/proxy'34export async function proxy(request: NextRequest) {5 // update user's auth session6 return await updateSession(request)7}89export const config = {10 matcher: [11 /*12 * Match all request paths except for the ones starting with:13 * - _next/static (static files)14 * - _next/image (image optimization files)15 * - favicon.ico (favicon file)16 * Feel free to modify this pattern to include more paths.17 */18 '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',19 ],20}Set up a login page#
Login and signup form#
To add login/signup page for your application, create a new folder named login, containing a page.tsx file with the following code for a login/signup form:
1import { login, signup } from './actions'23export default function LoginPage() {4 return (5 <form>6 <label htmlFor="email">Email:</label>7 <input id="email" name="email" type="email" required />8 <label htmlFor="password">Password:</label>9 <input id="password" name="password" type="password" required />10 <button formAction={login}>Log in</button>11 <button formAction={signup}>Sign up</button>12 </form>13 )14}Create the login/signup actions to hook up the form to the function which does the following:
- Retrieve the user's information.
- Send that information to Supabase as a signup request, which in turns sends a confirmation email. It uses Magic Links, so users can sign in with their email without using passwords.
- Handle any error that arises.
Create the action.ts file in the app/login folder, which contains the login and signup functions and the error/page.tsx file, which displays an error message if the login or signup fails.
1'use server'23import { revalidatePath } from 'next/cache'4import { redirect } from 'next/navigation'56import { createClient } from '@/lib/supabase/server'78export async function login(formData: FormData) {9 const supabase = await createClient()1011 // type-casting here for convenience12 // in practice, you should validate your inputs13 const data = {14 email: formData.get('email') as string,15 password: formData.get('password') as string,16 }1718 const { error } = await supabase.auth.signInWithPassword(data)1920 if (error) {21 redirect('/error')22 }2324 revalidatePath('/', 'layout')25 redirect('/account')26}2728export async function signup(formData: FormData) {29 const supabase = await createClient()3031 // type-casting here for convenience32 // in practice, you should validate your inputs33 const data = {34 email: formData.get('email') as string,35 password: formData.get('password') as string,36 }3738 const { error } = await supabase.auth.signUp(data)3940 if (error) {41 redirect('/error')42 }4344 revalidatePath('/', 'layout')45 redirect('/account')46}The cookies method is called before any calls to Supabase, which takes fetch calls out of Next.js's caching. This is important for authenticated data fetches, to ensure that users get access only to their own data.
Read the Next.js docs to learn more about opting out of data caching.
Email template#
Before proceeding, change the email template to support a server-side authentication flow that sends a token hash:
- Go to the Auth templates page in your dashboard.
- Select the Confirm signup template.
- Change
{{ .ConfirmationURL }}to{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email.
Did you know?
You can customize other emails sent out to new users, including the email's looks, content, and query parameters from the Authentication > Email section of the Dashboard.
Confirmation endpoint#
As you are working in a server-side rendering (SSR) environment, you need to create a server endpoint responsible for exchanging the token_hash for a session.
The code performs the following steps:
- Retrieves the code sent back from the Supabase Auth server using the
token_hashquery parameter. - Exchanges this code for a session, which you store in your chosen storage mechanism (in this case, cookies).
- Finally, redirects the user to the
accountpage.
app/auth/confirm/route.ts
1import { type EmailOtpType } from '@supabase/supabase-js'2import { type NextRequest, NextResponse } from 'next/server'3import { createClient } from '@/lib/supabase/server'45// Creating a handler to a GET request to route /auth/confirm6export async function GET(request: NextRequest) {7 const { searchParams } = new URL(request.url)8 const token_hash = searchParams.get('token_hash')9 const type = searchParams.get('type') as EmailOtpType | null10 const next = '/account'1112 // Create redirect link without the secret token13 const redirectTo = request.nextUrl.clone()14 redirectTo.pathname = next15 redirectTo.searchParams.delete('token_hash')16 redirectTo.searchParams.delete('type')1718 if (token_hash && type) {19 const supabase = await createClient()2021 const { error } = await supabase.auth.verifyOtp({22 type,23 token_hash,24 })25 if (!error) {26 redirectTo.searchParams.delete('next')27 return NextResponse.redirect(redirectTo)28 }29 }3031 // return the user to an error page with some instructions32 redirectTo.pathname = '/error'33 return NextResponse.redirect(redirectTo)34}Account page#
After a user signs in, they need a way to edit their profile details and manage their accounts.
Create a new component for that called AccountForm within the app/account folder.
app/account/account-form.tsx
1'use client'2import { useCallback, useEffect, useState } from 'react'3import { createClient } from '@/lib/supabase/client'4import Avatar from './avatar'56// ...789export default function AccountForm({ claims }: { claims: Claims | null }) {10 const supabase = createClient()11 const [loading, setLoading] = useState(true)12 const [fullname, setFullname] = useState<string | null>(null)13 const [username, setUsername] = useState<string | null>(null)14 const [website, setWebsite] = useState<string | null>(null)15 const [avatar_url, setAvatarUrl] = useState<string | null>(null)1617 const getProfile = useCallback(async () => {18 try {19 if (!claims?.sub) {20 setLoading(false)21 return22 }2324 setLoading(true)2526 const { data, error, status } = await supabase27 .from('profiles')28 .select(`full_name, username, website, avatar_url`)29 .eq('id', claims.sub)30 .single()3132 if (error && status !== 406) {33 console.log(error)34 throw error35 }3637 if (data) {38 setFullname(data.full_name)39 setUsername(data.username)40 setWebsite(data.website)41 setAvatarUrl(data.avatar_url)42 }43 } catch (error) {44 alert('Error loading user data!')45 } finally {46 setLoading(false)47 }48 }, [claims, supabase])4950 useEffect(() => {51 getProfile()52 }, [claims, getProfile])5354 async function updateProfile({55 username,56 website,57 avatar_url,58 }: {59 username: string | null60 fullname: string | null61 website: string | null62 avatar_url: string | null63 }) {64 try {65 if (!claims?.sub) {66 alert('You must be logged in to update your profile')67 return68 }6970 setLoading(true)7172 const { error } = await supabase.from('profiles').upsert({73 id: claims.sub,74 full_name: fullname,75 username,76 website,77 avatar_url,78 updated_at: new Date().toISOString(),79 })8081 // ...8283 return (84 <div className="form-widget">8586 {/* ... */}8788 <div>89 <label htmlFor="email">Email</label>90 <input id="email" type="text" value={claims?.email ?? ''} disabled />91 </div>92 <div>93 <label htmlFor="fullName">Full Name</label>94 <input95 id="fullName"96 type="text"97 value={fullname || ''}98 onChange={(e) => setFullname(e.target.value)}99 />100 </div>101 <div>102 <label htmlFor="username">Username</label>103 <input104 id="username"105 type="text"106 value={username || ''}107 onChange={(e) => setUsername(e.target.value)}108 />109 </div>110 <div>111 <label htmlFor="website">Website</label>112 <input113 id="website"114 type="url"115 value={website || ''}116 onChange={(e) => setWebsite(e.target.value)}117 />118 </div>119120 <div>121 <button122 className="button primary block"123 onClick={() => updateProfile({ fullname, username, website, avatar_url })}124 disabled={loading || !claims?.sub}125 >126 {loading ? 'Loading ...' : 'Update'}127 </button>128 </div>129130 <div>131 <form action="/auth/signout" method="post">132 <button className="button block" type="submit">133 Sign out134 </button>135 </form>136 </div>137 </div>138 )139}Create an account page for the AccountForm component you just created
app/account/page.tsx
1import AccountForm from './account-form'2import { createClient } from '@/lib/supabase/server'34export default async function Account() {5 const supabase = await createClient()67 const { data: claimsData } = await supabase.auth.getClaims()89 return <AccountForm claims={claimsData?.claims ?? null} />10}Sign out#
Create a route handler to handle the sign out from the server side, making sure to check if the user is logged in first.
app/auth/signout/route.ts
1import { createClient } from '@/lib/supabase/server'2import { revalidatePath } from 'next/cache'3import { type NextRequest, NextResponse } from 'next/server'45export async function POST(req: NextRequest) {6 const supabase = await createClient()78 // Check if a user's logged in9 const { data: claimsData } = await supabase.auth.getClaims()1011 if (claimsData?.claims) {12 await supabase.auth.signOut()13 }1415 revalidatePath('/', 'layout')16 return NextResponse.redirect(new URL('/login', req.url), {17 status: 302,18 })19}Profile photos#
Next, add a way for users to upload a profile photo. Supabase configures every project with Storage for managing large files like photos and videos.
Create an upload widget#
Start by creating a new component:
app/account/avatar.tsx
1'use client'2import React, { useEffect, useState } from 'react'3import { createClient } from '@/lib/supabase/client'4import Image from 'next/image'56export default function Avatar({7 uid,8 url,9 size,10 onUpload,11}: {12 uid: string | null13 url: string | null14 size: number15 onUpload: (url: string) => void16}) {17 const supabase = createClient()18 const [avatarUrl, setAvatarUrl] = useState<string | null>(url)19 const [uploading, setUploading] = useState(false)2021 useEffect(() => {22 async function downloadImage(path: string) {23 try {24 const { data, error } = await supabase.storage.from('avatars').download(path)25 if (error) {26 throw error27 }2829 const url = URL.createObjectURL(data)30 setAvatarUrl(url)31 } catch (error) {32 console.log('Error downloading image: ', error)33 }34 }3536 if (url) downloadImage(url)37 }, [url, supabase])3839 const uploadAvatar: React.ChangeEventHandler<HTMLInputElement> = async (event) => {40 try {41 setUploading(true)4243 if (!event.target.files || event.target.files.length === 0) {44 throw new Error('You must select an image to upload.')45 }4647 const file = event.target.files[0]48 const fileExt = file.name.split('.').pop()49 const filePath = `${uid}-${Math.random()}.${fileExt}`5051 const { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)5253 if (uploadError) {54 throw uploadError55 }5657 onUpload(filePath)58 } catch (error) {59 alert('Error uploading avatar!')60 } finally {61 setUploading(false)62 }63 }6465 return (66 <div>67 {avatarUrl ? (68 <Image69 width={size}70 height={size}71 src={avatarUrl}72 alt="Avatar"73 className="avatar image"74 style={{ height: size, width: size }}75 />76 ) : (77 <div className="avatar no-image" style={{ height: size, width: size }} />78 )}79 <div style={{ width: size }}>80 <label className="button primary block" htmlFor="single">81 {uploading ? 'Uploading ...' : 'Upload'}82 </label>83 <input84 style={{85 visibility: 'hidden',86 position: 'absolute',87 }}88 type="file"89 id="single"90 accept="image/*"91 onChange={uploadAvatar}92 disabled={uploading}93 />94 </div>95 </div>96 )97}Update the account form#
With the Avatar component created, update app/account/account-form.tsx to include it:
app/account/account-form.tsx
1'use client'2import { useCallback, useEffect, useState } from 'react'3import { createClient } from '@/lib/supabase/client'4import Avatar from './avatar'56type Claims = { sub: string; email?: string; [key: string]: unknown }78export default function AccountForm({ claims }: { claims: Claims | null }) {9 const supabase = createClient()10 const [loading, setLoading] = useState(true)11 const [fullname, setFullname] = useState<string | null>(null)12 const [username, setUsername] = useState<string | null>(null)13 const [website, setWebsite] = useState<string | null>(null)14 const [avatar_url, setAvatarUrl] = useState<string | null>(null)1516 const getProfile = useCallback(async () => {17 try {18 if (!claims?.sub) {19 setLoading(false)20 return21 }2223 setLoading(true)2425 const { data, error, status } = await supabase26 .from('profiles')27 .select(`full_name, username, website, avatar_url`)28 .eq('id', claims.sub)29 .single()3031 if (error && status !== 406) {32 console.log(error)33 throw error34 }3536 if (data) {37 setFullname(data.full_name)38 setUsername(data.username)39 setWebsite(data.website)40 setAvatarUrl(data.avatar_url)41 }42 } catch (error) {43 alert('Error loading user data!')44 } finally {45 setLoading(false)46 }47 }, [claims, supabase])4849 useEffect(() => {50 getProfile()51 }, [claims, getProfile])5253 async function updateProfile({54 username,55 website,56 avatar_url,57 }: {58 username: string | null59 fullname: string | null60 website: string | null61 avatar_url: string | null62 }) {63 try {64 if (!claims?.sub) {65 alert('You must be logged in to update your profile')66 return67 }6869 setLoading(true)7071 const { error } = await supabase.from('profiles').upsert({72 id: claims.sub,73 full_name: fullname,74 username,75 website,76 avatar_url,77 updated_at: new Date().toISOString(),78 })79 if (error) throw error80 alert('Profile updated!')81 } catch (error) {82 alert('Error updating the data!')83 } finally {84 setLoading(false)85 }86 }8788 return (89 <div className="form-widget">90 <Avatar91 uid={claims?.sub ?? null}92 url={avatar_url}93 size={150}94 onUpload={(url) => {95 setAvatarUrl(url)96 updateProfile({ fullname, username, website, avatar_url: url })97 }}98 />99 <div>100 <label htmlFor="email">Email</label>101 <input id="email" type="text" value={claims?.email ?? ''} disabled />102 </div>103 <div>104 <label htmlFor="fullName">Full Name</label>105 <input106 id="fullName"107 type="text"108 value={fullname || ''}109 onChange={(e) => setFullname(e.target.value)}110 />111 </div>112 <div>113 <label htmlFor="username">Username</label>114 <input115 id="username"116 type="text"117 value={username || ''}118 onChange={(e) => setUsername(e.target.value)}119 />120 </div>121 <div>122 <label htmlFor="website">Website</label>123 <input124 id="website"125 type="url"126 value={website || ''}127 onChange={(e) => setWebsite(e.target.value)}128 />129 </div>130131 <div>132 <button133 className="button primary block"134 onClick={() => updateProfile({ fullname, username, website, avatar_url })}135 disabled={loading || !claims?.sub}136 >137 {loading ? 'Loading ...' : 'Update'}138 </button>139 </div>140141 <div>142 <form action="/auth/signout" method="post">143 <button className="button block" type="submit">144 Sign out145 </button>146 </form>147 </div>148 </div>149 )150}Launch#
With all the pages, route handlers, and components in place, run the following in a terminal window:
1npm run devAnd then open the browser to localhost:3000/login and you should see the completed app.
When you enter your email and password, you will receive an email with the title Confirm Your Signup. Congrats 🎉!!!
At this stage you have a fully functional application!
See also#
- See the complete example on GitHub and deploy it to Vercel
- Build a Twitter Clone with the Next.js App Router and Supabase - free egghead course
- Explore the pre-built Auth components
- Explore the Supabase Cache Helpers
- See the Next.js Subscription Payments Starter template on GitHub