Next.js is a minimalist framework to build single-page JavaScript applications in a simple yet customizable way. The framework focuses on performance and out of the box support for Server-Side Rendering (SSR). The Next.js showcase confirms the success of the framework, which companies big and small use to build their applications, including Netflix, Scale.ai, Marvel, Jet, and even Auth0.

If you are new to Next.js and want to learn how to use this framework to build full-stack Jamstack applications, checkout the video playlist below by James Quick:

New Tools, New Challenges

Providing a solution to support authentication in Next.js was one of the most requested features in the platform. But why is that?

Can't we use any of the tools that we've been using for so long in React and Node.js, such as passport or auth0.js? Or new ones such as the Auth0 React SDK or Express OpenID Connect?

Next.js blurs the line between frontend and backend, making the existing ecosystem suboptimal if you want to use Next.js to its full potential.

One example is Passport, which depends on the availability of Express. And while you could technically use Express in your Next.js application, it will make all performance improvements fade away. If you want to optimize for fast cold starts and improve the reliability and scalability of your application, you need to shift to the serverless deployment model.

There are different ways to build and deploy Next.js applications. In this blog post, we'll explore those Next.js use cases, explain their architecture, and define the strategy you can use to implement authentication for each one.

What Does Authentication Mean For Next.js?

When you're building a Next.js application, you may need authentication in the following cases:

  • When accessing a page: "My Invoices"

  • When accessing a Next.js API route: /api/my/invoices

  • When your application calls an API hosted outside of your Next.js application on behalf of the user: from www.mycompany.com to billing.mycompany.com/api

Now that we understand where and when our application might require authentication, let's explore the authentication strategies you can implement for different Next.js deployment models.

Next.js Static Site Approach

Next.js allows you to generate a standalone static application without the need for a Node.js server. You can run the next build && next export command to generate HTML files for each page that supports it. You can use this generated output to deploy your site to any static hosting service, such as Vercel, Amazon S3, or Netlify.

Screenshot of the build command

You can use this technique to generate complete websites as static sites, like a company public front page, or when you're creating an "admin dashboard". The generated HTML could be the shell of your application — think of this shell as your application's header and footer. The Vercel dashboard is one of the best examples out there of how this could look:

Screenshot of Vercel dashboard shell

Once the "shell" has been served, the client-side will call the necessary APIs (carrying the user information), fetch user-specific content, and update the page:

Screenshot of Vercel dashboard with user information

This model has several advantages when it comes to hosting. Static hosting sites (like Vercel, Amazon S3, Azure Blob Storage, Netlify, and others) are battle-tested, inexpensive, but more importantly, they are extremely fast and play well with CDNs.

Diagram of a Next.js Static Site Deployment

One thing that will be somewhat different is how we handle authentication. The model where a server is available can handle the interaction with Auth0 and create a session, but in this model, we don't have a backend. All the work happens on the frontend:

  1. Your static site redirects your users to Auth0 to log in.
  2. When your users successfully log in, Auth0 redirects them to your static site.
  3. Your static site performs a code exchange with Auth0 to retrieve the user's id_token and access_token, which it stores in memory.

Diagram illustrating the Authorization Code Exchange form the client-side

If your use case requires dynamic content or user-specific content, you will also need to deploy something else, like an API. This API won't run as part of your static hosting site. You'll use a platform like AWS Lambda, Heroku, or Now, to deploy it. Your static site (the client-side) will use the access_token to make secure calls to that API directly, fetch the dynamic content, and enrich the static page served by the hosting platform.

Diagram of the client-side making calls to an API

This architecture is similar to how you can build any single-page application, where the application doesn't have an actual "backend" but instead calls one or more APIs. You'll find a variety of examples in the community of how to sign in to this type of application:

With use-auth0-hooks, for example, it's as easy as configuring your application like so:

import { Auth0Provider } from 'use-auth0-hooks';

export default class Root extends App {
  render () {
    const { Component, pageProps } = this.props;
    return (
      <Auth0Provider
        domain={'sandrino-dev.auth0.com'}
        clientId={'9f6ClmBt37ZGCXNqToPbefKmzVBSOLa2'}
        redirectUri={'http://localhost:3000/'}>
          <Component {...pageProps} />
      </Auth0Provider>
    );
  }
}

You can then use React Hooks to retrieve the user profile information and request an access token to make secure calls to your APIs. Your Next.js static site sends the access_token in the authorization headers of your API calls, which the following example does through the useApi hook:

import { useAuth } from 'use-auth0-hooks';

export default function MyShows() {
  const { isAuthenticated, isLoading, accessToken } = useAuth({
    audience: 'https://api/tv-shows',
    scope: 'read:shows'
  });

  if (!isAuthenticated) {
    return (
      <div>You must first sign in to access your subscriptions.</div>;
    )
  }

  if (isLoading) {
    return (
      <div>Loading your user information...</div>
    );
  }

  const { response, loading } = useApi(
    `${process.env.API_BASE_URL}/api/my/shows`,
    accessToken
  );

  if (loading) {
    return (
      <h1>Subscriptions for {user.email}<h1>
      <div>Loading your subscriptions ...</div>
    );
  }

  return (
    <h1>Subscriptions for {user.email}<h1>
    <div>You have subscribed to a total of {response && response.shows && response.shows.length} shows...</div>
  );
}

Visit the Next.js Practical Introduction to learn how to use the Next.js framework to build React applications.

What exactly happens behind the curtains here?

When using auth0-spa-js the user will sign in using the Authorization Code Grant with PKCE. At a high level, your Next.js application redirects the user to Auth0 to login. Auth0 will handle all the required authentication and authorization logic (sign-up, sign-in, MFA, consent, and so on). After users complete the authentication process with Auth0, Auth0 redirects them to your application with an Authorization Code in the query string.

The client-side will exchange that code for an id_token and optionally an access_token (1,2). You can use the access_token to call your API. When the access_token expires, the same flow will happen again under the covers, using an <iframe>. This "silent authentication" approach will keep working for as long as the user is logged in — as long as the user has a session in Auth0. When the user's session in Auth0 expires or a sign out takes place, this call will fail, and the user will be required to log in again.

Authorization Code Exchange from the client side

Next.js Serverless Deployment Model

Where Next.js shines is in the serverless deployment model, where you deploy all pages and API routes as separate serverless functions implemented using Vercel or AWS Lambda, for example.

In this model, you don't have a full-blown web framework running (like Express.js), but instead, the runtime will execute functions by passing them a request and a response object ((req, res) => { }). This is why we can't use traditional web frameworks (like Express.js) or any of the building blocks they offer for authenticating users in this model (like Passport.js) and creating sessions (express-sessions).

The following diagram illustrates how this model works: Next.js pages and API routes run as separate serverless functions. When the browser tries to access the TV Shows page (1), a function will take care of rendering and serving the page, effectively performing server-side rendering. This function will also call any APIs the page needs to fetch the necessary data (2).

Next.js Serverless Deployment Diagram

If the entire site has already been loaded, the rendering happens on the client whenever you visit another page. At that point, the client application makes all subsequent API calls directly. As you can see, this is where the line between the frontend and backend layers starts to become blurry.

Next.js SSR and API Call Diagram

Before we go into any specifics, it's important to call out that there are two specific flavors of the serverless model when it comes to authentication, depending on where you need the user to be available.

Serverless with the user on the frontend

One flavor which is very similar to the Static Site is shown in the diagram below. Whenever you need to render a page on the server side or call an API route, you will execute these calls in a serverless function. In this model, authentication takes place on the client-side:

  1. The client application redirects the user to Auth0.
  2. When users log in successfully, Auth0 redirects them to the client application.
  3. The client application completes the code exchange with Auth0 and retrieves the user's id_token and access_token, which it stores in memory.

Next.js client-side authentication for the Serverless Deployment model

Any page rendered by the serverless function can only return content that all users can access without needing any form of authentication. When your client application loads the page, it can execute some logic to fetch user-specific content by calling API routes or calling other APIs.

Next.js client-side logic in the Serverless Deployment model

In the diagram above, you can see an example of how this could work:

  1. A serverless function (SSR) can render the /account page.
  2. In turn, this serverless function also calls the /api/pricing-tiers API route, which simply returns the different subscription types available in the application (for example, Free, Developer, Enterprise). This is public information, so authentication is not required to access the pricing data.
  3. When the client-side is ready, it can now call the /api/billing-info API route and provide the user's access token. The client-side can then render content that is specific to the user. Accessing user billing information requires authentication.

Only the client-side and the API routes are aware of the user, while the server-side rendering of pages could only render public content, which is perfectly fine for SEO purposes.

Serverless with the user on the backend

The second flavor in this model involves a serverless function that needs the user when rendering the page. When that happens, you can't just rely on client-side authentication.

Next.js Serverless Diagram

This diagram is similar to the one from the frontend model, except for a few subtle but important differences:

  1. A serverless function (SSR) can render the /account page, but the browser sends a session cookie to it.
  2. This serverless function can call /api/billing-info by forwarding the session cookie. The serverless function can now render user content.
  3. This serverless function can also call the /api/pricing-tiers API route (nothing changes here from the frontend model).

In this example, the server side can completely render the user's account page.

You'll also need to consider the case where the site is already fully loaded, and the user navigates to the account page. In that case, the client-side can call the endpoints directly, and the cookie will automatically be provided to the API route:

  1. The client application can call an API route that requires authentication (because the browser will automatically provide the session cookie).
  2. The client application can also call API routes that don't require authentication.

Next.js Serverless API Call Diagram

To accommodate this use case, we've recently published an early access version of @auth0/nextjs-auth0, which takes care of authentication in the serverless deployment model using the Authorization Code Grant. This package also creates a session for the authenticated user using an HttpOnly cookie, which mitigates the most common XSS attack.

The nextjs-auth0 library is currently in an experimental state, and support is given at best effort. However, we'd love to hear your feedback on taking this library to the finish line with features you need to successfully secure your Next.js applications.

To use the library you'll start by initializing an instance of the SDK:

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

export default initAuth0({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  scope: 'openid profile',
  redirectUri: 'http://localhost:3000/api/callback',
  postLogoutRedirectUri: 'http://localhost:3000/',
  session: {
    cookieSecret: 'some-very-very-very-very-very-very-very-long-secret',
    cookieLifetime: 60 * 60 * 8
  }
});

You can execute the following command to generate a suitable string for the session secret easily:

node -e "console.log(crypto.randomBytes(32).toString('hex'))"

Once an instance is created, you'll add a few API routes in your Next.js application, which will handle all the necessary logic. Here is an example of the Login handler:

import auth0 from '../../utils/auth0';

export default async function login(req, res) {
  try {
    await auth0.handleLogin(req, res);
  } catch(error) {
    res.status(error.status || 500).end(error.message)
  }
}

And that's it! You can now access the user on the server side:

Profile.getInitialProps = async ({ req, res }) => {
  if (typeof window === 'undefined') {
    const { user } = await auth0.getSession(req);
    if (!user) {
      res.writeHead(302, {
        Location: '/api/login'
      });
      res.end();
      return;
    }

    return { user }
  }
}

By implementing the Profile handler, you'll also have an endpoint which exposes the user's information to the client application. As such, you can call API routes within your Next.js application without having to worry about access tokens or any of that. This is possible because you store the user's session in a cookie, which is sent along with every request your client makes to your API route.

async componentDidMount() {
  const res = await fetch('/api/me');
  if (res.ok) {
    this.setState({
      session: await res.json()
    })
  }
}

Note that authentication takes place on the server in this model, meaning that the client isn't aware that the user is logged in. You could make it aware by providing that information in the initial state or through an endpoint, but you won't expose any id_token or access_token to the client. That information remains on the server side.

What exactly happens behind the curtains here?

When using nextjs-auth0, the user logs in using the Authorization Code Grant. At a high level, the client application redirects the user to Auth0 (1,2), who handles all the required authentication and authorization logic (sign-up, sign-in, MFA, consent, and so on). Once users log in, Auth0 redirects them to your application with an Authorization Code in the query string (3).

Authorization Code Exchnage diagram

The server side (or better, the serverless function) then exchanges (4) that code for an id_token and optionally an access_token and refresh_token. After the library validates the id_token, it creates a session and stores it in an encrypted cookie (5). Each time you render a page on the server side, or you call an API route, you send the session cookie to the serverless functions, which can then access the session and any relevant user information.

Calling an External API

The pages and API routes can all access the user's session, but that is not the case for external APIs, typically hosted on other (sub-)domains. When consuming those APIs, you'll need to provide them with an access_token to authorize the user to access their protected resources.

When you need to call an external API on behalf of the user, you must proxy that call through a Next.js API route. These routes will have access to the user's session and, depending on how the user logged in, that session might contain the user's information. Optionally, the session may also have the following:

  • id_token
  • access_token
  • refresh_token

Identity icons for users, authentication, and API interaction graphics

When the Next.js API route needs to call an external API on behalf of the user, it can extract the access_token from the session and add it to the Authorization header of the HTTP call.

Next.js external API with access token diagram model

The following example illustrates how you would create an API route which extracts the access_token from the session and then uses it to call a downstream API.

import auth0 from '../../utils/auth0';

export default async function getBillingInfo(req, res) {
  try {
    const { accessToken } = await auth0.getSession(req);

    const client = new BillingApiClient(accessToken);
    return client.getBillingInfo();
  } catch(error) {
    console.error(error)
    res.status(error.status || 500).end(error.message)
  }
}

The biggest difference with the frontend model is that the server will be aware of the user authentication status when rendering pages. As such, the server side won't be limited to loading public data. The server side could also load data specific to the user and render that information.

You can find a full Auth0 example in the official Next.js repository.

The Custom Server Approach

A very common (but legacy) deployment model you'll see with Next.js is where you use a custom server to host the Next.js application. You can implement a custom server in Next.js using something like Express.js. It works like this:

  • The custom server accepts the request.
  • The custom server calls the app.getRequestHandler() method to get a Next.js request handler.
  • The custom server forwards the request to the Next.js request handler.

With this approach, the custom server can act as a proxy and process the request before Next.js handles it:

Custom Server Approach Next.js handling request diagram

Middlewares, which run before the Next.js server-side rendering, provide building blocks to your application like:

  • Authentication
  • Sessions
  • Enforcing authentication and authorization
  • Rate limiting

All the building blocks and tools that you can use today with Express.js are available to you in this custom server model. Here's the most basic example of how you would host your Next.js application with Express.js:

const next = require('next');
const express = require('express');
...

const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare()
  .then(() => {
    const server = express();
    ...
    passport.use(auth0);
    ...
    server.use(passport.initialize());
    server.use(passport.session());
    server.use(myApiRoutes);
    ...
    server.get('*', (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, (err) => {
      if (err) {
        throw err;
      }

      console.log('Listening on http://localhost:3000')
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

When it comes to authenticating users in the custom server model, you can use Passport.js (which is by far the most popular framework for authentication in Node.js) in combination with passport-auth0. When the user logs in, Passport.js creates a session using express-session and persists it in the browser using an HttpOnly cookie.

Custom Server model cookie HttpOnly diagram

Once the user has a session, they can access pages or call API endpoints that require authentication using Next.js API routes or traditional Express endpoints. The client application sends the session cookie along with each request, which makes the user information available on the server-side automatically.

Custom Server model server-side exchange diragram

In this model, you basically use Node.js and Express to build a regular web application. Authentication, database access, and other features are already a solved problem.

Visit the Next.js Authentication Tutorial for a complete example of how to create a Next.js application using the custom server model.

A Legacy Model?

The Next.js docs no longer list this model because it's the least optimal from a cost and performance point of view:

  • You miss out on the advantages of the serverless deployment model, such as distributed points of failure, infinite scalability, and low cost.
  • You can't generate static sites, which could be something you want if you're running a public-facing website. Static sites are fast and inexpensive to host.

Conclusion

And with that, we've covered the different deployment models which exist today for the Next.js framework, and we've explained the best way to authenticate in those models and the reasoning behind it.

If this tutorial has helped you better decide what to use for your deployment model, let us know in the comments below!

About Auth0

Auth0 provides a platform to authenticate, authorize, and secure access for applications, devices, and users. Security and application teams rely on Auth0's simplicity, extensibility, and expertise to make identity work for everyone. Safeguarding billions of login transactions each month, Auth0 secures identities so innovators can innovate, and empowers global enterprises to deliver trusted, superior digital experiences to their customers around the world.

For more information, visit https://auth0.com or follow @auth0 on Twitter.