close icon
SDK

Introducing Auth0's Next.js SDK

Learn how to authenticate users with Auth0’s Next.js SDK

March 16, 2021

TL;DR: Auth0 announces the release of nextjs-auth0, a new Next.js SDK that makes it super easy to add authentication to your Next.js apps. Get it here.

Next.js blurs the line between frontend and backend, so there is more than one way to do authentication on a Next.js app.

To identify which authentication pattern you should use, you must first understand the data-fetching strategy you want. The predominant patterns are:

Fetching user data client-side

You will use Static Generation to generate the page’s HTML at build time. The HTML will then be reused on each request and can be cached by a CDN. The user will be quickly served an app shell, usually a loading indicator, before the client-side code fetches the user’s data to populate the content.

Your typical authentication for this type of application will be that of a SPA, where the user’s tokens are stored on the client.

For fetching user data client-side, we recommend using auth0-react; we have an example Next.js app using auth0-react for authentication in the project’s repository here.

Fetching user data server-side

When the server receives a request for a page, it will fetch your user’s data and construct the page at the request time. This will be slower than returning the page from a CDN but doesn’t need to display an app shell while the frontend fetches the user data.

Your typical authentication for this type of application will be that of a Regular Web App, where the user’s tokens are stored in a secure session that is not directly accessible from the client-side and therefore not vulnerable to the more common XSS attacks.

💡As you can see from the two models described above, there are various tradeoffs for performance and security. For more information, check out our Ultimate Guide to Next.js Authentication with Auth0.

For fetching user data server-side, we recommend our new Next.js SDK nextjs-auth0.

Adding Session Based Authentication to a Next.Js Application

In a few lines of code nextjs-auth0 adds server-side login, logout, and session management. It also offers a suite of tools to access the user’s session from the server and client-side.

Create a Regular Web Application in the Auth0 Dashboard and configure the following URLs for your application under Application URIs:

Take note of the Client ID, Client Secret, and Domain of your application because you’ll need it in the next step.

Install the SDK using npm or yarn, eg.

npm install @auth0/nextjs-auth0

The library needs the following required configuration keys. These can be configured in a .env.local file in the root of your application (See more info about loading environmental variables in Next.js):

#A long secret value used to encrypt the session cookie
AUTH0_SECRET=LONG_RANDOM_VALUE
#The base url of your application
AUTH0_BASE_URL=http://localhost:3000
#The url of your Auth0 tenant domain
AUTH0_ISSUER_BASE_URL=https://YOUR_AUTH0_DOMAIN.auth0.com
#Your Auth0 application's Client ID
AUTH0_CLIENT_ID=YOUR_AUTH0_CLIENT_ID
#Your Auth0 application's Client Secret
AUTH0_CLIENT_SECRET=YOUR_AUTH0_CLIENT_SECRET

For a full list of configuration options see the docs.

Then, create a Dynamic API Route handler at /pages/api/auth/[...auth0].js.

import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();

This will create the following urls: /api/auth/login, /api/auth/callback, /api/auth/logout and /api/auth/me.

That’s it! The server-side is now setup and you can visit http://localhost:3000/api/auth/login to login.

To access the user on the client-side, wrap your pages/_app.js component in the UserProvidercomponent.

//pages/_app.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';
export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

This will populate a React Hook useUser you can use to check the user object. You can also log them in and out from the front end by redirecting to the appropriate /api/auth/* route.

// pages/index.js
import { useUser } from '@auth0/nextjs-auth0';

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

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

  if (user) {
    return (
      <div>
        Welcome {user.name}! <a href="/api/auth/logout">Logout</a>
      </div>
    );
  }

  return <a href="/api/auth/login">Login</a>;
};

Go checkout the QuickStart for a more detailed setup and also the examples for more ways to use the new nextjs-auth0 SDK.

Happy coding!

  • Twitter icon
  • LinkedIn icon
  • Faceboook icon