Next.js

View on Github

Next.js

Gravatar for rita.zerrizuela@auth0.com
By Rita Zerrizuela

This guide demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js SDK. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Next.js 10+

New to Auth? Learn How Auth0 works, how it integrates with Regular Web Applications and which protocol it uses.

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one. You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

App Dashboard

You need the following information:

  • Domain
  • Client ID
  • Client Secret

If you download the sample from the top of this page, these details are filled out for you.

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated. The callback URL for your app must be added to the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.

If you are following along with the sample project you downloaded from the top of this page, the callback URL you need to add to the Allowed Callback URLs field is http://localhost:3000/api/auth/callback.

Configure Logout URLs

A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter. The logout URL for your app must be added to the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.

If you are following along with the sample project you downloaded from the top of this page, the logout URL you need to add to the Allowed Logout URLs field is http://localhost:3000.

Install the Auth0 Next.js SDK

Run the following command within your project directory to install the Auth0 Next.js SDK:

npm install @auth0/nextjs-auth0

The SDK exposes methods and variables that help you integrate Auth0 with your Next.js application using API Routes on the backend and React Context with React Hooks on the frontend.

Configure the SDK

In the root directory of your project, add the file .env.local with the following environment variables:

AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_DOMAIN'
AUTH0_CLIENT_ID='YOUR_CLIENT_ID'
AUTH0_CLIENT_SECRET='YOUR_CLIENT_SECRET'
  • AUTH0_SECRET: A long secret value used to encrypt the session cookie. You can generate a suitable string using openssl rand -hex 32 on the command line.
  • AUTH0_BASE_URL: The base URL of your application.
  • AUTH0_ISSUER_BASE_URL: The URL of your Auth0 tenant domain. If you are using a Custom Domain with Auth0, set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab.
  • AUTH0_CLIENT_ID: Your Auth0 application's Client ID.
  • AUTH0_CLIENT_SECRET: Your Auth0 application's Client Secret.

The SDK will read these values from the Node.js process environment and automatically configure itself.

Add the dynamic API route

Inside the pages/api directory, create the file auth/[...auth0].js. Import in that file the handleAuth method from the SDK, and export the result of calling it.

// pages/api/auth/[...auth0].js
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();

This creates the following routes:

  • /api/auth/login: The route used to perform login with Auth0.
  • /api/auth/logout: The route used to log the user out.
  • /api/auth/callback: The route Auth0 will redirect the user to after a successful login.
  • /api/auth/me: The route to fetch the user profile from.

Add the UserProvider component

On the frontend side, the SDK uses React Context to manage the authentication state of your users. To make that state available to all your pages, you need to override the App component and wrap its inner component with a UserProvider. Create the file pages/_app.js as follows:

// pages/_app.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';

export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

The authentication state exposed by UserProvider can be accessed in any component using the useUser() hook.

Checkpoint

Now that you have added the dynamic route and UserProvider, run your application to verify that your application is not throwing any errors related to Auth0.

Add Login to Your Application

A user can now log in to your application by visiting the /api/auth/login route provided by the SDK. Add a link to your login route using an anchor tag.

Next linting rules might suggest using the Link component instead of an anchor tag. The Link component is meant to perform client-side transitions between pages. As the link points to an API route and not to a page, you should keep it as an anchor tag.

<a href="/api/auth/login">Login</a>

Checkpoint

Add the login link to your application. When you click it, verify that your Next.js application redirects you to the Auth0 Universal Login page and that you can now log in or sign up using a username and password or a social provider.

Once that's complete, verify that Auth0 redirects back to your application.

Auth0 Universal Login

Auth0 enables the Google social provider by default on new tenants and offers you developer keys to test logging in with social identity providers. However, these developer keys have some limitations that may cause your application to behave differently. For more details on what this behavior may look like and how to fix it, consult the Test Social Connections with Auth0 Developer Keys document.

Add Logout to Your Application

Now that you can log in to your Next.js application, you need a way to log out. You can add a link that points to the /api/auth/logout API route. Clicking it redirects your users to your Auth0 logout endpoint (https://YOUR_DOMAIN/v2/logout) and then immediately redirects them back to your application.

<a href="/api/auth/logout">Logout</a>

Checkpoint

Add the logout link to your application. When you click it, verify that your Next.js application redirects you to the address you specified as one of the "Allowed Logout URLs" in the "Settings".

Show User Profile Information

The Auth0 Next.js SDK helps you retrieve the profile information associated with the logged-in user, such as their name or profile picture, to personalize the user interface. The profile information is available through the user property exposed by the useUser() hook. Take this Profile component as an example of how to use it:

import React from 'react';
import { useUser } from '@auth0/nextjs-auth0';

export default function Profile() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  return (
    user && (
      <div>
        <img src={user.picture} alt={user.name} />
        <h2>{user.name}</h2>
        <p>{user.email}</p>
      </div>
    )
  );
}

The user property contains sensitive information and artifacts related to the user's identity. As such, its availability depends on the user's authentication status. To prevent any render errors:

  • Ensure that the SDK has completed loading before accessing the user property by checking that isLoading is false.
  • Ensure that the SDK has loaded successfully by checking that no error was produced.
  • Check the user property to ensure that Auth0 has authenticated the user before React renders any component that consumes it.

Checkpoint

Verify that you can display the user.name or any other user property within a component correctly after you have logged in.

What's next?

We put together a few examples of how to use nextjs-auth0 in more advanced use cases:

Use Auth0 for FREE