Convert Figma logo to code with AI

auth0 logonextjs-auth0

Next.js SDK for signing in with Auth0

2,013
381
2,013
60

Top Related Projects

24,088

Authentication for the Web.

71,327

The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Firebase Javascript SDK

OpenID Certified™ OAuth 2.0 Authorization Server implementation for Node.js

Quick Overview

The auth0/nextjs-auth0 repository is an SDK for implementing authentication in Next.js applications using Auth0. It provides a simple and secure way to add login, logout, and user profile functionality to Next.js projects, leveraging Auth0's identity platform.

Pros

  • Easy integration with Next.js applications
  • Supports both API Routes and Edge Middleware
  • Provides built-in security features and best practices
  • Offers flexible configuration options

Cons

  • Limited to Auth0 as the authentication provider
  • May require additional setup for complex authentication scenarios
  • Learning curve for developers new to Auth0
  • Potential overhead for simple applications

Code Examples

  1. Protecting an API route:
import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0';

export default withApiAuthRequired(async function myApiRoute(req, res) {
  const { user } = await getSession(req, res);
  res.json({ protected: 'My Secret', id: user.sub });
});
  1. Adding login and logout buttons:
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>;
}
  1. Protecting client-side rendered pages:
import { withPageAuthRequired } from '@auth0/nextjs-auth0/client';

export default withPageAuthRequired(function Profile({ user }) {
  return <div>Hello {user.name}</div>;
});

Getting Started

  1. Install the package:

    npm install @auth0/nextjs-auth0
    
  2. Create an Auth0 account and set up an application.

  3. Add environment variables to your .env.local file:

    AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'
    AUTH0_BASE_URL='http://localhost:3000'
    AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN'
    AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
    AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'
    
  4. Wrap your app in the UserProvider:

    import { UserProvider } from '@auth0/nextjs-auth0/client';
    
    export default function App({ Component, pageProps }) {
      return (
        <UserProvider>
          <Component {...pageProps} />
        </UserProvider>
      );
    }
    
  5. Add login and logout API routes:

    // pages/api/auth/[...auth0].js
    import { handleAuth } from '@auth0/nextjs-auth0';
    
    export default handleAuth();
    

Now you can use the SDK's components and hooks in your Next.js application to implement authentication features.

Competitor Comparisons

24,088

Authentication for the Web.

Pros of next-auth

  • More flexible and customizable, supporting a wide range of authentication providers
  • Open-source with a large community, leading to frequent updates and improvements
  • Built-in support for database adapters, allowing easy integration with various databases

Cons of next-auth

  • Requires more setup and configuration compared to nextjs-auth0
  • May have a steeper learning curve for beginners
  • Less specialized support for Auth0-specific features

Code Comparison

next-auth:

import NextAuth from "next-auth"
import Providers from "next-auth/providers"

export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET
    }),
  ],
})

nextjs-auth0:

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

export default handleAuth();

next-auth offers more flexibility in provider configuration, while nextjs-auth0 provides a simpler setup specifically for Auth0.

Both libraries are popular choices for authentication in Next.js applications. next-auth is more versatile and community-driven, suitable for projects requiring multiple authentication providers or custom setups. nextjs-auth0 is ideal for projects exclusively using Auth0, offering a more streamlined integration with Auth0 services.

71,327

The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Pros of Supabase

  • Offers a full-stack solution with database, authentication, and storage
  • Provides real-time capabilities out of the box
  • Includes a user-friendly dashboard for managing data and services

Cons of Supabase

  • Less specialized in authentication compared to NextJS Auth0
  • May have a steeper learning curve for developers new to the platform
  • Potentially more complex setup for projects that only need authentication

Code Comparison

NextJS Auth0:

import { useUser } from '@auth0/nextjs-auth0/client';

export default function Profile() {
  const { user, error, isLoading } = useUser();
  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;
  return user && <div>Hello {user.name}!</div>;
}

Supabase:

import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react';

export default function Profile() {
  const supabase = useSupabaseClient();
  const user = useUser();
  if (!user) return <div>Loading...</div>;
  return <div>Hello {user.email}!</div>;
}

Both repositories provide authentication solutions, but Supabase offers a broader range of features beyond authentication. NextJS Auth0 is more focused on authentication and integrates seamlessly with Next.js applications. Supabase provides a complete backend solution, including database and storage, which may be beneficial for projects requiring more than just authentication.

Firebase Javascript SDK

Pros of firebase-js-sdk

  • Comprehensive suite of tools beyond authentication (database, storage, hosting)
  • Real-time data synchronization capabilities
  • Extensive documentation and community support

Cons of firebase-js-sdk

  • Potential vendor lock-in to Google's ecosystem
  • Less flexibility in customizing authentication flows
  • Higher learning curve for full platform utilization

Code Comparison

nextjs-auth0:

import { useUser } from '@auth0/nextjs-auth0/client';

export default function Profile() {
  const { user, error, isLoading } = useUser();
  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;
  return user && <div>Hello {user.name}!</div>;
}

firebase-js-sdk:

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log("User is signed in:", user.displayName);
  } else {
    console.log("No user is signed in.");
  }
});

Both libraries offer authentication solutions, but firebase-js-sdk provides a broader set of features for building full-stack applications. nextjs-auth0 is more focused on authentication for Next.js applications, offering a simpler integration for that specific framework. The code examples demonstrate the different approaches to user authentication and state management in each library.

OpenID Certified™ OAuth 2.0 Authorization Server implementation for Node.js

Pros of node-oidc-provider

  • Highly customizable and flexible OpenID Connect implementation
  • Supports a wide range of OIDC features and extensions
  • Can be used as a standalone identity provider or integrated into existing applications

Cons of node-oidc-provider

  • Steeper learning curve due to its comprehensive nature
  • Requires more setup and configuration compared to nextjs-auth0
  • Less opinionated, which may lead to more decision-making for developers

Code Comparison

nextjs-auth0:

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

export default handleAuth();

node-oidc-provider:

const Provider = require('oidc-provider');
const configuration = { /* ... */ };
const oidc = new Provider('http://localhost:3000', configuration);

app.use('/oidc', oidc.callback());

The nextjs-auth0 example shows a simple setup for handling authentication routes, while the node-oidc-provider example demonstrates initializing the provider with custom configuration and integrating it into an existing application.

node-oidc-provider offers more control and flexibility but requires more setup, whereas nextjs-auth0 provides a more streamlined approach specifically tailored for Next.js applications using Auth0 as the identity provider.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

nextjs-auth0

The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications.

Release Coverage Downloads License CircleCI

📚 Documentation - 🚀 Getting Started- 💻 API Reference - 💬 Feedback

Documentation

  • QuickStart- our guide for adding Auth0 to your Next.js app.
  • FAQs - Frequently asked questions about nextjs-auth0.
  • Examples - lots of examples for your different use cases.
  • Security - Some important security notices that you should check.
  • Architecture - Architectural overview of the SDK.
  • Testing - Some help with testing your nextjs-auth0 application.
  • Deploying - How we deploy our example app to Vercel.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

Installation

Using npm:

npm install @auth0/nextjs-auth0

This library requires Node.js 16 LTS and newer LTS versions.

Auth0 Configuration

Create a Regular Web Application in the Auth0 Dashboard.

If you're using an existing application, verify that you have configured the following settings in your Regular Web Application:

  • Click on the "Settings" tab of your application's page.
  • Scroll down and click on the "Show Advanced Settings" link.
  • Under "Advanced Settings", click on the "OAuth" tab.
  • Ensure that "JsonWebToken Signature Algorithm" is set to RS256 and that "OIDC Conformant" is enabled.

Next, configure the following URLs for your application under the "Application URIs" section of the "Settings" page:

  • Allowed Callback URLs: http://localhost:3000/api/auth/callback
  • Allowed Logout URLs: http://localhost:3000/

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:

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

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.

Continue setup depending on your router:

Page Router

Add the Dynamic API Route

Create a dynamic API route handler under the /pages/api directory:

  • Create an auth directory under the /pages/api/ directory.
  • Create a [auth0].js file under the newly created auth directory.

The path to your dynamic API route file would be /pages/api/auth/[auth0].js. Populate that file as follows:

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

export default handleAuth();
Add the UserProvider to Custom App

Wrap your pages/_app.js component with the UserProvider component:

// pages/_app.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0/client';

export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}
Consume Authentication

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:

// pages/index.js
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>;
}

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.

App Router

Check out Using this SDK with React Server Components before proceeding.

Add the Dynamic API Route

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:

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

export const GET = handleAuth();
Add the UserProvider to your layout

Wrap your app/layout.js component with the UserProvider component:

// 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>
  );
}
Consume Authentication

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:

// 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>;
}

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.

The cookie can be written from middleware, route handlers and server actions.

For other comprehensive examples, see the EXAMPLES.md document.

API Reference

Server

For Node

import * from @auth0/nextjs-auth0

For Edge runtime

import * from @auth0/nextjs-auth0/edge

Client (for the Browser)

import * from @auth0/nextjs-auth0/client

Testing helpers

import * from @auth0/nextjs-auth0/testing

Visit the auto-generated API Docs for more details

Cookies and Security

All cookies will be set to HttpOnly, SameSite=Lax and will be set to Secure if the application's AUTH0_BASE_URL is https.

The HttpOnly setting will make sure that client-side JavaScript is unable to access the cookie to reduce the attack surface of XSS attacks.

The SameSite=Lax setting will help mitigate CSRF attacks. Learn more about SameSite by reading the "Upcoming Browser Behavior Changes: What Developers Need to Know" blog post.

Caching and Security

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:

// _app.jsx
function App({ Component, pageProps }) {
  return (
    <UserProvider loginUrl="/foo/api/auth/login" profileUrl="/foo/api/auth/me">
      <Component {...pageProps} />
    </UserProvider>
  );
}

Also, any links to login or logout should include the basePath:

<a href="/foo/api/auth/login">Login</a><br />
<a href="/foo/api/auth/logout">Logout</a>

You should configure the baseUrl (or the AUTH0_BASE_URL environment variable). For example:

# .env.local
AUTH0_BASE_URL=http://localhost:3000/foo

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.jsx
export default MySsrPage = () => <></>;

const getFullReturnTo = (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';
};

export const getServerSideProps = (ctx) => {
  const returnTo = getFullReturnTo(ctx.req);
  return withPageAuthRequired({ 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 are using Static HTML Export with Next.js.
  • 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.

For end to end tests, have a look at how we use a mock OIDC Provider.

Deploying

For deploying, have a look at how we deploy our example app to Vercel.

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please read the following:

Vulnerability Reporting

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 Logo

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.

NPM DownloadsLast 30 Days