Convert Figma logo to code with AI

auth0 logonextjs-auth0

Next.js SDK for signing in with Auth0

2,149
410
2,149
68

Top Related Projects

26,329

Authentication for the Web.

76,348

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

26,329

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.

76,348

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 Downloads License

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

Documentation

  • QuickStart- our guide for adding Auth0 to your Next.js app.
  • Examples - lots of examples for your different use cases.
  • Security - Some important security notices that you should check.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

1. Install the SDK

npm i @auth0/nextjs-auth0

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

2. Add the environment variables

Add the following environment variables to your .env.local file:

AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=
AUTH0_SECRET=
APP_BASE_URL=

The AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET can be obtained from the Auth0 Dashboard once you've created an application. This application must be a Regular Web Application.

The AUTH0_SECRET is the key used to encrypt the session and transaction cookies. You can generate a secret using openssl:

openssl rand -hex 32

The APP_BASE_URL is the URL that your application is running on. When developing locally, this is most commonly http://localhost:3000.

[!IMPORTANT]
You will need to register the follwing URLs in your Auth0 Application via the Auth0 Dashboard:

  • Add http://localhost:3000/auth/callback to the list of Allowed Callback URLs
  • Add http://localhost:3000 to the list of Allowed Logout URLs

3. Create the Auth0 SDK client

Create an instance of the Auth0 client. This instance will be imported and used in anywhere we need access to the authentication methods on the server.

Add the following contents to a file named lib/auth0.ts:

import { Auth0Client } from "@auth0/nextjs-auth0/server"

export const auth0 = new Auth0Client()

4. Add the authentication middleware

Create a middleware.ts file in the root of your project's directory:

import type { NextRequest } from "next/server"

import { auth0 } from "./lib/auth0"

export async function middleware(request: NextRequest) {
  return await auth0.middleware(request)
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
}

[!NOTE]
If you're using a src/ directory, the middleware.ts file must be created inside the src/ directory.

You can now begin to authenticate your users by redirecting them to your application's /auth/login route:

import { auth0 } from "@/lib/auth0"

export default async function Home() {
  const session = await auth0.getSession()

  if (!session) {
    return (
      <main>
        <a href="/auth/login?screen_hint=signup">Sign up</a>
        <a href="/auth/login">Log in</a>
      </main>
    )
  }

  return (
    <main>
      <h1>Welcome, {session.user.name}!</h1>
    </main>
  )
}

[!IMPORTANT]
You must use <a> tags instead of the <Link> component to ensure that the routing is not done client-side as that may result in some unexpected behavior.

Customizing the client

You can customize the client by using the options below:

OptionTypeDescription
domainstringThe Auth0 domain for the tenant (e.g.: example.us.auth0.com or https://example.us.auth0.com). If it's not specified, it will be loaded from the AUTH0_DOMAIN environment variable.
clientIdstringThe Auth0 client ID. If it's not specified, it will be loaded from the AUTH0_CLIENT_ID environment variable.
clientSecretstringThe Auth0 client secret. If it's not specified, it will be loaded from the AUTH0_CLIENT_SECRET environment variable.
authorizationParametersAuthorizationParametersThe authorization parameters to pass to the /authorize endpoint. See Passing authorization parameters for more details.
clientAssertionSigningKeystring or CryptoKeyPrivate key for use with private_key_jwt clients. This can also be specified via the AUTH0_CLIENT_ASSERTION_SIGNING_KEY environment variable.
clientAssertionSigningAlgstringThe algorithm used to sign the client assertion JWT. This can also be provided via the AUTH0_CLIENT_ASSERTION_SIGNING_ALG environment variable.
appBaseUrlstringThe URL of your application (e.g.: http://localhost:3000). If it's not specified, it will be loaded from the APP_BASE_URL environment variable.
secretstringA 32-byte, hex-encoded secret used for encrypting cookies. If it's not specified, it will be loaded from the AUTH0_SECRET environment variable.
signInReturnToPathstringThe path to redirect the user to after successfully authenticating. Defaults to /.
sessionSessionConfigurationConfigure the session timeouts and whether to use rolling sessions or not. See Session configuration for additional details.
beforeSessionSavedBeforeSessionSavedHookA method to manipulate the session before persisting it. See beforeSessionSaved for additional details.
onCallbackOnCallbackHookA method to handle errors or manage redirects after attempting to authenticate. See onCallback for additional details.
sessionStoreSessionStoreA custom session store implementation used to persist sessions to a data store. See Database sessions for additional details.
pushedAuthorizationRequestsbooleanConfigure the SDK to use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server.
routesRoutesConfigure the paths for the authentication routes. See Custom routes for additional details.
allowInsecureRequestsbooleanAllow insecure requests to be made to the authorization server. This can be useful when testing with a mock OIDC provider that does not support TLS, locally. This option can only be used when NODE_ENV is not set to production.
httpTimeoutnumberInteger value for the HTTP timeout in milliseconds for authentication requests. Defaults to 5000 milliseconds
enableTelemetrybooleanBoolean value to opt-out of sending the library name and version to your authorization server via the Auth0-Client header. Defaults to true.

Routes

The SDK mounts 6 routes:

  1. /auth/login: the login route that the user will be redirected to to initiate an authentication transaction
  2. /auth/logout: the logout route that must be added to your Auth0 application's Allowed Logout URLs
  3. /auth/callback: the callback route that must be added to your Auth0 application's Allowed Callback URLs
  4. /auth/profile: the route to check the user's session and return their attributes
  5. /auth/access-token: the route to check the user's session and return an access token (which will be automatically refreshed if a refresh token is available)
  6. /auth/backchannel-logout: the route that will receive a logout_token when a configured Back-Channel Logout initiator occurs

Feedback

Contributing

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

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

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