# FusionAuth QuickStart for Next.js

Integrate FusionAuth with an example Next.js website.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

![Next.js](https://fusionauth.io/img/icons/nextjs.svg)

This QuickStart explains how to add a login page and authentication to a website built with [Next.js](https://nextjs.org/). 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:

*   [Node.js](https://nodejs.org/en/download) 22.13 or later
*   [Docker](https://docs.docker.com/get-started/get-docker/) 23 or later

If you use macOS or Windows, you need one of the following container management tools:

*   [Docker Desktop](https://www.docker.com/products/docker-desktop/)
*   [OrbStack](https://docs.orbstack.dev/quick-start) (to use OrbStack for `docker compose` commands after installation, run `docker context use orbstack`)
*   [Podman](https://podman.io/docs/installation) (in the commands below, replace `docker` with `podman`)

## 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:

1.  Create a folder for the app and navigate into it:
    
    ```shell-session
    $ mkdir nextjs-quickstart && cd nextjs-quickstart
    ```
    
2.  Create a `package.json` file and set the project to use JavaScript modules:
    
    ```shell-session
    $ npm init -y
    ```
    
    ```shell-session
    $ npm pkg set type=module
    ```
    
3.  Install dependencies:
    
    ```shell-session
    $ npm install next@16.4.6 react@19.3.1 react-dom@19.3.1
    ```
    
4.  In the `nextjs-quickstart` folder, create a folder named `app`. In the `app` folder, create a file named `layout.js` with the following contents:
    
    ```jsx
    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>
      );
    }
    ```
    
5.  In the `app` folder, create a file named `page.js` with the following contents:
    
    ```jsx
    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.txt` and shows it in a form. When you submit the form, the `save` [server action](https://nextjs.org/docs/app/getting-started/mutating-data) writes the new text to the file.
    
6.  Run the app:
    
    ```shell-session
    $ npx next dev
    ```
    
7.  Open the app at [http://localhost:3000](http://localhost:3000).
    
8.  Replace the text area text with "Hello Next.js", then click the **Save Changes** button.
    
9.  In a file browser or terminal, look in the `nextjs-quickstart` folder. You should see a new file named `note.txt`, with text content "Hello Next.js".
    
10.  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:

1.  Open your container management tool (listed in the prerequisites above).
    
2.  From the `nextjs-quickstart` folder, clone the [GitHub repository for the FusionAuth instance you'll use with this QuickStart](https://github.com/FusionAuth/fusionauth-quickstart-app):
    
    ```shell-session
    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    ```
    
3.  Navigate into the cloned directory:
    
    ```shell-session
    $ cd fusionauth-quickstart-app
    ```
    
4.  To start a local instance of FusionAuth, run the following command (omit the `-d` flag to see all Docker logs):
    
    ```shell-session
    $ docker compose up -d
    ```
    
5.  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.
    
6.  Open [http://localhost:9011/admin](http://localhost:9011/admin) to access the FusionAuth Admin UI.
    
7.  Log in with these credentials:
    
    *   username: `admin@example.com`
    *   password: `password`
8.  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.
    
9.  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:

1.  Navigate out of the `fusionauth-quickstart-app` folder, back to the `nextjs-quickstart` folder that contains `app` and `note.txt`:
    
    ```shell-session
    $ cd ..
    ```
    
2.  Create a file named `.env` with the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):
    
    ```plaintext
    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_characters
    ```
    
    Next.js reads the `.env` file automatically when the server starts.
    
3.  Install the dependencies we'll need to authenticate with FusionAuth:
    
    ```shell-session
    $ npm install openid-client@6.9.0 iron-session@9.1.0
    ```
    
    We're adding [openid-client](https://github.com/panva/openid-client), which handles communication with our FusionAuth instance, and [iron-session](https://github.com/vvo/iron-session), which stores the logged-in user in an encrypted cookie.
    
4.  In the `nextjs-quickstart` folder, create a file named `auth.js` with the following contents:
    
    ```js
    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' });
    }
    ```
    
    *   `getConfig` uses `client.discovery` to find the login and token endpoints in FusionAuth's OpenID Connect discovery document at `/.well-known/openid-configuration`.
    *   `getSession` reads the session cookie, which iron-session encrypts with the `SESSION_SECRET` from the `.env` file.
5.  In the `app` folder, create a folder named `login`. In the `login` folder, create a file named `route.js` with the following contents:
    
    ```js
    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 `/login` route creates a [PKCE](https://fusionauth.io/docs/authentication/oauth/authorization-code.md#proof-key-for-code-exchange) 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.
    
6.  In the `app` folder, create a folder named `oauth-callback`. In the `oauth-callback` folder, create a file named `route.js` with the following contents:
    
    ```js
    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-callback` route calls `authorizationCodeGrant`, which exchanges the authorization code from FusionAuth for tokens and validates the [ID token](https://fusionauth.io/docs/authentication/oauth/tokens.md#id-token). The app then stores the user's Id in the session.
    
7.  In the `app` folder, create a folder named `logout`. In the `logout` folder, create a file named `route.js` with the following contents:
    
    ```js
    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 `/logout` route clears the session, then sends the user to FusionAuth's `/oauth2/logout` endpoint so the FusionAuth session ends too.
    
8.  Replace the contents of `app/page.js` with the following code:
    
    ```jsx
    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 `requireLogin` function sends users who aren't logged in to `/login`. The page and the `save` action both call it, because Next.js runs server actions as separate requests.
    
9.  That's it! Your Next.js app should now use FusionAuth login. Run the app:
    
    ```shell-session
    $ npx next dev
    ```
    
10.  Open the app at [http://localhost:3000](http://localhost:3000).
     
11.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
12.  Edit the text file from the safety of an authenticated Next.js app.
     
13.  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:

1.  Open the FusionAuth Admin UI at [http://localhost:9011/admin](http://localhost:9011/admin).
    
2.  Log in with the following credentials:
    
    *   username: `admin@example.com`
    *   password: `password`
3.  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**
4.  Click the **Save** button in the top right of the page to save your changes to self-service registration.
    
5.  Navigate to Users -> Richard Hendricks -> Manage .
    
6.  In the **Source** tab, look for the `firstName` and `lastName` fields. That's what we'll use to personalize the UI for each user. We'll use the user's `id` field to generate a unique name for each user's note.
    
7.  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.
    
8.  Replace the contents of `app/login/route.js` with the following code, which also requests the `profile` and `email` scopes:
    
    ```js
    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);
    }
    ```
    
9.  Replace the contents of `app/oauth-callback/route.js` with the following code, which reads the user's name (first and last) and email from the ID token and stores them in the session:
    
    ```js
    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.
    
10.  Replace the contents of `app/logout/route.js` with the following code, which passes a `post_logout_redirect_uri` to send the user back to the login page after FusionAuth ends their session:
     
     ```js
     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',
       }));
     }
     ```
     
11.  Replace the contents of `app/page.js` with the following code, which stores each user's note in a separate file:
     
     ```jsx
     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>
         </>
       );
     }
     ```
     
12.  Open the app at [http://localhost:3000](http://localhost:3000). The Next.js server reloads the changed files, so you don't need to restart it.
     
13.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
14.  *In a separate private/incognito window*, open the app at [http://localhost:3000](http://localhost:3000).
     
15.  Click **Create an account** and create an account using your personal email address, name, and birthdate.
     
16.  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 `requireLogin` function kept logged-out users away from the notes page and the `save` action.
*   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](https://fusionauth.io/docs/get-started.md).

FusionAuth has many features (including [Social Login](https://fusionauth.io/docs/authentication/identity-providers.md#social-identity-providers), [Single Sign-On](https://fusionauth.io/docs/authentication/sessions/enable-sso.md), [Passkeys](https://fusionauth.io/docs/authentication/passkeys/configure.md), [Multi-factor Authentication](https://fusionauth.io/docs/authentication/multi-factor-authentication.md)), most of which are free. This example app is a great starting point for learning about FusionAuth features.
---

## Other pages in Web

> For the full index of this section, see [Quickstarts](https://fusionauth.io/docs/llms-quickstarts.txt).

- [FusionAuth QuickStart for Python Django](https://fusionauth.io/docs/quickstarts/web/django.md): Integrate FusionAuth with an example Python Django website.
- [FusionAuth QuickStart for Express](https://fusionauth.io/docs/quickstarts/web/express.md): Integrate FusionAuth with an example Express website.
- [Web](https://fusionauth.io/docs/quickstarts/web.md): Explore step-by-step web application QuickStart guides from FusionAuth to seamlessly integrate authentication into your application.
- [FusionAuth QuickStart for .NET](https://fusionauth.io/docs/quickstarts/web/quickstart-dotnet-web.md): QuickStart integration of .NET web application with FusionAuth.
- [FusionAuth QuickStart for Golang](https://fusionauth.io/docs/quickstarts/web/quickstart-golang-web.md): QuickStart integration of a Golang web application with FusionAuth using the CoreOS OIDC library.
- [FusionAuth QuickStart for Spring Boot With Thymeleaf](https://fusionauth.io/docs/quickstarts/web/quickstart-java-springboot-web.md): QuickStart integration of a Spring Boot web application using Thymeleaf with FusionAuth.
- [FusionAuth QuickStart for Nuxt](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-nuxt-web.md): QuickStart integration of a Nuxt web application with FusionAuth.
- [FusionAuth QuickStart for Remix](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-remix-web.md): QuickStart integration of Javascript Remix web application with FusionAuth.
- [FusionAuth QuickStart for Drupal](https://fusionauth.io/docs/quickstarts/web/quickstart-php-drupal-web.md): QuickStart integration of Drupal web application with FusionAuth.
- [FusionAuth QuickStart for Laravel](https://fusionauth.io/docs/quickstarts/web/quickstart-php-laravel-web.md): QuickStart integration of PHP Laravel web application with FusionAuth.
- [FusionAuth QuickStart for PHP](https://fusionauth.io/docs/quickstarts/web/quickstart-php-web.md): QuickStart integration of PHP web application with FusionAuth.
- [FusionAuth QuickStart for Python Flask](https://fusionauth.io/docs/quickstarts/web/quickstart-python-flask-web.md): QuickStart integration of Python Flask web application with FusionAuth.
- [FusionAuth QuickStart for Ruby on Rails](https://fusionauth.io/docs/quickstarts/web/quickstart-ruby-rails-web.md): QuickStart integration of Ruby on Rails web application with FusionAuth.
- [FusionAuth QuickStart for Rust with Actix](https://fusionauth.io/docs/quickstarts/web/quickstart-rust-actix-web.md): QuickStart integration of a Rust Actix web application with FusionAuth.
- [FusionAuth QuickStart for WordPress](https://fusionauth.io/docs/quickstarts/web/quickstart-wordpress-web.md): QuickStart integration of WordPress application with FusionAuth.
