For almost a year now, the team at Next.js has been building the foundations for the future of Next.js, a future based on the React architecture, which includes Server Components, Server Actions, and much more.
With the introduction of Next.js 13.4 a few months ago, the new App router architecture with support for React Server Components, nested routes, layouts, and new data fetching design, was promoted to stable and is the recommended option for newly built Next.js applications.
These new fundamental changes in architecture and APIs on Next.js meant that many libraries with support for Next.js had to undergo changes to fully utilize and benefit from the latest release.
Auth0's first SDK for Next.js dates back to 2021. Since then, we have been committed to the Next.js community by providing a robust, scalable, and developer-friendly SDK for implementing user authentication. We are very happy to announce the stable release of the Auth0 Next.js SDK v3 with support for App Router, Edge Runtime, and Responses in Middleware. We’ve created this quickstart guide that demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js SDK.
What Do I Need to Do With Existing Applications Using Pages Router?
Not much. Like Next.js, the Auth0 Next.js SDK v3
continues to support the Pages Router and the new App Router. When updating to the new SDK, there are three considerations to keep in mind:
- As is the case for Next.js
v13.4
, the new SDK requires Nodev16
LTS or newer releases. - For TypeScript applications, differences in function signatures that support both the Pages and App Router may require you to use explicit declarations for the
request
andresponse
objects to help TypeScript infer their type correctly. For example:Before:
import { withApiAuthRequired } from '@auth0/nextjs-auth0' export default withApiAuthRequired(async function handler(req, res) { res.status(200).json({}); });
After:
import { NextApiRequest, NextApiResponse } from 'next'; import { withApiAuthRequired } from '@auth0/nextjs-auth0' export default withApiAuthRequired(async function handler(req: NextApiRequest, res: NextApiResponse) { res.status(200).json({}); });
- The
/401
handler has been removed: As of Next.jsv13.1
, you can now return responses from middleware. As such, the unauthorized handler has been removed in favor of an unauthorized response.
If you need to migrate your application from the Auth0 Next.js SDK v2
to the latest version, please follow our official v3
migration guide.
Working with the New App Router
Working with the new App Router requires a shift in the architecture and project structure of your Next.js application, and as a result of this new architecture, there are a few limitations that you need to understand before implementing authentication for your application or working with cookies and sessions in general.
These are the steps to add authentication to your Next.js application using the latest version of the Auth0 Next.js SDK:
Install the Auth0 SDK for Next.js
First and foremost, install the Auth0 Next.js SDK using the following command:
npm install @auth0/nextjs-auth0
Add the dynamic API route
As was the case for Pages Router, the Auth0 SDK automatically creates a series of API routes or endpoints to handle essential authentication features such as login, logout, and getting user information.
For the Auth0 Next.js SDK to create such routes, it is necessary to create a catch-all, dynamic API route handler under the /app/api
directory. Technically speaking, you don’t need to use the api
directory anymore to specify API routes. However, our SDK follows that convention for simplicity and clarity.
Then, create a route.js
or route.ts
file under the /app/api/auth/[auth0]/
directory and populate it with the following code:
import { handleAuth } from '@auth0/nextjs-auth0';
export const GET = handleAuth();
Make the Auth0 hooks accessible throughout your application
When working on the client side of your Next.js application, you can use the useUser()
hook from the Auth0 Next.js SDK to retrieve information about the current user and session. Since this hook leverages the React Context API to manage and communicate the authentication state of the user, you’ll have to wrap your components with a UserProvider
.
When using the Next.js App Router, you should wrap your root layout with UserProvider
as follows:
// app/layout.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0/client';
export default function App({ children }) {
return (
<UserProvider>
<body>{children}</body>
</UserProvider>
);
}
Access user and session information
You can check if a user is authenticated by verifying that the user
object returned by the useUser()
hook is defined. Additionally, you can log in or log out of your users from the client layer of your Next.js application by redirecting them to the corresponding automatically-generated route.
Here is an example of a client component accessing and using user information to build a basic login, logout user flow.
// pages/index.js
'use client';
import { useUser } from '@auth0/nextjs-auth0/client';
export default function Index() {
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>;
}
What’s Next
With the release of the Auth0 Next.js SDK v3, we are excited to continue supporting the Next.js community with a comprehensive solution for user authentication and route protection.
In this article, we only covered the basics, and if you want to learn more about how to secure your application, please check the official GitHub repository for the SDK as well as some examples of practical use cases, or check out our Next.js code samples. To get started on Next.js Authentication with Auth0 check out this blog post.
Auth0 by Okta is committed to providing our community and customers with a smooth yet robust developer experience to secure their applications. We continue to look for ways to improve our products and shape the future of authentication. We'd love to hear about your experience using our latest iteration of the Auth0 Next.js SDK.
Thanks for reading!