The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications.
📚 Documentation - 🚀 Getting Started - 💻 API Reference - 💬 Feedback
- QuickStart- our guide for adding Auth0 to your Next.js app.
- Examples - lots of examples for your different use cases.
- Security - Some important security notices that you should check.
- Docs Site - explore our docs site and learn more about Auth0.
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"
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 a src/
directory, the middleware.ts
file must be created inside the src/
directory.
You can now begin to authenticate your users by redirecting them to your application's /auth/login
route:
import { auth0 } from "@/lib/auth0"
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="