
Authentication is a vital component of modern web applications, ensuring that users can access their data securely while performing authorized actions. Nuxt.js, a significant framework built on Vue.js as its fundamental pillar, provides several methods to handle authentication, including the use of modules like nuxt-auth or nuxt-auth-utils, as well as the use of middleware to control access to different routes. For Vue.js development companies, implementing secure and efficient authentication mechanisms is essential for building reliable applications.
One of the most efficient ways to implement authentication in a Nuxt 3 application is by using the @sidebase/nuxt-auth module. By the end of this guide, you will have a thorough understanding of how to set up authentication with the @sidebase/nuxt-auth module, enabling you to build a secure and user-friendly application.
1. Nuxt Auth Overview
Nuxt Auth is an authentication module for Nuxt.js that simplifies the integration of user authentication into Nuxt applications. It allows you to easily manage authentication flows such as session management, login, and registration. Serving as a wrapper around the popular NextAuth.js library, it offers a seamless and native experience for Nuxt 3 developers. Built on top of the nuxtjs/auth module, it provides a flexible and extensible approach to handling user authentication and authorization.
2. Features of Nuxt Auth
The following are the key features of Nuxt Auth:
- Multiple Authentication Providers: Supports OAuth providers like Google, GitHub, and Facebook, as well as credentials-based authentication (email/password) out of the box.
- Session Management: Automatically manages user sessions and securely stores authentication tokens. It handles session expiry and refreshes tokens as needed to maintain secure and continuous access.
- Middleware for Protected Routes: Nuxt Auth can automatically apply middleware to protect specific pages or routes, ensuring that only authenticated users can access them.
- Built-in Token Management: Nuxt Auth handles storing and refreshing access tokens, making it easier to manage tokens such as JWT (JSON Web Tokens).
- TypeScript Support: Nuxt Auth offers full TypeScript support, providing type safety and autocompletion for configurations and authentication workflows. This enhances the development experience by integrating seamlessly with Nuxt 3’s TypeScript setup.
- Hybrid Rendering: Supports hybrid rendering methods, including (SSR/CSR/SWR/Prerendering), providing flexibility in rendering modes.
- Server-Side Authentication: Allows you to protect server routes and APIs by ensuring that only authenticated users can access specific resources.
3. When to Use @sidebase/nuxt-auth?
The following are the scenarios to consider before moving to authentication using @sidebase/nuxt-auth module:
- If you have specific authentication flow requirements or need to adapt the system for your backend, @sidebase/nuxt-auth is highly configurable to suit diverse use cases.
- If you need to secure frontend routes, @sidebase/nuxt-auth helps restrict access to protected pages based on user authentication. It also facilitates handling authentication on both the client and server sides.
- If you want a modular and extensible authentication solution tailored for Nuxt.js, that allows easy integration and customization.
- If your application requires token-based authentication (like JWT), this module efficiently manages the process of exchanging tokens with your backend.
4. Implementation of Nuxt Auth
Follow these steps to implement your Nuxt Auth:
4.1 Prerequisites
- To get started, you need to have Node.js installed on your machine.
- Having a basic understanding of Vue.js and Nuxt.js will also help you follow along more easily.
4.2 Create a New Nuxt.js Application
Start by creating a new folder for your project, for example, on your desktop, then open your terminal and navigate to that directory using command-line navigation.
Open your terminal and run the following command. You can replace ‘my-app’ with any project name of your choice.
Command:
npx create-nuxt-app demo-nuxt-authentication |
After running the command, the CLI will guide you through a series of configuration prompts. Simply answer each question based on your project needs and customize the setup according to your preferences.
Navigate to the directory of your newly created project using the following command:
Command:
cd demo-nuxt-authentication |
Folder structure:

Example: Building a basic dashboard interface within the application.
Delete the current content inside app.vue and insert <NuxtPage /> in its place.
<br>Create a new file /pages/dashboard.vue<br> |
Start your application by executing this command.
Command:
npm run dev |
After the command executes successfully, open your browser and navigate to http://localhost:3000/dashboard to access the dashboard page.

4.3 Install the nuxt-auth Module
We’re using the @sidebase/nuxt-auth module to handle authentication in our Nuxt application.
You can install NuxtAuth by running the appropriate command using nuxi, Nuxt’s command-line tool:
Command:
- Using npm:
npx nuxi module add sidebase-auth
- Using pnpm:
pnpm exec nuxi module add sidebase-auth
- Using yarn:
<strong></strong>yarn dlx nuxi module add sidebase-auth
Manual Installation
- Using npm:
npm i -D @sidebase/nuxt-auth
- Using pnpm:
pnpm i -D @sidebase/nuxt-auth
- Using yarn:
yarn add -D @sidebase/nuxt-auth
4.4 Add nuxt-auth to nuxt.config.ts
export default defineNuxtConfig({ compatibilityDate: '2024-11-01', devtools: { enabled: true }, modules: ['@sidebase/nuxt-auth'] }) |
4.5 More Configs on nuxt.config.ts
You can customize NuxtAuth easily by setting various configuration options directly in your nuxt.config.ts file, giving you the flexibility to tailor authentication to your app’s needs.
The example below demonstrates how to set up and configure an authentication provider using auth.js in a Nuxt 3 project.
export default defineNuxtConfig({ compatibilityDate: "2024-11-01", devtools: { enabled: true }, modules: ["@sidebase/nuxt-auth"], auth: { isEnabled: true, disableServerSideAuth: false, originEnvKey: "AUTH_ORIGIN", baseURL: "http://localhost:5000/api", provider: { /* your provider config */ }, sessionRefresh: { enablePeriodically: false, enableOnWindowFocus: false, }, }, }); |
Let’s understand the configuration parameters mentioned in the above code:
- isEnabled: Specifies whether the NuxtAuth module is enabled. Set it to true to activate authentication features.
- originEnvKey: Specifies the environment variable that sets your app’s origin (including domain and protocol). This value is used to identify the origin in production. By default, it checks for AUTH_ORIGIN or runtimeConfig.authOrigin.
- disableServerSideAuth: When this option is enabled, the server consistently returns a “loading” state for authentication. This requires the client to fetch the session manually, which helps prevent caching user-specific session data. This setting is especially useful if your app uses caching systems. You can apply this option to specific routes using routeRules for more precise control.
- baseURL: Sets the complete base URL for authentication routes. This is only required if you choose to define it yourself instead of using the default value.
- Provider: Configure the authentication method for your app. Available options include:
- AuthJS: Perfect for configuring OAuth and Magic Link authentication methods.
- Local: It integrates smoothly with the custom authentication system using username and password.
- sessionRefresh: Controls the process of refreshing sessions on the client side
- enablePeriodically: Automatically refresh the session at specified intervals if it exists. You can set a number (e.g., 60000 for 60 seconds) or use true (which defaults to refreshing every second). Set it to false to disable automatic refresh.
- enableOnWindowFocus: If set to true, the session will be refreshed whenever the browser window gains focus.
4.5.1 Choosing the Right Provider
The ideal authentication provider for your project depends on your specific requirements. Read the overview below to help you choose the most suitable authentication provider:
- Auth.js is a great choice if you need a plug-and-play solution for OAuth with major providers like Google or GitHub. It also allows you to set up Magic Link login with minimal configuration.
- The local provider is ideal if you have an existing backend that manages username and password logins, or if you’re creating a static application. Starting from version 0.9.0, it also supports refresh tokens.
This guide shows how to set up @sidebase/nuxt-auth using the Local Provider, which is a good choice if you have an existing backend that manages username and password authentication, or if you’re building a static app. Starting from version 0.9.0, the Local Provider also supports refresh tokens.
Configuration:
The complete setup for the Local Provider is specified in the nuxt.config.ts file. Within the auth settings, just assign the provider to local.
export default defineNuxtConfig({ compatibilityDate: "2024-11-01", devtools: { enabled: true }, modules: ["@sidebase/nuxt-auth"], auth: { isEnabled: true, disableServerSideAuth: false, originEnvKey: "AUTH_ORIGIN", baseURL: "http://localhost:5000/api", provider: { type: "local", }, sessionRefresh: { enablePeriodically: false, enableOnWindowFocus: false, }, }, }); |
4.5.2 API Endpoints
You can define the endpoints to which you should send authentication requests.
export default defineNuxtConfig({ compatibilityDate: "2024-11-01", devtools: { enabled: true }, modules: ["@sidebase/nuxt-auth"], auth: { isEnabled: true, disableServerSideAuth: false, originEnvKey: "AUTH_ORIGIN", baseURL: "http://localhost:5000/api", provider: { type: "local", endpoints: { signIn: { path: "/auth/sign-in", method: "post" }, signOut: { path: "/auth/logout", method: "get" }, signUp: { path: "/auth/sign-up", method: "post" }, getSession: { path: "/users/me", method: "get" }, }, }, sessionRefresh: { enablePeriodically: false, enableOnWindowFocus: false, }, }, }); |
Authentication endpoints are set up as objects that include a path and an HTTP method. When a user takes an action, a request is sent to the matching endpoint. For instance, calling the getSession endpoint sends a request with a token included in the headers. You can customize both the headers and token behavior as needed.
In the given example, the baseURL is assigned using a runtime configuration value specified by originEnvKey, which produces request URLs like this:
- Sign In: /api/auth/login (POST)
- Sign Out: /api/auth/logout (POST)
- Sign Up: /api/auth/register (POST)
- Get Session: /api/auth/session (GET)
You can fully customize these endpoints or disable any that you don’t need by setting them to false. For instance, if your app doesn’t require user registration, you can disable the signUp endpoint.
provider: { type: "local", endpoints: { signIn: { path: "/auth/sign-in", method: "post" }, signOut: { path: "/auth/logout", method: "get" }, signUp: false, getSession: { path: "/users/me", method: "get" }, }, }, |
4.5.3 Connecting to an External Backend
You can configure your authentication endpoints to communicate with an external backend instead of relying on your local server.
provider: { type: "local", endpoints: { signIn: { path: "/auth/sign-in", method: "post" }, signOut: { path: "/auth/logout", method: "get" }, signUp: { path: "/auth/sign-up", method: "post" }, getSession: { path: "/users/me", method: "get" }, }, }, |
4.5.4 Token Handling
Both the Local and Refresh providers work by exchanging access tokens with your backend server. When a user logs in, the sign-in endpoint should respond with an access token. NextAuth then stores this token in the session and uses it to authenticate subsequent requests, including those made to retrieve the current session using getSession.
Your configuration of token settings will vary based on your backend’s implementation and how it delivers token data. NextAuth is designed to be highly flexible, allowing integration with various backend systems and token formats.
provider: { type: "local", endpoints: { signIn: { path: "/auth/sign-in", method: "post" }, signOut: { path: "/auth/logout", method: "get" }, signUp: { path: "/auth/sign-up", method: "post" }, getSession: { path: "/users/me", method: "get" }, }, token: { signInResponseTokenPointer: "/data/tokens/access_token", }, }, |
SignInResponseTokenPointer specifies how NuxtAuth should locate and extract the authentication token from the response returned by your signIn endpoint.
NuxtAuth will use the specified path to locate and store the token within the session.
4.5.5 Refresh Configuration
NuxtAuth lets you configure a dedicated refresh token setup, giving you control over how refresh tokens are managed. This allows you to customize the refresh process and token format to suit the specific needs of your backend system.
provider: { type: "local", endpoints: { signIn: { path: "/auth/sign-in", method: "post" }, signOut: { path: "/auth/logout", method: "get" }, signUp: { path: "/auth/sign-up", method: "post" }, getSession: { path: "/users/me", method: "get" }, }, token: { signInResponseTokenPointer: "/data/tokens/access_token", }, refresh: { isEnabled: true, endpoint: { path: "/auth/refresh", method: "post" }, refreshOnlyToken: true, token: { signInResponseRefreshTokenPointer: "/data/tokens/refresh_token", refreshResponseTokenPointer: "/data/token", cookieName: "auth.refreshToken", secureCookieAttribute: false, httpOnlyCookieAttribute: false, }, }, }, |
isEnabled:
The isEnabled option within the refresh configuration determines whether NextAuth should automatically use a refresh token to obtain a new access token. This approach is commonly used in modern authentication workflows to maintain user sessions without requiring users to log in frequently.
endpoint (Refresh Token Endpoint):
This setting specifies the API route that NuxtAuth uses to obtain a new access token when the current one is about to expire, by using the refresh token.
refreshOnlyToken:
The refreshOnlyToken option determines whether only the access token should be updated during a refresh request, leaving the refresh token untouched. This is particularly useful when your backend issues the refresh token only once at login and doesn’t require it to be regenerated afterward.
Example:
If your backend provides a new access token with each refresh but only includes the refresh token during the initial login, you should set refreshOnlyToken to true:
refreshOnlyToken: true |
This ensures that only the access token is renewed, while the refresh token stays the same.
Option to Disable:
If you want both the access token and the refresh token to be updated simultaneously during a refresh request, you can enable this by setting:
refreshOnlyToken: false |
This allows NuxtAuth to refresh both the access token and the refresh token each time a refresh request is made.
4.5.6 Token:
signInResponseRefreshTokenPointer
The signInResponseRefreshTokenPointer tells NuxtAuth how to locate the refresh token within the response returned by the sign-in endpoint. When a user logs in, the backend usually includes both an access token and a refresh token in the response. This option ensures that NextAuth can correctly extract and store the refresh token for later use.
How it Works:
NuxtAuth looks for the refresh token in a specific location within the response returned after signing in. The signInResponseRefreshTokenPointer tells NextAuth exactly where to find the refresh token in that response object.
As an illustration, suppose the response object returned by the sign-in endpoint is structured like this:
{ "token": { "refreshToken": "YOUR_REFRESH_TOKEN", "accessToken": "YOUR_ACCESS_TOKEN" }, "timestamp": "2023" } |
You can configure the signInResponseRefreshTokenPointer with the value /token/refreshToken to direct NuxtAuth to the exact location where it should retrieve the refresh token.
signInResponseRefreshTokenPointer: ‘/token/refreshToken’
refreshResponseTokenPointer
The refreshResponseTokenPointer is used to identify where the new access token is located within the response returned by the refresh endpoint. After NuxtAuth sends a request to refresh the session using the refresh token, the response often includes a new access token and, sometimes, a new refresh token as well. This option tells NuxtAuth how to find and extract the new access token from that response.
How it works:
When you set the refreshResponseTokenPointer in NuxtAuth, it tells the system where to find the access token within the response returned by the refresh endpoint.
Let’s say, for instance, that the response you get from the refresh endpoint looks something like this:
{ "token": { "bearer": "THE_NEW_AUTH_TOKEN" }, "timestamp": "2023" } |
Here’s how you would set up the refreshResponseTokenPointer configuration:
refreshResponseTokenPointer: ‘/token/bearer’
Default Behavior:
If you do not specify a value for refreshResponseTokenPointer (leaving it as the default empty string), NuxtAuth will use the signInResponseTokenPointer configuration to extract the access token from the refresh response. In other words, unless you define a separate pointer for the refresh token, NuxtAuth will assume the token is located in the same place as it was in the sign-in response.
refreshRequestTokenPointer
The refreshRequestTokenPointer option specifies the location of the refresh token in the response returned by the refresh token endpoint. This is especially helpful when working with an external backend or when the response structure doesn’t follow typical conventions.
By configuring this pointer, you instruct NuxtAuth exactly where to find and retrieve the refresh token from the server’s response so that it can be properly saved.
Default:
“auth.refresh-token” |
cookieName
The cookieName option specifies the name of the cookie used to store the refresh token. This is important for securely handling the refresh token within the user’s browser. By storing the token in a cookie, the client application can automatically include it in future requests, enabling seamless token renewal when needed.
How it Works:
When NuxtAuth needs to save a refresh token, it stores it in a cookie. The name of this cookie is defined by the cookieName setting. By default, the cookie name is ‘auth.refresh-token’, so the refresh token will be stored under this name unless you specify a different one.
secureCookieAttribute
The secureCookieAttribute setting controls whether the refresh token cookie is transmitted only over HTTPS connections. When enabled, the cookie is flagged as secure, i.e., the browser will include it only in requests made through secure HTTPS channels. This enhances security by preventing the cookie from being sent over unencrypted HTTP connections, helping to protect it from threats such as Man-in-the-Middle (MitM) attacks.
httpOnlyCookieAttribute
The httpOnlyCookieAttribute setting controls whether the JavaScript in the browser can access the refresh token cookie. When this option is set to true, the cookie is marked with the HttpOnly flag, which means it can’t be read or modified by client-side JavaScript. This helps protect against cross-site scripting (XSS) attacks by keeping the token hidden from potentially malicious scripts.
4.5.7 Pages
The pages configuration allows you to specify a custom login page URL to which users will be redirected if they try to access a protected page without logging in. This is particularly helpful for managing authentication in your Nuxt 3 application. If a logged-out user tries to access a secure page, they’ll automatically be sent to the login page you have defined.
Key Configuration:
Path: The location or URL of the login page.
provider: { type: "local", endpoints: { signIn: { path: "/auth/sign-in", method: "post" }, signOut: { path: "/auth/logout", method: "get" }, signUp: { path: "/auth/sign-up", method: "post" }, getSession: { path: "/users/me", method: "get" }, }, pages: { login: "/signin", }, // previous configuration }, |
How It Works:
- Login Redirection: When an unauthenticated user attempts to access a protected page, the Nuxt application will automatically redirect them to the login page specified in your pages configuration.
- Global Middleware: The login page is exempt from the global authentication middleware, meaning users will not be redirected from it, even if it’s typically protected. In other words, the login page is treated as an exception to the standard authentication rules.
4.5.8 dataResponsePointer
The dataResponsePointer option is used to define the exact location within the response object where the session data can be found after a successful login or session retrieval.
When using TypeScript with NuxtAuth, you can customize the types returned by your backend API by extending the default session types. This customization requires either modifying your nuxt.config.ts file or creating a dedicated type definition file. Doing so helps ensure type safety and improves integration with your backend’s session structure.
session: { dataResponsePointer: "/data", dataType: { id: "number", email: "string", }, }, |
In the example provided, NuxtAuth automatically detects the correct types from your configuration, ensuring that any use of useSession() or getSession() throughout your application returns a fully typed session object. This session object is shaped by the response your backend provides, as well as the types you’ve defined in your configuration.
interface SessionData { id: string | number email: string } |
4.5.9 Session Access and Management
After setting up your chosen authentication provider, you can start integrating NuxtAuth into your frontend components. NuxtAuth provides two versatile composables that make it easy to access and manage authentication sessions within your application.
4.6 Set Up Your Components
To handle styling, the Tailwind CSS plugin is used here. You can add it to your project by running the following command:
Command:
npm install tailwindcss @tailwindcss/vite |
Next, include the assets/css/main.css file in your project setup.
main.css
@import "tailwindcss"; |
Set Up the Vite Plugin
To use the @tailwindcss/vite plugin in your Nuxt project, include it in the Vite plugins array within your Nuxt configuration.
export default defineNuxtConfig({ // previous configuration vite: { plugins: [tailwindcss()], }, }) |
Register the CSS file globally
Add the newly created ./assets/css/main.css file to the css array in your nuxt.config.ts file to ensure it’s included in your project.
export default defineNuxtConfig({ // previous configuration css: ["~/assets/css/main.css"], vite: { plugins: [tailwindcss()], }, }) |
Before creating individual pages, we’ll set up a layout that will wrap all our views.
Start by creating a directory named /layouts, and within that folder, add a file titled default.vue.
<script setup> const { status, signOut } = useAuth(); const isLoggedIn = computed(() => status.value === "authenticated"); const handleLogout = async () => { await signOut(); navigateTo("/signin"); }; </script> <template> <nav class="bg-white shadow-md p-4 flex justify-between"> <h1 class="text-xl font-bold text-gray-800">MyApp</h1> <div class="flex space-x-4"> <NuxtLink to="/" class="text-gray-700 hover:text-blue-600 transition"> Home </NuxtLink> <NuxtLink v-if="!isLoggedIn" to="/signin" class="text-gray-700 hover:text-blue-600 transition" > Login </NuxtLink> <NuxtLink v-if="!isLoggedIn" to="/signup" class="text-gray-700 hover:text-blue-600 transition" > Sign Up </NuxtLink> <NuxtLink v-if="isLoggedIn" to="/private" class="text-gray-700 hover:text-blue-600 transition" > Private </NuxtLink> <button v-if="isLoggedIn" @click="handleLogout" class="bg-red-500 hover:bg-red-600 text-white px-4 py-1 rounded" > Logout </button> </div> </nav> <main class="p-4"> <slot /> </main> </template> |
Status:
This is a reactive variable that indicates the user’s current authentication state. It can have one of the following values:
- “authenticated”: when the user is signed in
- “unauthenticated”: when the user is not signed in
- “loading”: when the authentication status is being determined
signOut:
This method logs the user out by clearing the session and performing any configured logout actions, such as redirecting the user to the login page.
How to Use the Default Layout?
Simply wrap the <NuxtPage /> component inside your app.vue file to ensure the default layout is applied across all pages.
//app.vue <template> <div> <NuxtLayout> <NuxtPage /> </NuxtLayout> </div> </template> |
Setup Views
Create a pages directory in your Nuxt project. This folder will hold the various views (or pages) of your application, such as:
- Home.vue – This is the public-facing landing or homepage.
- SignIn.vue – the page where users can log in.
- SignUp.vue – the page for user registration.
- Other private or secure pages – these are pages that require authentication to access.
Home page: /pages/index.vue
<script setup> definePageMeta({ auth: false, }); </script> <template> <p>Welcome Home</p> </template> |
In Nuxt 3, the definePageMeta({ auth: false }) directive is used to disable authentication protection for a specific page when using the @sidebase/nuxt-auth module. This allows you to make a page publicly accessible, bypassing any authentication requirements.
SignIn Page: /pages/signin
<script setup lang="ts"> const { signIn } = useAuth(); const formData = reactive({ email: "", password: "", }); const login = async (e: Event) => { try { e.preventDefault(); let res = await signIn( { ...formData }, { callbackUrl: "/" } // Where the user will be redirected after a successiful login ); console.log("res", res); } catch (error) { console.log("error", error); } }; definePageMeta({ title: "Signin", layout: "default", public: true, auth: { unauthenticatedOnly: true, navigateAuthenticatedTo: "/", }, }); </script> <template> <section class="min-h-screen flex items-center justify-center bg-gray-100"> <form @submit.prevent="login" class="w-full max-w-md p-8 bg-white rounded-2xl shadow-md space-y-6" > <h2 class="text-2xl font-bold text-center text-gray-800">Login</h2> <input v-model="formData.email" type="email" placeholder="Email" class="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> <input v-model="formData.password" type="password" placeholder="Password" class="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-md transition duration-300 disabled:opacity-50" > <span>Login</span> </button> </form> </section> </template> |
signIn is a function that initiates the login process through the provider you have set up, such as “local” or “authjs.”
SignUp Page: /pages/signup.vue
<script setup lang="ts"> const { signUp } = useAuth(); const formData = reactive({ email: "", password: "", firstName: "", lastName: "", phoneNumber: "", }); const onSignUp = async (e: Event) => { try { e.preventDefault(); await signUp({ ...formData }, undefined, { preventLoginFlow: true, }); await navigateTo("/signin"); } catch (error) { console.log("error", error); } }; definePageMeta({ title: "Signup", layout: "default", public: true, auth: { unauthenticatedOnly: true, }, }); </script> <template> <section class="min-h-screen flex items-center justify-center bg-gray-100"> <form @submit.prevent="onSignUp" class="w-full max-w-md p-8 bg-white rounded-2xl shadow-md space-y-6" > <h2 class="text-2xl font-bold text-center text-gray-800">Sign Up</h2> <input v-model="formData.email" type="email" placeholder="Email" class="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> <input v-model="formData.password" type="password" placeholder="Password" class="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> <input v-model="formData.firstName" type="text" placeholder="First Name" class="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> <input v-model="formData.lastName" type="text" placeholder="Last Name" class="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> <input v-model="formData.phoneNumber" type="text" placeholder="Phone Number" class="w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required /> <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-md transition duration-300 disabled:opacity-50" > <span>Sign Up</span> </button> </form> </section> </template> |
Private Page: /pages/private.vue
<script setup> definePageMeta({ auth: true, layout: "default", }); const { data } = useAuth(); </script> <template> <div> <h1>Id: {{ data.id }}</h1> <h2>Email: {{ data.email }}</h2> <p>This page is private, you can only see it if you are logged in.</p> </div> </template> |
This page is only accessible to authenticated users. If a user is not logged in, they will be redirected to the login page.
The line const { data } = useAuth(); is used to access the authentication information from the NuxtAuth context. It extracts the relevant authentication data related from the context provided.
Data
The data property contains the session details of the authenticated user, or any other relevant user-related information, depending on how it is configured.
Once you’ve completed all the configurations and set up the necessary components, the next step is to launch your application.
To start your Nuxt application, simply run the command below in your terminal:
Command:
npm run dev |
This will start the development server, and you should be able to access your app at:
http://localhost:3000





5. Final Thoughts
Implementing authentication in a Nuxt.js application using the @sidebase/nuxt-auth module provides a streamlined and flexible approach to secure your app. This module allows developers to quickly integrate various authentication strategies, including local and refresh token providers, and easily manage user sessions. The module’s built-in support for token-based authentication ensures that your application remains secure while allowing users to access protected routes seamlessly. Follow the steps provided in the guide and follow them sequentially to implement a powerful authentication system, increasing the security and reliability of the application.
Comments
Leave a message...