Getting Started

Build a User Management App with Next.js


This 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 User Management example

Project setup

Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase and then creating a "schema" inside the database.

Create a project

  1. Create a new project in the Supabase Dashboard.
  2. Enter your project details.
  3. Wait for the new database to launch.

Set up the database schema

Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, or you can just copy/paste the SQL from below and run it yourself.

  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter.
  3. Click Run.

_10
supabase link --project-ref <project-id>
_10
# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>
_10
supabase db pull

Get the API Keys

Now that you've created some database tables, you are ready to insert data using the auto-generated API. We just need to get the Project URL and anon key from the API settings.

  1. Go to the API Settings page in the Dashboard.
  2. Find your Project URL, anon, and service_role keys on this page.

Building the app

Let's start building the Next.js app from scratch.

Initialize a Next.js app

We can use create-next-app to initialize an app called supabase-nextjs:


_10
npx create-next-app@latest --use-npm supabase-nextjs
_10
cd supabase-nextjs

Then install the Supabase client library: supabase-js


_10
npm install @supabase/supabase-js

And finally we want to save the environment variables in a .env.local. Create a .env.local file at the root of the project, and paste the API URL and the anon key that you copied earlier.

.env.local

_10
NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
_10
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY

App styling (optional)

An optional step is to update the CSS file app/globals.css to make the app look nice. You can find the full contents of this file here.

Supabase Server-Side Auth

Next.js is a highly versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and middleware 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. See the Next.js Server-Side Auth guide for more information.

Install the package for Next.js.


_10
npm install @supabase/ssr

Supabase utilities

There are two different types of clients in Supabase:

  1. Client Component client - To access Supabase from Client Components, which run in the browser.
  2. Server Component client - To access Supabase from Server Components, Server Actions, and Route Handlers, which run only on the server.

It is recommended to create the following essential utilities files for creating clients, and organize them within utils/supabase at the root of the project.

Create a client.js and a server.js with the following functionalities for client-side Supabase and server-side Supabase, respectively.

utils/supabase/client.js
utils/supabase/server.js

_10
import { createBrowserClient } from '@supabase/ssr'
_10
_10
export function createClient() {
_10
// Create a supabase client on the browser with project's credentials
_10
return createBrowserClient(
_10
process.env.NEXT_PUBLIC_SUPABASE_URL,
_10
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
_10
)
_10
}

Next.js middleware

Since Server Components can't write cookies, you need middleware to refresh expired Auth tokens and store them. This is accomplished by:

  • Refreshing the Auth token with the call to supabase.auth.getUser.
  • 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 middleware only runs on route that access Supabase. For more information, check out this documentation.

Create a middleware.js file at the project root and another one within the utils/supabase folder. The utils/supabase file contains the logic for updating the session. This is used by the middleware.js file, which is a Next.js convention.

middleware.js
utils/supabase/middleware.js

_19
import { updateSession } from '@/utils/supabase/middleware'
_19
_19
export async function middleware(request) {
_19
// update user's auth session
_19
return await updateSession(request)
_19
}
_19
_19
export const config = {
_19
matcher: [
_19
/*
_19
* Match all request paths except for the ones starting with:
_19
* - _next/static (static files)
_19
* - _next/image (image optimization files)
_19
* - favicon.ico (favicon file)
_19
* Feel free to modify this pattern to include more paths.
_19
*/
_19
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
_19
],
_19
}

Set up a login page

Login and Signup form

Create a login/signup page for your application:

Create a new folder named login, containing a page.jsx file with a login/signup form.

app/login/page.jsx

_14
import { login, signup } from './actions'
_14
_14
export default function LoginPage() {
_14
return (
_14
<form>
_14
<label htmlFor="email">Email:</label>
_14
<input id="email" name="email" type="email" required />
_14
<label htmlFor="password">Password:</label>
_14
<input id="password" name="password" type="password" required />
_14
<button formAction={login}>Log in</button>
_14
<button formAction={signup}>Sign up</button>
_14
</form>
_14
)
_14
}

Navigate to http://localhost:3000/login. You should see your login form, but it's not yet hooked up to the actual login function. Next, you need to create the login/signup actions. They will:

  • Retrieve the user's information.
  • Send that information to Supabase as a signup request, which in turns will send a confirmation email.
  • Handle any error that arises.
app/login/actions.js
app/error/page.jsx

_44
'use server'
_44
_44
import { revalidatePath } from 'next/cache'
_44
import { redirect } from 'next/navigation'
_44
_44
import { createClient } from '@/utils/supabase/server'
_44
_44
export async function login(formData) {
_44
const supabase = await createClient()
_44
_44
// type-casting here for convenience
_44
// in practice, you should validate your inputs
_44
const data = {
_44
email: formData.get('email'),
_44
password: formData.get('password'),
_44
}
_44
_44
const { error } = await supabase.auth.signInWithPassword(data)
_44
_44
if (error) {
_44
redirect('/error')
_44
}
_44
_44
revalidatePath('/', 'layout')
_44
redirect('/account')
_44
}
_44
_44
export async function signup(formData) {
_44
const supabase = await createClient()
_44
_44
const data = {
_44
email: formData.get('email'),
_44
password: formData.get('password'),
_44
}
_44
_44
const { error } = await supabase.auth.signUp(data)
_44
_44
if (error) {
_44
redirect('/error')
_44
}
_44
_44
revalidatePath('/', 'layout')
_44
redirect('/account')
_44
}

When you enter your email and password, you will receive an email with the title Confirm Your Signup. Congrats 🎉!!!

Email template

Change the email template to support a server-side authentication flow.

Before we proceed, let's change the email template to support sending a token hash:

  • Go to the Auth templates page in your dashboard.
  • Select Confirm signup template.
  • Change {{ .ConfirmationURL }} to {{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email.

Confirmation endpoint

As we are working in a server-side rendering (SSR) environment, it is necessary to create a server endpoint responsible for exchanging the token_hash for a session.

In the following code snippet, we perform the following steps:

  • Retrieve the code sent back from the Supabase Auth server using the token_hash query parameter.
  • Exchange this code for a session, which we store in our chosen storage mechanism (in this case, cookies).
  • Finally, we redirect the user to the account page.
app/auth/confirm/route.js

_34
import { type NextRequest, NextResponse } from 'next/server'
_34
_34
import { createClient } from '@/utils/supabase/server'
_34
_34
// Creating a handler to a GET request to route /auth/confirm
_34
export async function GET(request) {
_34
const { searchParams } = new URL(request.url)
_34
const token_hash = searchParams.get('token_hash')
_34
const type = searchParams.get('type')
_34
const next = '/account'
_34
_34
// Create redirect link without the secret token
_34
const redirectTo = request.nextUrl.clone()
_34
redirectTo.pathname = next
_34
redirectTo.searchParams.delete('token_hash')
_34
redirectTo.searchParams.delete('type')
_34
_34
if (token_hash && type) {
_34
const supabase = await createClient()
_34
_34
const { error } = await supabase.auth.verifyOtp({
_34
type,
_34
token_hash,
_34
})
_34
if (!error) {
_34
redirectTo.searchParams.delete('next')
_34
return NextResponse.redirect(redirectTo)
_34
}
_34
}
_34
_34
// return the user to an error page with some instructions
_34
redirectTo.pathname = '/error'
_34
return NextResponse.redirect(redirectTo)
_34
}

Account page

After a user is signed in we can allow them to edit their profile details and manage their account.

Let's create a new component for that called AccountForm within the app/account folder.

app/account/account-form.jsx

_118
'use client'
_118
import { useCallback, useEffect, useState } from 'react'
_118
import { createClient } from '@/utils/supabase/client'
_118
_118
export default function AccountForm({ user }) {
_118
const supabase = createClient()
_118
const [loading, setLoading] = useState(true)
_118
const [fullname, setFullname] = useState(null)
_118
const [username, setUsername] = useState(null)
_118
const [website, setWebsite] = useState(null)
_118
const [avatar_url, setAvatarUrl] = useState(null)
_118
_118
const getProfile = useCallback(async () => {
_118
try {
_118
setLoading(true)
_118
_118
const { data, error, status } = await supabase
_118
.from('profiles')
_118
.select(`full_name, username, website, avatar_url`)
_118
.eq('id', user?.id)
_118
.single()
_118
_118
if (error && status !== 406) {
_118
throw error
_118
}
_118
_118
if (data) {
_118
setFullname(data.full_name)
_118
setUsername(data.username)
_118
setWebsite(data.website)
_118
setAvatarUrl(data.avatar_url)
_118
}
_118
} catch (error) {
_118
alert('Error loading user data!')
_118
} finally {
_118
setLoading(false)
_118
}
_118
}, [user, supabase])
_118
_118
useEffect(() => {
_118
getProfile()
_118
}, [user, getProfile])
_118
_118
async function updateProfile({ username, website, avatar_url }) {
_118
try {
_118
setLoading(true)
_118
_118
const { error } = await supabase.from('profiles').upsert({
_118
id: user?.id,
_118
full_name: fullname,
_118
username,
_118
website,
_118
avatar_url,
_118
updated_at: new Date().toISOString(),
_118
})
_118
if (error) throw error
_118
alert('Profile updated!')
_118
} catch (error) {
_118
alert('Error updating the data!')
_118
} finally {
_118
setLoading(false)
_118
}
_118
}
_118
_118
return (
_118
<div className="form-widget">
_118
<div>
_118
<label htmlFor="email">Email</label>
_118
<input id="email" type="text" value={user?.email} disabled />
_118
</div>
_118
<div>
_118
<label htmlFor="fullName">Full Name</label>
_118
<input
_118
id="fullName"
_118
type="text"
_118
value={fullname || ''}
_118
onChange={(e) => setFullname(e.target.value)}
_118
/>
_118
</div>
_118
<div>
_118
<label htmlFor="username">Username</label>
_118
<input
_118
id="username"
_118
type="text"
_118
value={username || ''}
_118
onChange={(e) => setUsername(e.target.value)}
_118
/>
_118
</div>
_118
<div>
_118
<label htmlFor="website">Website</label>
_118
<input
_118
id="website"
_118
type="url"
_118
value={website || ''}
_118
onChange={(e) => setWebsite(e.target.value)}
_118
/>
_118
</div>
_118
_118
<div>
_118
<button
_118
className="button primary block"
_118
onClick={() => updateProfile({ fullname, username, website, avatar_url })}
_118
disabled={loading}
_118
>
_118
{loading ? 'Loading ...' : 'Update'}
_118
</button>
_118
</div>
_118
_118
<div>
_118
<form action="/auth/signout" method="post">
_118
<button className="button block" type="submit">
_118
Sign out
_118
</button>
_118
</form>
_118
</div>
_118
</div>
_118
)
_118
}

Create an account page for the AccountForm component we just created

app/account/page.jsx

_12
import AccountForm from './account-form'
_12
import { createClient } from '@/utils/supabase/server'
_12
_12
export default async function Account() {
_12
const supabase = await createClient()
_12
_12
const {
_12
data: { user },
_12
} = await supabase.auth.getUser()
_12
_12
return <AccountForm user={user} />
_12
}

Sign out

Let's create a route handler to handle the signout from the server side. Make sure to check if the user is logged in first!

app/auth/signout/route.js

_21
import { createClient } from '@/utils/supabase/server'
_21
import { revalidatePath } from 'next/cache'
_21
import { NextResponse } from 'next/server'
_21
_21
export async function POST(req) {
_21
const supabase = await createClient()
_21
_21
// Check if a user's logged in
_21
const {
_21
data: { user },
_21
} = await supabase.auth.getUser()
_21
_21
if (user) {
_21
await supabase.auth.signOut()
_21
}
_21
_21
revalidatePath('/', 'layout')
_21
return NextResponse.redirect(new URL('/login', req.url), {
_21
status: 302,
_21
})
_21
}

Launch!

Now that we have all the pages, route handlers and components in place, let's run this in a terminal window:


_10
npm run dev

And then open the browser to localhost:3000 and you should see the completed app.

Bonus: Profile photos

Every Supabase project is configured with Storage for managing large files like photos and videos.

Create an upload widget

Let's create an avatar widget for the user so that they can upload a profile photo. We can start by creating a new component:

app/account/avatar.jsx

_87
'use client'
_87
import React, { useEffect, useState } from 'react'
_87
import { createClient } from '@/utils/supabase/client'
_87
import Image from 'next/image'
_87
_87
export default function Avatar({ uid, url, size, onUpload }) {
_87
const supabase = createClient()
_87
const [avatarUrl, setAvatarUrl] = useState(url)
_87
const [uploading, setUploading] = useState(false)
_87
_87
useEffect(() => {
_87
async function downloadImage(path) {
_87
try {
_87
const { data, error } = await supabase.storage.from('avatars').download(path)
_87
if (error) {
_87
throw error
_87
}
_87
_87
const url = URL.createObjectURL(data)
_87
setAvatarUrl(url)
_87
} catch (error) {
_87
console.log('Error downloading image: ', error)
_87
}
_87
}
_87
_87
if (url) downloadImage(url)
_87
}, [url, supabase])
_87
_87
const uploadAvatar = async (event) => {
_87
try {
_87
setUploading(true)
_87
_87
if (!event.target.files || event.target.files.length === 0) {
_87
throw new Error('You must select an image to upload.')
_87
}
_87
_87
const file = event.target.files[0]
_87
const fileExt = file.name.split('.').pop()
_87
const filePath = `${uid}-${Math.random()}.${fileExt}`
_87
_87
const { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
_87
_87
if (uploadError) {
_87
throw uploadError
_87
}
_87
_87
onUpload(filePath)
_87
} catch (error) {
_87
alert('Error uploading avatar!')
_87
} finally {
_87
setUploading(false)
_87
}
_87
}
_87
_87
return (
_87
<div>
_87
{avatarUrl ? (
_87
<Image
_87
width={size}
_87
height={size}
_87
src={avatarUrl}
_87
alt="Avatar"
_87
className="avatar image"
_87
style={{ height: size, width: size }}
_87
/>
_87
) : (
_87
<div className="avatar no-image" style={{ height: size, width: size }} />
_87
)}
_87
<div style={{ width: size }}>
_87
<label className="button primary block" htmlFor="single">
_87
{uploading ? 'Uploading ...' : 'Upload'}
_87
</label>
_87
<input
_87
style={{
_87
visibility: 'hidden',
_87
position: 'absolute',
_87
}}
_87
type="file"
_87
id="single"
_87
accept="image/*"
_87
onChange={uploadAvatar}
_87
disabled={uploading}
_87
/>
_87
</div>
_87
</div>
_87
)
_87
}

Add the new widget

And then we can add the widget to the AccountForm component:

app/account/account-form.jsx

_20
// Import the new component
_20
import Avatar from './avatar'
_20
_20
// ...
_20
_20
return (
_20
<div className="form-widget">
_20
{/* Add to the body */}
_20
<Avatar
_20
uid={user?.id}
_20
url={avatar_url}
_20
size={150}
_20
onUpload={(url) => {
_20
setAvatarUrl(url)
_20
updateProfile({ fullname, username, website, avatar_url: url })
_20
}}
_20
/>
_20
{/* ... */}
_20
</div>
_20
)

At this stage you have a fully functional application!

See also