FusionAuth QuickStart for Nuxt
On this page
This QuickStart explains how to add a login page and authentication to a website built with Nuxt. 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:
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 Nuxt App#
For this QuickStart, we'll use a Nuxt app that reads and writes data to a text file:
-
Create a folder for the app and navigate into it:
$ mkdir nuxt-quickstart && cd nuxt-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 nuxt@4.6.4 vue@3.5.45 -
In the
nuxt-quickstartfolder, create a folder namedapp. In theappfolder, create a file namedapp.vuewith the following contents:<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,
useFetchloads the note from the/api/noteroute. The form sends the new text back to the same route. -
In the
nuxt-quickstartfolder, create a folder namedserver. In theserverfolder, create a folder namedapi. In theapifolder, create a file namednote.get.jswith the following contents: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') }; }); -
In the
apifolder, create a file namednote.post.jswith the following contents: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/apiinto a server route. The.getand.postsuffixes set the HTTP method, sonote.get.jsreads the note andnote.post.jssaves it, both at/api/note. -
Run the app:
$ npx nuxt dev -
Open the app at http://localhost:3000.
-
Replace the text area text with "Hello Nuxt", then click the Save Changes button.
-
In a file browser or terminal, look in the
nuxt-quickstartfolder. You should see a new file namednote.txt, with text content "Hello Nuxt". -
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:
-
Open your container management tool (listed in the prerequisites above).
-
From the
nuxt-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 Nuxt 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 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:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to thenuxt-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_charactersNuxt reads the
.envfile automatically when the development server starts. -
Install the dependency we'll need to authenticate with FusionAuth:
$ npm install openid-client@6.9.0openid-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. -
In the
serverfolder, create a folder namedutils. In theutilsfolder, create a file namedauth.jswith the following contents: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/utilsavailable in the other server files without an import.getConfigusesclient.discoveryto find the login and token endpoints in FusionAuth's OpenID Connect discovery document at/.well-known/openid-configuration.getUserSessionreads the session cookie, whichuseSessionencrypts with theSESSION_SECRETfrom the.envfile.
-
In the
serverfolder, create a folder namedroutes. In theroutesfolder, create a file namedlogin.get.jswith the following contents: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/routesbecome routes without the/apiprefix, so this file handles/login. The route 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
routesfolder, create a file namedoauth-callback.get.jswith the following contents: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-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
routesfolder, create a file namedlogout.get.jswith the following contents: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
/logoutroute clears the session, then sends the user to FusionAuth's/oauth2/logoutendpoint so the FusionAuth session ends too. -
In the
serverfolder, create a folder namedmiddleware. In themiddlewarefolder, create a file namedauth.jswith the following contents:// 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/noteroutes. -
Replace the contents of
app/app.vuewith the following code, which adds a Logout button:<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> -
That's it! Your Nuxt app should now use FusionAuth login. Run the app:
$ npx nuxt 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 Nuxt 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 Nuxt app.
-
Replace the contents of
server/routes/login.get.jswith the following code, which also requests theprofileandemailscopes: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); }); -
Replace the contents of
server/routes/oauth-callback.get.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'; 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. -
Replace the contents of
server/routes/logout.get.jswith the following code, which passes apost_logout_redirect_urito send the user back to the login page after FusionAuth ends their session: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', })); }); -
In the
server/utilsfolder, create a file namednotes.jswith the following contents, which gives each user a separate note file: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`; } -
Replace the contents of
server/api/note.get.jswith the following code, which reads the logged-in user's note and returns their name with it: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') }; }); -
Replace the contents of
server/api/note.post.jswith the following code, which saves the note to the logged-in user's file: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 }); -
Replace the contents of
app/app.vuewith the following code, which shows the user's name:<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> -
Open the app at http://localhost:3000. The Nuxt 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, a password, your name, and your 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 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/noteroutes. - 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.