@auth0/nextjs-auth0 is a library that provides authentication and authorization for Next.js applications using Auth0. It simplifies the process of integrating Auth0 into Next.js apps by providing a set of tools and utilities for handling user sessions, protecting routes, and managing user profiles.
What are @auth0/nextjs-auth0's main functionalities?
User Authentication
This feature allows you to handle user authentication with Auth0. The `handleAuth` function sets up the necessary routes for login, logout, and callback.
This feature allows you to protect API routes by ensuring that only authenticated users can access them. The `withApiAuthRequired` function wraps your API route handler to enforce authentication.
import { withApiAuthRequired } from '@auth0/nextjs-auth0';
export default withApiAuthRequired((req, res) => {
res.status(200).json({ message: 'This is a protected API route' });
});
Protecting Pages
This feature allows you to protect Next.js pages by ensuring that only authenticated users can access them. The `withPageAuthRequired` function wraps your page component to enforce authentication.
import { withPageAuthRequired } from '@auth0/nextjs-auth0';
const ProtectedPage = () => {
return <div>This is a protected page</div>;
};
export default withPageAuthRequired(ProtectedPage);
Fetching User Profile
This feature allows you to fetch and display the authenticated user's profile information. The `useUser` hook provides the user's data, loading state, and any errors.
next-auth is a complete open-source authentication solution for Next.js applications. It supports multiple authentication providers, including OAuth, email/password, and custom credentials. Compared to @auth0/nextjs-auth0, next-auth offers more flexibility in terms of provider options and customization but may require more configuration.
Firebase provides a suite of tools for building and managing web and mobile applications, including authentication. Firebase Authentication supports various authentication methods, such as email/password, phone, and social providers. Compared to @auth0/nextjs-auth0, Firebase offers a broader range of services beyond authentication, such as real-time databases and cloud functions, but may be more complex to integrate into a Next.js application.
Passport is a popular authentication middleware for Node.js. It supports a wide range of authentication strategies, including OAuth, OpenID, and custom strategies. Compared to @auth0/nextjs-auth0, Passport provides more granular control over the authentication process but requires more setup and configuration.
The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications.
Take note of the Client ID, Client Secret, and Domain values under the "Basic Information" section. You'll need these values in the next step.
Basic Setup
Configure the Application
You need to allow your Next.js application to communicate properly with Auth0. You can do so by creating a .env.local file under your root project directory that defines the necessary Auth0 configuration values as follows:
# 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'
You can execute the following command to generate a suitable string for the AUTH0_SECRET value:
You can see a full list of Auth0 configuration options in the "Configuration properties" section of the "Module config" document.
For more details about loading environment variables in Next.js, visit the "Environment Variables" document.
Add handleAuth() to your app, which creates the following route handlers under the hood that perform different parts of the authentication flow:
/api/auth/login: Your Next.js application redirects users to your identity provider for them to log in (you can optionally pass a returnTo parameter to return to a custom relative URL after login, for example /api/auth/login?returnTo=/profile).
/api/auth/callback: Your identity provider redirects users to this route after they successfully log in.
/api/auth/logout: Your Next.js application logs out the user.
/api/auth/me: You can fetch user profile information in JSON format.
You can now determine if a user is authenticated by checking that the user object returned by the useUser() hook is defined. You can also log in or log out your users from the frontend layer of your Next.js application by redirecting them to the appropriate automatically-generated route:
Next linting rules might suggest using the Link component instead of an anchor tag. The Link component is meant to perform client-side transitions between pages. As the links point to an API route and not to a page, you should keep them as anchor tags.
Create a catch-all, dynamic API route handler under the /app/api directory (strictly speaking you do not need to put API routes under /api but we maintain the convention for simplicity):
Create an api directory under the /app/ directory.
Create an auth directory under the newly created /app/api/ directory.
Create a [auth0] directory under the newly created auth directory.
Create a route.js file under the newly created [auth0] directory.
The path to your dynamic API route file will be /app/api/auth/[auth0]/route.js. Populate that file as follows:
You can now determine if a user is authenticated by checking that the user object returned by the useUser() hook is defined. You can also log in or log out your users from the frontend layer of your Next.js application by redirecting them to the appropriate automatically-generated route:
Next linting rules might suggest using the Link component instead of an anchor tag. The Link component is meant to perform client-side transitions between pages. As the links point to an API route and not to a page, you should keep them as anchor tags.
Using this SDK with React Server Components
Server Components in the App Directory (including Pages and Layouts) cannot write to a cookie.
If you rely solely on Server Components to read and update your session you should be aware of the following:
If you have a rolling session (the default for this SDK), the expiry will not be updated when the user visits your site. So the session may expire sooner than you would expect (you can use withMiddlewareAuthRequired to mitigate this).
If you refresh the access token, the new access token will not be persisted in the session. So subsequent attempts to get an access token will always result in refreshing the expired access token in the session.
If you make any other updates to the session, they will not be persisted between requests.
Many hosting providers will offer to cache your content at the edge in order to serve data to your users as fast as possible. For example Vercel will cache your content on the Vercel Edge Network for all static content and Serverless Functions if you provide the necessary caching headers on your response.
It's generally a bad idea to cache any response that requires authentication, even if the response's content appears safe to cache there may be other data in the response that isn't.
This SDK offers a rolling session by default, which means that any response that reads the session will have a Set-Cookie header to update the cookie's expiry. Vercel and potentially other hosting providers include the Set-Cookie header in the cached response, so even if you think the response's content can be cached publicly, the responses Set-Cookie header cannot.
Check your hosting provider's caching rules, but in general you should never cache responses that either require authentication or even touch the session to check authentication (eg when using withApiAuthRequired, withPageAuthRequired or even just getSession or getAccessToken).
Error Handling and Security
Errors that come from Auth0 in the redirect_uri callback may contain reflected user input via the OpenID Connect error and error_description query parameter. Because of this, we do some basic escaping on the message, error and error_description properties of the IdentityProviderError.
But, if you write your own error handler, you should not render the error message, or error and error_description properties without using a templating engine that will properly escape them for other HTML contexts first.
Base Path and Internationalized Routing
With Next.js you can deploy a Next.js application under a sub-path of a domain using Base Path and serve internationalized (i18n) routes using Internationalized Routing.
If you use these features the urls of your application will change and so the urls to the nextjs-auth0 routes will change. To accommodate this there are various places in the SDK that you can customise the url.
For example, if basePath: '/foo' you should prepend this to the loginUrl and profileUrl specified in your Auth0Provider:
For any pages that are protected with the Server Side withPageAuthRequired you should update the returnTo parameter depending on the basePath and locale if necessary.
// ./pages/my-ssr-page.jsxexportdefaultMySsrPage = () =><></>;
constgetFullReturnTo = (ctx) => {
// TODO: implement getFullReturnTo based on the ctx.resolvedUrl, ctx.locale// and your next.config.js's basePath and i18n settings.return'/foo/en-US/my-ssr-page';
};
exportconstgetServerSideProps = (ctx) => {
const returnTo = getFullReturnTo(ctx.req);
returnwithPageAuthRequired({ returnTo })(ctx);
};
Comparison with the Auth0 React SDK
We also provide an Auth0 React SDK, auth0-react, which may be suitable for your Next.js application.
The SPA security model used by auth0-react is different from the Web Application security model used by this SDK. In short, this SDK protects pages and API routes with a cookie session (see "Cookies and Security"). A SPA library like auth0-react will store the user's ID token and access token directly in the browser and use them to access external APIs directly.
You should be aware of the security implications of both models. However, auth0-react may be more suitable for your needs if you meet any of the following scenarios:
You do not need to access user data during server-side rendering.
You want to get the access token and call external API's directly from the frontend layer rather than using Next.js API routes as a proxy to call external APIs.
Testing
By default, the SDK creates and manages a singleton instance to run for the lifetime of the application. When testing your application, you may need to reset this instance, so its state does not leak between tests.
If you're using Jest, we recommend using jest.resetModules() after each test. Alternatively, you can look at creating your own instance of the SDK, so it can be recreated between tests.
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
What is Auth0?
Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?
This project is licensed under the MIT license. See the LICENSE file for more info.
The npm package @auth0/nextjs-auth0 receives a total of 189,421 weekly downloads. As such, @auth0/nextjs-auth0 popularity was classified as popular.
We found that @auth0/nextjs-auth0 demonstrated a not healthy version release cadence and project activity because the last version was released a year ago.Ā It has 45 open source maintainers collaborating on the project.
Package last updated on 06 Dec 2023
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.