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+

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

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.

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.

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

Was this helpful?

/

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://{yourDomain}'
AUTH0_CLIENT_ID='{yourClientId}'
AUTH0_CLIENT_SECRET='{yourClientSecret}'

Was this helpful?

/
  • 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

Create an auth directory under the pages/api directory. Under this newly created auth directory, create a [...auth0].js file. The path to your dynamic API route file should then be pages/api/auth/[...auth0].js.

Then, 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();

Was this helpful?

/

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/client';

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

Was this helpful?

/

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

Users can now log in to your application by visiting the /api/auth/login route provided by the SDK. Add a link that points to the login route using an anchor tag. Clicking it redirects your users to the Auth0 Universal Login Page, where Auth0 can authenticate them. Upon successful authentication, Auth0 will redirect your users back to your application.

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

Was this helpful?

/

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

Add Logout to Your Application

Now that you can log in to your Next.js application, you need a way to log out. 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>

Was this helpful?

/

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/client';

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>
    )
  );
}

Was this helpful?

/

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