# FusionAuth QuickStart for Nuxt

Integrate FusionAuth with an example Nuxt website.

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

![Nuxt](https://fusionauth.io/img/icons/nuxt.svg)

This QuickStart explains how to add a login page and authentication to a website built with [Nuxt](https://nuxt.com/). You'll begin with a simple Nuxt 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) 24.15 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 Nuxt App

For this QuickStart, we'll use a Nuxt app that reads and writes data to a text file:

1.  Create a folder for the app and navigate into it:
    
    ```shell-session
    $ mkdir nuxt-quickstart && cd nuxt-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 nuxt@4.6.4 vue@3.5.45
    ```
    
4.  In the `nuxt-quickstart` folder, create a folder named `app`. In the `app` folder, create a file named `app.vue` with the following contents:
    
    ```markup
    <script setup>
    const { data } = await useFetch('/api/note');
    </script>
    
    <template>
      <h1>Edit: note.txt</h1>
      <form method="POST" action="/api/note">
        <textarea name="content" :value="data.content" style="width: 100%; height: 300px; padding: 10px" />
        <br />
        <button type="submit" style="padding: 10px 20px; background: #007bff; color: white; border: none">Save Changes</button>
      </form>
    </template>
    ```
    
    When the page renders, `useFetch` loads the note from the `/api/note` route. The form sends the new text back to the same route.
    
5.  In the `nuxt-quickstart` folder, create a folder named `server`. In the `server` folder, create a folder named `api`. In the `api` folder, create a file named `note.get.js` with the following contents:
    
    ```js
    import { existsSync, readFileSync, writeFileSync } from 'node:fs';
    
    const TARGET_FILE = 'note.txt';
    
    export default defineEventHandler(() => {
      // Ensure the file exists so we don't crash
      if (!existsSync(TARGET_FILE)) writeFileSync(TARGET_FILE, 'Hello! Edit this text.');
      return { content: readFileSync(TARGET_FILE, 'utf8') };
    });
    ```
    
6.  In the `api` folder, create a file named `note.post.js` with the following contents:
    
    ```js
    import { writeFileSync } from 'node:fs';
    
    const TARGET_FILE = 'note.txt';
    
    export default defineEventHandler(async (event) => {
      const { content } = await readBody(event);
      writeFileSync(TARGET_FILE, content);
      return sendRedirect(event, '/'); // Refresh the page to show updated content
    });
    ```
    
    Nuxt turns each file in `server/api` into a [server route](https://nuxt.com/docs/4.x/directory-structure/server). The `.get` and `.post` suffixes set the HTTP method, so `note.get.js` reads the note and `note.post.js` saves it, both at `/api/note`.
    
7.  Run the app:
    
    ```shell-session
    $ npx nuxt dev
    ```
    
8.  Open the app at [http://localhost:3000](http://localhost:3000).
    
9.  Replace the text area text with "Hello Nuxt", then click the **Save Changes** button.
    
10.  In a file browser or terminal, look in the `nuxt-quickstart` folder. You should see a new file named `note.txt`, with text content "Hello Nuxt".
     
11.  Congratulations, you have a working Nuxt app that lets you edit a local text file through your web browser. Press **Ctrl+C** on your keyboard to stop the Nuxt server.
     

## Install and Run FusionAuth

Before we can add authentication to our Nuxt app, we need a local FusionAuth instance:

1.  Open your container management tool (listed in the prerequisites above).
    
2.  From the `nuxt-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 Nuxt 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 Nuxt 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 Nuxt App

Now that you have a working instance of FusionAuth and a working Nuxt app, let's use FusionAuth to add login to your Nuxt app:

1.  Navigate out of the `fusionauth-quickstart-app` folder, back to the `nuxt-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
    ```
    
    Nuxt reads the `.env` file automatically when the development server starts.
    
3.  Install the dependency we'll need to authenticate with FusionAuth:
    
    ```shell-session
    $ npm install openid-client@6.9.0
    ```
    
    [openid-client](https://github.com/panva/openid-client) handles communication with our FusionAuth instance. We don't need a session library, because Nuxt's server includes `useSession`, which stores the session in an encrypted cookie.
    
4.  In the `server` folder, create a folder named `utils`. In the `utils` folder, create a file named `auth.js` with the following contents:
    
    ```js
    import * as client from 'openid-client';
    
    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 function getUserSession(event) {
      return useSession(event, { password: process.env.SESSION_SECRET, name: 'session' });
    }
    ```
    
    Nuxt makes everything exported from `server/utils` available in the other server files without an import.
    
    *   `getConfig` uses `client.discovery` to find the login and token endpoints in FusionAuth's OpenID Connect discovery document at `/.well-known/openid-configuration`.
    *   `getUserSession` reads the session cookie, which `useSession` encrypts with the `SESSION_SECRET` from the `.env` file.
5.  In the `server` folder, create a folder named `routes`. In the `routes` folder, create a file named `login.get.js` with the following contents:
    
    ```js
    import * as client from 'openid-client';
    
    export default defineEventHandler(async (event) => {
      const session = await getUserSession(event);
      const codeVerifier = client.randomPKCECodeVerifier();
      await session.update({ codeVerifier });
    
      const url = client.buildAuthorizationUrl(await getConfig(), {
        redirect_uri: CALLBACK_URL,
        scope: 'openid',
        code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
        code_challenge_method: 'S256',
      });
      return sendRedirect(event, url.href);
    });
    ```
    
    Files in `server/routes` become routes without the `/api` prefix, so this file handles `/login`. The 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 `routes` folder, create a file named `oauth-callback.get.js` with the following contents:
    
    ```js
    import * as client from 'openid-client';
    
    export default defineEventHandler(async (event) => {
      const session = await getUserSession(event);
      const currentUrl = new URL(event.path, CALLBACK_URL);
    
      // exchange the authorization code for tokens and validate the ID token
      const tokens = await client.authorizationCodeGrant(await getConfig(), currentUrl, {
        pkceCodeVerifier: session.data.codeVerifier,
      });
    
      await session.update({ user: { id: tokens.claims().sub }, codeVerifier: undefined });
      return sendRedirect(event, '/');
    });
    ```
    
    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 `routes` folder, create a file named `logout.get.js` with the following contents:
    
    ```js
    export default defineEventHandler(async (event) => {
      // Clear the local session
      const session = await getUserSession(event);
      await session.clear();
    
      // Redirect to FusionAuth to clear the SSO session
      return sendRedirect(event, `${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.  In the `server` folder, create a folder named `middleware`. In the `middleware` folder, create a file named `auth.js` with the following contents:
    
    ```js
    // require authentication to access everything except the login routes
    const PUBLIC_PATHS = ['/login', '/oauth-callback'];
    
    export default defineEventHandler(async (event) => {
      if (PUBLIC_PATHS.includes(getRequestURL(event).pathname)) return;
    
      const session = await getUserSession(event);
      if (!session.data.user) return sendRedirect(event, '/login');
    });
    ```
    
    Nuxt runs server middleware on every request before the route handler. This middleware sends users who aren't logged in to `/login`, which protects both the page and the `/api/note` routes.
    
9.  Replace the contents of `app/app.vue` with the following code, which adds a **Logout** button:
    
    ```markup
    <script setup>
    const { data } = await useFetch('/api/note');
    </script>
    
    <template>
      <a href="/logout" class="logout-btn" style="float: right; background: #dc3545; color: white; padding: 8px 15px; text-decoration: none; border-radius: 4px">Logout</a>
      <h1>Edit: note.txt</h1>
      <form method="POST" action="/api/note">
        <textarea name="content" :value="data.content" style="width: 100%; height: 300px; padding: 10px" />
        <br />
        <button type="submit" style="padding: 10px 20px; background: #007bff; color: white; border: none">Save Changes</button>
      </form>
    </template>
    ```
    
10.  That's it! Your Nuxt app should now use FusionAuth login. Run the app:
     
     ```shell-session
     $ npx nuxt dev
     ```
     
11.  Open the app at [http://localhost:3000](http://localhost:3000).
     
12.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
13.  Edit the text file from the safety of an authenticated Nuxt app.
     
14.  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 Nuxt app.
    
8.  Replace the contents of `server/routes/login.get.js` with the following code, which also requests the `profile` and `email` scopes:
    
    ```js
    import * as client from 'openid-client';
    
    export default defineEventHandler(async (event) => {
      const session = await getUserSession(event);
      const codeVerifier = client.randomPKCECodeVerifier();
      await session.update({ codeVerifier });
    
      const url = client.buildAuthorizationUrl(await getConfig(), {
        redirect_uri: CALLBACK_URL,
        scope: 'openid profile email',
        code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
        code_challenge_method: 'S256',
      });
      return sendRedirect(event, url.href);
    });
    ```
    
9.  Replace the contents of `server/routes/oauth-callback.get.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';
    
    export default defineEventHandler(async (event) => {
      const session = await getUserSession(event);
      const currentUrl = new URL(event.path, CALLBACK_URL);
    
      // exchange the authorization code for tokens and validate the ID token
      const tokens = await client.authorizationCodeGrant(await getConfig(), currentUrl, {
        pkceCodeVerifier: session.data.codeVerifier,
      });
    
      const claims = tokens.claims();
      const fullName = `${claims.given_name ?? ''} ${claims.family_name ?? ''}`.trim();
      const user = { id: claims.sub, email: claims.email, name: fullName || claims.email || 'User' };
      await session.update({ user, codeVerifier: undefined });
      return sendRedirect(event, '/');
    });
    ```
    
    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 `server/routes/logout.get.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
     export default defineEventHandler(async (event) => {
       // Clear the local session
       const session = await getUserSession(event);
       await session.clear();
     
       // Redirect to FusionAuth to clear the SSO session
       return sendRedirect(event, `${FUSIONAUTH_URL}/oauth2/logout?` + new URLSearchParams({
         client_id: CLIENT_ID,
         post_logout_redirect_uri: 'http://localhost:3000/login',
       }));
     });
     ```
     
11.  In the `server/utils` folder, create a file named `notes.js` with the following contents, which gives each user a separate note file:
     
     ```js
     import { mkdirSync } from 'node:fs';
     
     // set up a directory for multi-user files
     const DATA_DIR = 'user_data';
     mkdirSync(DATA_DIR, { recursive: true });
     
     // helper to get specific user file
     export function getUserFile(userId) {
       return `${DATA_DIR}/note-${userId}.txt`;
     }
     ```
     
12.  Replace the contents of `server/api/note.get.js` with the following code, which reads the logged-in user's note and returns their name with it:
     
     ```js
     import { existsSync, readFileSync, writeFileSync } from 'node:fs';
     
     export default defineEventHandler(async (event) => {
       const { user } = (await getUserSession(event)).data;
       const targetFile = getUserFile(user.id);
     
       // Ensure the file exists so we don't crash
       if (!existsSync(targetFile)) writeFileSync(targetFile, `Hello ${user.name}!`);
       return { name: user.name, content: readFileSync(targetFile, 'utf8') };
     });
     ```
     
13.  Replace the contents of `server/api/note.post.js` with the following code, which saves the note to the logged-in user's file:
     
     ```js
     import { writeFileSync } from 'node:fs';
     
     export default defineEventHandler(async (event) => {
       const { user } = (await getUserSession(event)).data;
       const { content } = await readBody(event);
       writeFileSync(getUserFile(user.id), content);
       return sendRedirect(event, '/'); // Refresh the page to show updated content
     });
     ```
     
14.  Replace the contents of `app/app.vue` with the following code, which shows the user's name:
     
     ```markup
     <script setup>
     const { data } = await useFetch('/api/note');
     </script>
     
     <template>
       <a href="/logout" class="logout-btn" style="float: right; background: #dc3545; color: white; padding: 8px 15px; text-decoration: none; border-radius: 4px">Logout</a>
       <p style="float: right; margin-right: 20px">Welcome, {{ data.name }}</p>
       <h1>Personal Note Editor</h1>
       <form method="POST" action="/api/note">
         <textarea name="content" :value="data.content" style="width: 100%; height: 300px; padding: 10px" />
         <br />
         <button type="submit" style="padding: 10px 20px; background: #007bff; color: white; border: none">Save Changes</button>
       </form>
     </template>
     ```
     
15.  Open the app at [http://localhost:3000](http://localhost:3000). The Nuxt server reloads the changed files, so you don't need to restart it.
     
16.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
17.  *In a separate private/incognito window*, open the app at [http://localhost:3000](http://localhost:3000).
     
18.  Click **Create an account** and create an account using your personal email address, a password, your name, and your birthdate.
     
19.  Enjoy using your unique user note! You should see your name at the top of the page, and in the default note text.
     

Your Nuxt 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 Nuxt 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 server middleware kept logged-out users away from the notes page and the `/api/note` routes.
*   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.
- [FusionAuth QuickStart for Python Flask](https://fusionauth.io/docs/quickstarts/web/flask.md): Integrate FusionAuth with an example Python Flask 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 Next.js](https://fusionauth.io/docs/quickstarts/web/nextjs.md): Integrate FusionAuth with an example Next.js website.
- [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 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 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.
