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
tobilling.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.
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:
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:
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.
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:
- Your static site redirects your users to Auth0 to log in.
- When your users successfully log in, Auth0 redirects them to your static site.
- Your static site performs a code exchange with Auth0 to retrieve the user's
id_token
andaccess_token
, which it stores in memory.
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.
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:
auth0-react
(usingauth0-spa-js
)useAuth
(usingauth0.js
)
With auth0-react
, for example, it's as easy as configuring your application like so:
// pages/_app.jsx
import { Auth0Provider } from '@auth0/auth0-react';
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 useSWR hook:
import { useAuth0 } from '@auth0/auth0-react';
import useSWR from 'swr';
export default function MyShows() {
const {
user,
isAuthenticated,
isLoading,
getAccessTokenSilently,
} = useAuth0();
const { data, error } = useSWR(
isLoading || !isAuthenticated ? null : '/api/my/shows',
async (url) => {
const accessToken = await getAccessTokenSilently({
audience: 'https://api/tv-shows',
scope: 'read:shows',
});
const res = await fetch(url, {
headers: {
authorization: `Bearer ${accessToken}`,
},
});
return res.json();
}
);
if (isLoading) {
return <div>Loading your user information...</div>;
}
if (!isAuthenticated) {
return <div>You must first sign in to access your subscriptions.</div>;
}
if (error) {
return <div>There was an error loading your subscriptions.</div>;
}
if (!data) {
return (
<div>
<h1>Subscriptions for {user.email}</h1>
<div>Loading your subscriptions ...</div>
</div>
);
}
return (
<div>
<h1>Subscriptions for {user.email}</h1>
<div>You have subscribed to a total of {data.length} shows...</div>
</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.
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).
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.
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:
- The client application redirects the user to Auth0.
- When users log in successfully, Auth0 redirects them to the client application.
- The client application completes the code exchange with Auth0 and retrieves the user's
id_token
andaccess_token
, which it stores in memory.
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.
In the diagram above, you can see an example of how this could work:
- A serverless function (SSR) can render the
/account
page. - 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. - 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.
This diagram is similar to the one from the frontend model, except for a few subtle but important differences:
- A serverless function (SSR) can render the
/account
page, but the browser sends a session cookie to it. - This serverless function can call
/api/billing-info
by forwarding the session cookie. The serverless function can now render user content. - 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:
- The client application can call an API route that requires authentication (because the browser will automatically provide the session cookie).
- The client application can also call API routes that don't require authentication.
To accommodate this use case, we've published @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.
To use the library you'll start by defining some environment variables in a .env.local
file in the root of your application:
# A long secret value used to encrypt the session cookie
AUTH0_SECRET=some-very-very-very-very-very-very-very-long-secret
# 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
Read the "Environment Variables" document for more details about loading environmental variables in Next.js.
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'))"
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
.
And that's it! You've now setup the server side of your application.
To setup the client side, wrap your pages/_app.js
component in the UserProvider
component.
// pages/_app.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';
export default function App({ Component, pageProps }) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
);
}
Now you can login, logout and access the user on the client.
// 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>;
};
Note that authentication takes place on the server in this model, meaning that the client isn't aware that the user is logged in. The useUser
hook makes it aware by accessing that information in the initial state or through the /api/auth/profile
endpoint, but it 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).
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
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.
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 { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
export default withApiAuthRequired(async function products(req, res) {
try {
const { accessToken } = await getAccessToken(req, res);
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:
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.
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.
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 by Okta takes a modern approach to customer identity and enables organizations to provide secure access to any application, for any user. Auth0 is a highly customizable platform that is as simple as development teams want, and as flexible as they need. Safeguarding billions of login transactions each month, Auth0 delivers convenience, privacy, and security so customers can focus on innovation. For more information, visit https://auth0.com.