
Security News
Meet Socket at Black Hat and DEF CON 2025 in Las Vegas
Meet Socket at Black Hat & DEF CON 2025 for 1:1s, insider security talks at Allegiant Stadium, and a private dinner with top minds in software supply chain security.
@auth0/nextjs-auth0
Advanced tools
@auth0/nextjs-auth0 is a library that provides authentication and authorization for Next.js applications using Auth0. It simplifies the process of integrating Auth0 into Next.js apps by providing a set of tools and utilities for handling user sessions, protecting routes, and managing user profiles.
User Authentication
This feature allows you to handle user authentication with Auth0. The `handleAuth` function sets up the necessary routes for login, logout, and callback.
const { handleAuth } = require('@auth0/nextjs-auth0');
export default handleAuth();
Protecting API Routes
This feature allows you to protect API routes by ensuring that only authenticated users can access them. The `withApiAuthRequired` function wraps your API route handler to enforce authentication.
import { withApiAuthRequired } from '@auth0/nextjs-auth0';
export default withApiAuthRequired((req, res) => {
res.status(200).json({ message: 'This is a protected API route' });
});
Protecting Pages
This feature allows you to protect Next.js pages by ensuring that only authenticated users can access them. The `withPageAuthRequired` function wraps your page component to enforce authentication.
import { withPageAuthRequired } from '@auth0/nextjs-auth0';
const ProtectedPage = () => {
return <div>This is a protected page</div>;
};
export default withPageAuthRequired(ProtectedPage);
Fetching User Profile
This feature allows you to fetch and display the authenticated user's profile information. The `useUser` hook provides the user's data, loading state, and any errors.
import { useUser } from '@auth0/nextjs-auth0';
const UserProfile = () => {
const { user, error, isLoading } = useUser();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>{error.message}</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
};
export default UserProfile;
next-auth is a complete open-source authentication solution for Next.js applications. It supports multiple authentication providers, including OAuth, email/password, and custom credentials. Compared to @auth0/nextjs-auth0, next-auth offers more flexibility in terms of provider options and customization but may require more configuration.
Firebase provides a suite of tools for building and managing web and mobile applications, including authentication. Firebase Authentication supports various authentication methods, such as email/password, phone, and social providers. Compared to @auth0/nextjs-auth0, Firebase offers a broader range of services beyond authentication, such as real-time databases and cloud functions, but may be more complex to integrate into a Next.js application.
Passport is a popular authentication middleware for Node.js. It supports a wide range of authentication strategies, including OAuth, OpenID, and custom strategies. Compared to @auth0/nextjs-auth0, Passport provides more granular control over the authentication process but requires more setup and configuration.
The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications.
š Documentation - š Getting Started - š» API Reference - š¬ Feedback
npm i @auth0/nextjs-auth0
This library requires Node.js 20 LTS and newer LTS versions.
Add the following environment variables to your .env.local
file:
AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=
AUTH0_SECRET=
APP_BASE_URL=
The AUTH0_DOMAIN
, AUTH0_CLIENT_ID
, and AUTH0_CLIENT_SECRET
can be obtained from the Auth0 Dashboard once you've created an application. This application must be a Regular Web Application
.
The AUTH0_SECRET
is the key used to encrypt the session and transaction cookies. You can generate a secret using openssl
:
openssl rand -hex 32
The APP_BASE_URL
is the URL that your application is running on. When developing locally, this is most commonly http://localhost:3000
.
[!IMPORTANT]
You will need to register the follwing URLs in your Auth0 Application via the Auth0 Dashboard:
- Add
http://localhost:3000/auth/callback
to the list of Allowed Callback URLs- Add
http://localhost:3000
to the list of Allowed Logout URLs
Create an instance of the Auth0 client. This instance will be imported and used in anywhere we need access to the authentication methods on the server.
Add the following contents to a file named lib/auth0.ts
:
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client();
Create a middleware.ts
file in the root of your project's directory:
import type { NextRequest } from "next/server";
import { auth0 } from "./lib/auth0"; // Adjust path if your auth0 client is elsewhere
export async function middleware(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"
]
};
[!NOTE]
If you're using asrc/
directory, themiddleware.ts
file must be created inside thesrc/
directory.
You can now begin to authenticate your users by redirecting them to your application's /auth/login
route:
import { auth0 } from "./lib/auth0"; // Adjust path if your auth0 client is elsewhere
export default async function Home() {
const session = await auth0.getSession();
if (!session) {
return (
<main>
<a href="/auth/login?screen_hint=signup">Sign up</a>
<a href="/auth/login">Log in</a>
</main>
);
}
return (
<main>
<h1>Welcome, {session.user.name}!</h1>
</main>
);
}
[!IMPORTANT]
You must use<a>
tags instead of the<Link>
component to ensure that the routing is not done client-side as that may result in some unexpected behavior.
You can customize the client by using the options below:
Option | Type | Description |
---|---|---|
domain | string | The Auth0 domain for the tenant (e.g.: example.us.auth0.com or https://example.us.auth0.com ). If it's not specified, it will be loaded from the AUTH0_DOMAIN environment variable. |
clientId | string | The Auth0 client ID. If it's not specified, it will be loaded from the AUTH0_CLIENT_ID environment variable. |
clientSecret | string | The Auth0 client secret. If it's not specified, it will be loaded from the AUTH0_CLIENT_SECRET environment variable. |
authorizationParameters | AuthorizationParameters | The authorization parameters to pass to the /authorize endpoint. See Passing authorization parameters for more details. |
clientAssertionSigningKey | string or CryptoKey | Private key for use with private_key_jwt clients. This can also be specified via the AUTH0_CLIENT_ASSERTION_SIGNING_KEY environment variable. |
clientAssertionSigningAlg | string | The algorithm used to sign the client assertion JWT. This can also be provided via the AUTH0_CLIENT_ASSERTION_SIGNING_ALG environment variable. |
appBaseUrl | string | The URL of your application (e.g.: http://localhost:3000 ). If it's not specified, it will be loaded from the APP_BASE_URL environment variable. |
logoutStrategy | "auto" | "oidc" | "v2" | Strategy for logout endpoint selection. "auto" (default) uses OIDC logout when available, falls back to /v2/logout . "oidc" always uses OIDC logout. "v2" always uses /v2/logout endpoint which supports wildcard URLs. See Configuring logout strategy for details. |
secret | string | A 32-byte, hex-encoded secret used for encrypting cookies. If it's not specified, it will be loaded from the AUTH0_SECRET environment variable. |
signInReturnToPath | string | The path to redirect the user to after successfully authenticating. Defaults to / . |
session | SessionConfiguration | Configure the session timeouts and whether to use rolling sessions or not. See Session configuration for additional details. Also allows configuration of cookie attributes like domain , path , secure , sameSite , and transient . If not specified, these can be configured using AUTH0_COOKIE_* environment variables. Note: httpOnly is always true . See Cookie Configuration for details. |
beforeSessionSaved | BeforeSessionSavedHook | A method to manipulate the session before persisting it. See beforeSessionSaved for additional details. |
onCallback | OnCallbackHook | A method to handle errors or manage redirects after attempting to authenticate. See onCallback for additional details. |
sessionStore | SessionStore | A custom session store implementation used to persist sessions to a data store. See Database sessions for additional details. |
pushedAuthorizationRequests | boolean | Configure the SDK to use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server. |
routes | Routes | Configure the paths for the authentication routes. See Custom routes for additional details. |
allowInsecureRequests | boolean | Allow insecure requests to be made to the authorization server. This can be useful when testing with a mock OIDC provider that does not support TLS, locally. This option can only be used when NODE_ENV is not set to production . |
httpTimeout | number | Integer value for the HTTP timeout in milliseconds for authentication requests. Defaults to 5000 milliseconds |
enableTelemetry | boolean | Boolean value to opt-out of sending the library name and version to your authorization server via the Auth0-Client header. Defaults to true . |
You can specify the following environment variables to configure the session cookie:
AUTH0_COOKIE_DOMAIN=
AUTH0_COOKIE_PATH=
AUTH0_COOKIE_TRANSIENT=
AUTH0_COOKIE_SECURE=
AUTH0_COOKIE_SAME_SITE=
Respective counterparts are also available in the client configuration. See Cookie Configuration for more details.
Your Next.js application may be configured to use a base path (e.g.: /dashboard
) ā this is usually done by setting the basePath
option in the next.config.js
file. To configure the SDK to use the base path, you will also need to set the NEXT_PUBLIC_BASE_PATH
environment variable which will be used when mounting the authentication routes.
For example, if the NEXT_PUBLIC_BASE_PATH
environment variable is set to /dashboard
, the SDK will mount the authentication routes on /dashboard/auth/login
, /dashboard/auth/callback
, /dashboard/auth/profile
, etc.
[!NOTE] We do not recommend using the
NEXT_PUBLIC_BASE_PATH
environment variable in conjunction with aAPP_BASE_URL
that contains a path component. If your application is configured to use a base path, you should set theAPP_BASE_URL
to the root URL of your application (e.g.:https://example.com
) and use theNEXT_PUBLIC_BASE_PATH
environment variable to specify the base path (e.g.:/dashboard
).
The SDK performs validation of required configuration options when initializing the Auth0Client
. The following options are mandatory and must be provided either through constructor options or environment variables:
domain
(or AUTH0_DOMAIN
environment variable)clientId
(or AUTH0_CLIENT_ID
environment variable)appBaseUrl
(or APP_BASE_URL
environment variable)secret
(or AUTH0_SECRET
environment variable)clientSecret
(or AUTH0_CLIENT_SECRET
environment variable), ORclientAssertionSigningKey
(or AUTH0_CLIENT_ASSERTION_SIGNING_KEY
environment variable)If any of these required options are missing, the SDK will issue a warning with a detailed message explaining which options are missing and how to provide them.
The SDK mounts 6 routes:
/auth/login
: the login route that the user will be redirected to to initiate an authentication transaction/auth/logout
: the logout route that must be added to your Auth0 application's Allowed Logout URLs/auth/callback
: the callback route that must be added to your Auth0 application's Allowed Callback URLs/auth/profile
: the route to check the user's session and return their attributes/auth/access-token
: the route to check the user's session and return an access token (which will be automatically refreshed if a refresh token is available)/auth/backchannel-logout
: the route that will receive a logout_token
when a configured Back-Channel Logout initiator occurs[!IMPORTANT]
The/auth/access-token
route is enabled by default, but is only neccessary when the access token is needed on the client-side. If this isn't something you need, you can disable this endpoint by settingenableAccessTokenEndpoint
tofalse
.
We appreciate feedback and contribution to this repo! Before you get started, please read the following:
To provide feedback or report a bug, please raise an issue on our issue tracker.
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?
This project is licensed under the MIT license. See the LICENSE file for more info.
v4.8.0 (2025-07-03)
Added
withPageAuthRequired
for protecting pages client side #2193 (guabu)Fixed
max-age=0
to delete cookie #2200 (guabu)FAQs
Auth0 Next.js SDK
The npm package @auth0/nextjs-auth0 receives a total of 307,934 weekly downloads. As such, @auth0/nextjs-auth0 popularity was classified as popular.
We found that @auth0/nextjs-auth0 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 40 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Meet Socket at Black Hat & DEF CON 2025 for 1:1s, insider security talks at Allegiant Stadium, and a private dinner with top minds in software supply chain security.
Security News
CAI is a new open source AI framework that automates penetration testing tasks like scanning and exploitation up to 3,600Ć faster than humans.
Security News
Deno 2.4 brings back bundling, improves dependency updates and telemetry, and makes the runtime more practical for real-world JavaScript projects.