FusionAuth QuickStart for Next.js
On this page
This QuickStart explains how to add a login page and authentication to a website built with Next.js. You'll begin with a simple Next.js app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.
This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.
Prerequisites#
This QuickStart requires:
If you use macOS or Windows, you need one of the following container management tools:
- Docker Desktop
- OrbStack (to use OrbStack for
docker composecommands after installation, rundocker context use orbstack) - Podman (in the commands below, replace
dockerwithpodman)
Create a Simple Next.js App#
For this QuickStart, we'll use a Next.js app that reads and writes data to a text file:
-
Create a folder for the app and navigate into it:
$ mkdir nextjs-quickstart && cd nextjs-quickstart -
Create a
package.jsonfile and set the project to use JavaScript modules:$ npm init -y$ npm pkg set type=module -
Install dependencies:
$ npm install next@16.4.6 react@19.3.1 react-dom@19.3.1 -
In the
nextjs-quickstartfolder, create a folder namedapp. In theappfolder, create a file namedlayout.jswith the following contents:export const metadata = { title: 'Text Editor' }; export default function RootLayout({ children }) { return ( <html lang="en"> <body style={{ fontFamily: 'sans-serif', margin: 40, lineHeight: 1.6 }}>{children}</body> </html> ); } -
In the
appfolder, create a file namedpage.jswith the following contents:import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { revalidatePath } from 'next/cache'; const TARGET_FILE = 'note.txt'; async function save(formData) { 'use server'; writeFileSync(TARGET_FILE, formData.get('content')); revalidatePath('/'); // Refresh the page to show updated content } export default function Home() { // Ensure the file exists so we don't crash if (!existsSync(TARGET_FILE)) writeFileSync(TARGET_FILE, 'Hello! Edit this text.'); const content = readFileSync(TARGET_FILE, 'utf8'); return ( <> <h1>Edit: {TARGET_FILE}</h1> <form action={save}> <textarea name="content" key={content} defaultValue={content} style={{ width: '100%', height: 300, padding: 10 }} /> <br /> <button type="submit" style={{ padding: '10px 20px', background: '#007bff', color: 'white', border: 'none' }}>Save Changes</button> </form> </> ); }The page reads
note.txtand shows it in a form. When you submit the form, thesaveserver action writes the new text to the file. -
Run the app:
$ npx next dev -
Open the app at http://localhost:3000.
-
Replace the text area text with "Hello Next.js", then click the Save Changes button.
-
In a file browser or terminal, look in the
nextjs-quickstartfolder. You should see a new file namednote.txt, with text content "Hello Next.js". -
Congratulations, you have a working Next.js app that lets you edit a local text file through your web browser. Press Ctrl+C on your keyboard to stop the Next.js server.
Install and Run FusionAuth#
Before we can add authentication to our Next.js app, we need a local FusionAuth instance:
-
Open your container management tool (listed in the prerequisites above).
-
From the
nextjs-quickstartfolder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:$ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git -
Navigate into the cloned directory:
$ cd fusionauth-quickstart-app -
To start a local instance of FusionAuth, run the following command (omit the
-dflag to see all Docker logs):$ docker compose up -d -
Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.
-
Open http://localhost:9011/admin to access the FusionAuth Admin UI.
-
Log in with these credentials:
- username:
admin@example.com - password:
password
- username:
-
Navigate to Applications -> QuickStart App -> Edit -> OAuth . On this page, you can find your client ID, your client secret, and specify redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Next.js app with FusionAuth.
-
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Next.js app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
Add FusionAuth to the Next.js App#
Now that you have a working instance of FusionAuth and a working Next.js app, let's use FusionAuth to add login to your Next.js app:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to thenextjs-quickstartfolder that containsappandnote.txt:$ cd .. -
Create a file named
.envwith the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production FUSIONAUTH_CALLBACK_URL=http://localhost:3000/oauth-callback SESSION_SECRET=a_very_long_random_string_of_at_least_32_charactersNext.js reads the
.envfile automatically when the server starts. -
Install the dependencies we'll need to authenticate with FusionAuth:
$ npm install openid-client@6.9.0 iron-session@9.1.0We're adding openid-client, which handles communication with our FusionAuth instance, and iron-session, which stores the logged-in user in an encrypted cookie.
-
In the
nextjs-quickstartfolder, create a file namedauth.jswith the following contents:import * as client from 'openid-client'; import { getIronSession } from 'iron-session'; import { cookies } from 'next/headers'; export const FUSIONAUTH_URL = 'http://localhost:9011'; export const CLIENT_ID = process.env.FUSIONAUTH_CLIENT_ID; export const CALLBACK_URL = process.env.FUSIONAUTH_CALLBACK_URL; // find FusionAuth's login and token endpoints in its OpenID Connect discovery document let config; export async function getConfig() { config ??= await client.discovery(new URL(FUSIONAUTH_URL), CLIENT_ID, process.env.FUSIONAUTH_CLIENT_SECRET, undefined, { execute: [client.allowInsecureRequests], // the local FusionAuth instance uses http }); return config; } // an encrypted cookie that holds the logged-in user and the PKCE code verifier export async function getSession() { return getIronSession(await cookies(), { password: process.env.SESSION_SECRET, cookieName: 'session' }); }getConfigusesclient.discoveryto find the login and token endpoints in FusionAuth's OpenID Connect discovery document at/.well-known/openid-configuration.getSessionreads the session cookie, which iron-session encrypts with theSESSION_SECRETfrom the.envfile.
-
In the
appfolder, create a folder namedlogin. In theloginfolder, create a file namedroute.jswith the following contents:import * as client from 'openid-client'; import { redirect } from 'next/navigation'; import { CALLBACK_URL, getConfig, getSession } from '../../auth'; export async function GET() { const session = await getSession(); session.codeVerifier = client.randomPKCECodeVerifier(); await session.save(); const url = client.buildAuthorizationUrl(await getConfig(), { redirect_uri: CALLBACK_URL, scope: 'openid', code_challenge: await client.calculatePKCECodeChallenge(session.codeVerifier), code_challenge_method: 'S256', }); redirect(url.href); }The
/loginroute creates a PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges. code verifier, saves it in the session, and sends the user to the FusionAuth login page. With PKCE, the app sends the code verifier when it exchanges the authorization code for tokens, so a stolen authorization code is useless on its own. -
In the
appfolder, create a folder namedoauth-callback. In theoauth-callbackfolder, create a file namedroute.jswith the following contents:import * as client from 'openid-client'; import { redirect } from 'next/navigation'; import { CALLBACK_URL, getConfig, getSession } from '../../auth'; export async function GET(request) { const session = await getSession(); const currentUrl = new URL(request.nextUrl.pathname + request.nextUrl.search, CALLBACK_URL); // exchange the authorization code for tokens and validate the ID token const tokens = await client.authorizationCodeGrant(await getConfig(), currentUrl, { pkceCodeVerifier: session.codeVerifier, }); session.user = { id: tokens.claims().sub }; delete session.codeVerifier; await session.save(); redirect('/'); }The
/oauth-callbackroute callsauthorizationCodeGrant, which exchanges the authorization code from FusionAuth for tokens and validates the ID tokenA JSON Web Token that contains information about the authenticated user.. The app then stores the user's Id in the session. -
In the
appfolder, create a folder namedlogout. In thelogoutfolder, create a file namedroute.jswith the following contents:import { redirect } from 'next/navigation'; import { CLIENT_ID, FUSIONAUTH_URL, getSession } from '../../auth'; export async function GET() { // Clear the local session const session = await getSession(); session.destroy(); // Redirect to FusionAuth to clear the SSO session redirect(`${FUSIONAUTH_URL}/oauth2/logout?` + new URLSearchParams({ client_id: CLIENT_ID })); }The
/logoutroute clears the session, then sends the user to FusionAuth's/oauth2/logoutendpoint so the FusionAuth session ends too. -
Replace the contents of
app/page.jswith the following code:import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { revalidatePath } from 'next/cache'; import { redirect } from 'next/navigation'; import { getSession } from '../auth'; const TARGET_FILE = 'note.txt'; // require authentication to access async function requireLogin() { const session = await getSession(); if (!session.user) redirect('/login'); } async function save(formData) { 'use server'; await requireLogin(); writeFileSync(TARGET_FILE, formData.get('content')); revalidatePath('/'); // Refresh the page to show updated content } export default async function Home() { await requireLogin(); // Ensure the file exists so we don't crash if (!existsSync(TARGET_FILE)) writeFileSync(TARGET_FILE, 'Hello! Edit this text.'); const content = readFileSync(TARGET_FILE, 'utf8'); return ( <> <a href="/logout" className="logout-btn" style={{ float: 'right', background: '#dc3545', color: 'white', padding: '8px 15px', textDecoration: 'none', borderRadius: 4 }}>Logout</a> <h1>Edit: {TARGET_FILE}</h1> <form action={save}> <textarea name="content" key={content} defaultValue={content} style={{ width: '100%', height: 300, padding: 10 }} /> <br /> <button type="submit" style={{ padding: '10px 20px', background: '#007bff', color: 'white', border: 'none' }}>Save Changes</button> </form> </> ); }The
requireLoginfunction sends users who aren't logged in to/login. The page and thesaveaction both call it, because Next.js runs server actions as separate requests. -
That's it! Your Next.js app should now use FusionAuth login. Run the app:
$ npx next dev -
Open the app at http://localhost:3000.
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
Edit the text file from the safety of an authenticated Next.js app.
-
Click Logout. FusionAuth ends your session and sends you back to the login page.
Add Independent Notes for Each User#
To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:
-
Open the FusionAuth Admin UI at http://localhost:9011/admin.
-
Log in with the following credentials:
- username:
admin@example.com - password:
password
- username:
-
Navigate to Applications -> QuickStart App -> Edit -> Registration .
- Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
- In the Registration field list, turn on the Enabled and Required switches for the following rows:
- Birthdate
- First name
- Last name
-
Click the Save button in the top right of the page to save your changes to self-service registration.
-
Navigate to Users -> Richard Hendricks -> Manage .
-
In the Source tab, look for the
firstNameandlastNamefields. That's what we'll use to personalize the UI for each user. We'll use the user'sidfield to generate a unique name for each user's note. -
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Next.js app.
-
Replace the contents of
app/login/route.jswith the following code, which also requests theprofileandemailscopes:import * as client from 'openid-client'; import { redirect } from 'next/navigation'; import { CALLBACK_URL, getConfig, getSession } from '../../auth'; export async function GET() { const session = await getSession(); session.codeVerifier = client.randomPKCECodeVerifier(); await session.save(); const url = client.buildAuthorizationUrl(await getConfig(), { redirect_uri: CALLBACK_URL, scope: 'openid profile email', code_challenge: await client.calculatePKCECodeChallenge(session.codeVerifier), code_challenge_method: 'S256', }); redirect(url.href); } -
Replace the contents of
app/oauth-callback/route.jswith the following code, which reads the user's name (first and last) and email from the ID token and stores them in the session:import * as client from 'openid-client'; import { redirect } from 'next/navigation'; import { CALLBACK_URL, getConfig, getSession } from '../../auth'; export async function GET(request) { const session = await getSession(); const currentUrl = new URL(request.nextUrl.pathname + request.nextUrl.search, CALLBACK_URL); // exchange the authorization code for tokens and validate the ID token const tokens = await client.authorizationCodeGrant(await getConfig(), currentUrl, { pkceCodeVerifier: session.codeVerifier, }); const claims = tokens.claims(); const fullName = `${claims.given_name ?? ''} ${claims.family_name ?? ''}`.trim(); session.user = { id: claims.sub, email: claims.email, name: fullName || claims.email || 'User' }; delete session.codeVerifier; await session.save(); redirect('/'); }openid-client validates the ID token and
tokens.claims()returns its claims, so we don't need a separate JWT library. -
Replace the contents of
app/logout/route.jswith the following code, which passes apost_logout_redirect_urito send the user back to the login page after FusionAuth ends their session:import { redirect } from 'next/navigation'; import { CLIENT_ID, FUSIONAUTH_URL, getSession } from '../../auth'; export async function GET() { // Clear the local session const session = await getSession(); session.destroy(); // Redirect to FusionAuth to clear the SSO session redirect(`${FUSIONAUTH_URL}/oauth2/logout?` + new URLSearchParams({ client_id: CLIENT_ID, post_logout_redirect_uri: 'http://localhost:3000/login', })); } -
Replace the contents of
app/page.jswith the following code, which stores each user's note in a separate file:import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { revalidatePath } from 'next/cache'; import { redirect } from 'next/navigation'; import { getSession } from '../auth'; // set up a directory for multi-user files const DATA_DIR = 'user_data'; mkdirSync(DATA_DIR, { recursive: true }); // require authentication to access async function requireLogin() { const session = await getSession(); if (!session.user) redirect('/login'); return session.user; } // helper to get specific user file function getUserFile(userId) { return `${DATA_DIR}/note-${userId}.txt`; } async function save(formData) { 'use server'; const user = await requireLogin(); writeFileSync(getUserFile(user.id), formData.get('content')); revalidatePath('/'); // Refresh the page to show updated content } export default async function Home() { const user = await requireLogin(); const targetFile = getUserFile(user.id); // Ensure the file exists so we don't crash if (!existsSync(targetFile)) writeFileSync(targetFile, `Hello ${user.name}!`); const content = readFileSync(targetFile, 'utf8'); return ( <> <a href="/logout" className="logout-btn" style={{ float: 'right', background: '#dc3545', color: 'white', padding: '8px 15px', textDecoration: 'none', borderRadius: 4 }}>Logout</a> <p style={{ float: 'right', marginRight: 20 }}>Welcome, {user.name}</p> <h1>Personal Note Editor</h1> <form action={save}> <textarea name="content" key={content} defaultValue={content} style={{ width: '100%', height: 300, padding: 10 }} /> <br /> <button type="submit" style={{ padding: '10px 20px', background: '#007bff', color: 'white', border: 'none' }}>Save Changes</button> </form> </> ); } -
Open the app at http://localhost:3000. The Next.js server reloads the changed files, so you don't need to restart it.
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
In a separate private/incognito window, open the app at http://localhost:3000.
-
Click Create an account and create an account using your personal email address, name, and birthdate.
-
Enjoy using your unique user note! You should see your name at the top of the page, and in the default note text.
Your Next.js app now provides unique notes for each user. Each user can independently edit and save their note. To see all of the notes, look for note-<id>.txt files in the user_data directory. To identify which note corresponds to which user, compare the id in the file name with the id field in the user's Source tab.
Summary#
In this QuickStart, FusionAuth handled login for your Next.js app:
- openid-client sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
- The
requireLoginfunction kept logged-out users away from the notes page and thesaveaction. - The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
- FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.
Next Steps#
This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.
FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.