• Stars
    star
    1,903
  • Rank 23,501 (Top 0.5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Next.js SDK for signing in with Auth0

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 supports the following tooling versions:

  • Node.js: 12 LTS and newer LTS releases are supported.
  • Next.js: >=10

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 the Dynamic API Route

Go to your Next.js application and create a catch-all, 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();

Executing handleAuth() 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.

Note: handleAuth requires Node.js and so will not work on Cloudflare Workers or Vercel Edge Runtime.

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.

There are two additional ways to check for an authenticated user; one for Next.js pages using withPageAuthRequired and one for Next.js API routes using withApiAuthRequired.

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

API Reference

Server (for Node.js)

import * from @auth0/nextjs-auth0

Edge (for Middleware and the 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.

More Repositories

1

node-jsonwebtoken

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
JavaScript
17,054
star
2

java-jwt

Java implementation of JSON Web Token (JWT)
Java
5,403
star
3

express-jwt

connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
TypeScript
4,396
star
4

jwt-decode

Decode JWT tokens; useful for browser applications.
JavaScript
2,913
star
5

angular2-jwt

Helper library for handling JWTs in Angular apps
TypeScript
2,606
star
6

angular-jwt

Library to help you work with JWTs on AngularJS
JavaScript
1,259
star
7

lock

Auth0's signin solution
JavaScript
1,121
star
8

go-jwt-middleware

A Middleware for Go Programming Language to check for JWTs on HTTP requests
Go
978
star
9

auth0.js

Auth0 headless browser sdk
JavaScript
949
star
10

auth0-spa-js

Auth0 authentication for Single Page Applications (SPA) with PKCE
TypeScript
873
star
11

auth0-react

Auth0 SDK for React Single Page Applications (SPA)
TypeScript
820
star
12

node-jwks-rsa

A library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint.
JavaScript
767
star
13

node-jws

JSON Web Signatures
JavaScript
698
star
14

angular-storage

A storage library for AngularJS done right
JavaScript
644
star
15

repo-supervisor

Scan your code for security misconfiguration, search for passwords and secrets. 🔍
JavaScript
632
star
16

node-auth0

Node.js client library for the Auth0 platform.
JavaScript
586
star
17

cosmos

🔭 Auth0 Design System
JavaScript
545
star
18

JWTDecode.swift

A JWT decoder for iOS, macOS, tvOS, and watchOS
Swift
545
star
19

nginx-jwt

Lua script for Nginx that performs reverse proxy auth using JWT's
JavaScript
534
star
20

SimpleKeychain

A simple Keychain wrapper for iOS, macOS, tvOS, and watchOS
Swift
488
star
21

auth0-python

Auth0 SDK for Python
Python
445
star
22

express-openid-connect

An Express.js middleware to protect OpenID Connect web applications.
JavaScript
434
star
23

react-native-auth0

React Native toolkit for Auth0 API
JavaScript
432
star
24

JWTDecode.Android

A library to help you decode JWTs for Android
Java
428
star
25

docs

Auth0 documentation
JavaScript
364
star
26

auth0-PHP

PHP SDK for Auth0 Authentication and Management APIs.
PHP
355
star
27

wt-cli

Webtask CLI - all you need is code
JavaScript
322
star
28

auth0.net

.NET client for the Auth0 Authentication & Management APIs.
C#
296
star
29

passport-auth0

Auth0 authentication strategy for Passport.js
JavaScript
283
star
30

rules

Rules are code snippets written in JavaScript that are executed as part of the authentication pipeline in Auth0
JavaScript
283
star
31

react-native-lock

[DEPRECATED] A wrapper of Lock to use with React Native (iOS & Android)
Java
277
star
32

Auth0.swift

Auth0 SDK for Apple platforms
Swift
275
star
33

auth0-java

Java client library for the Auth0 platform
Java
265
star
34

Lock.swift

A Swift & iOS framework to authenticate using Auth0 and with a Native Look & Feel
Swift
251
star
35

auth0-cli

Build, manage and test your Auth0 integrations from the command line
Go
232
star
36

auth0-deploy-cli

The Auth0 Deploy CLI is a tool that helps you manage your Auth0 tenant configuration. It integrates into your development workflows as a standalone CLI or as a node module.
JavaScript
231
star
37

laravel-auth0

Laravel SDK for Auth0 Authentication and Management APIs.
PHP
224
star
38

ruby-auth0

Ruby toolkit for Auth0 API
Ruby
189
star
39

cxn

cXn: extensible open-source CDN
Ruby
178
star
40

jwks-rsa-java

Java
178
star
41

passport-windowsauth

Windows Authentication strategy for Passport.js
JavaScript
175
star
42

Auth0.Android

Android toolkit for Auth0 API
Kotlin
171
star
43

auth0-angular

Auth0 SDK for Angular Single Page Applications
TypeScript
167
star
44

styleguide

🖌 Conjunction of design patterns, components and resources used across our products.
Stylus
160
star
45

terraform-provider-auth0

The Auth0 Terraform Provider is the official plugin for managing Auth0 tenant configuration through the Terraform tool.
Go
155
star
46

Lock.Android

Android Library to authenticate using Auth0 and with a Native Look & Feel
Java
140
star
47

jwt-handbook-samples

JWT Handbook code samples
JavaScript
139
star
48

wordpress

WordPress Plugin for Auth0 Authentication
PHP
133
star
49

node-samlp

SAML Protocol support for node (only IdP for now)
JavaScript
129
star
50

passport-linkedin-oauth2

Passport Strategy for LinkedIn OAuth 2.0
JavaScript
115
star
51

omniauth-auth0

OmniAuth strategy to login with Auth0
Ruby
112
star
52

symfony

Symfony SDK for Auth0 Authentication and Management APIs.
PHP
110
star
53

go-auth0

Go SDK for the Auth0 Management API.
Go
107
star
54

node-odata-parser

OData query string parser for node.js.
JavaScript
106
star
55

node-jwa

JSON Web Algorithms
JavaScript
98
star
56

auth0-vue

Auth0 authentication SDK for Vue.js apps
TypeScript
95
star
57

lock-passwordless

Auth0 Lock Passwordless [DEPRECATED]
JavaScript
93
star
58

express-jwt-authz

Validate the JWT scope to authorize access to an endpoint
JavaScript
93
star
59

auth0-angular2

84
star
60

auth0-aspnetcore-authentication

SDK for integrating Auth0 in ASPNET Core
C#
82
star
61

open-source-template

A template for open source projects at Auth0
81
star
62

auth0-authorization-extension

Auth0 Extension that adds authorization features to your account
JavaScript
81
star
63

react-browserify-spa-seed

Seed / Boilerplate project to create your own SPA using React, Browserify and ReworkCSS
JavaScript
80
star
64

node-baas

Node.js implementation of Bcrypt as a micro service.
JavaScript
79
star
65

password-sheriff

Password policies made easy.
JavaScript
77
star
66

sharelock-android

Sharelock Android app
Java
76
star
67

auth0-oidc-client-net

OIDC Client for .NET Desktop and Mobile applications
C#
75
star
68

node-oauth2-jwt-bearer

Monorepo for libraries that protect Node APIs with OAuth2 Bearer JWTs
TypeScript
75
star
69

idtoken-verifier

Lightweight RSA JWT verification
JavaScript
73
star
70

ad-ldap-connector

Auth0 AD and LDAP connector
JavaScript
70
star
71

nodejs-msi

Build an MSI Windows Installer for a node.js application using WIX Toolset.
PowerShell
70
star
72

auth0-spring-security-api

Spring Security integration with Auth0 to secure your API with JWTs
Java
70
star
73

id-generator

Generates random ids with a prefix (a la Stripe)
JavaScript
66
star
74

node-saml

SAML assertion creation for node
JavaScript
65
star
75

webtask-scripts

JavaScript
61
star
76

TouchIDAuth

A library for passwordless authentication using TouchID & JWT
Objective-C
60
star
77

passport-azure-ad-oauth2

OAuth 2.0 authentication Passport strategies for Windows Azure Active Directory
JavaScript
59
star
78

spa-pkce

JavaScript
58
star
79

discourse-plugin

Discourse plugin to authenticate with auth0.
Ruby
58
star
80

auth0-multitenant-spa-api-sample

JQuery SPA + Node.js API with multi-tenant support
JavaScript
58
star
81

sandboxjs

Sandbox node.js code like a boss
JavaScript
58
star
82

multitenant-jwt-auth

This sample shows how to implement an API that authenticates using JWTs. It supports mutiple tenants and JWT blacklisting.
JavaScript
54
star
83

coreos-mongodb

CoreOS MongoDB units
52
star
84

shiny-auth0

Auth0 shiny proxy
JavaScript
51
star
85

auth0-flutter

Auth0 SDK for Flutter
Dart
49
star
86

auth0-cordova

Auth0 integration for Cordova apps
JavaScript
49
star
87

sharelock-osx

Swift
47
star
88

disyuntor

A circuit-breaker implementation for node.js
TypeScript
47
star
89

passport-wsfed-saml2

passport strategy for both WS-fed and SAML2 protocol
JavaScript
47
star
90

php-jwt-example

Php JWT example.
PHP
46
star
91

auth0-aspnet-owin

Auth0 ASP.NET 4.5 Owin/Katana Authentication Handler
JavaScript
46
star
92

webauthn.me

webauthn.me, learn more about the Web Authentication API or try the debugger.
JavaScript
43
star
93

auth0-custom-password-reset-hosted-page

An example on how to do a custom reset password hosted page.
HTML
41
star
94

magic

Auth0 Cryptography Toolkit
JavaScript
40
star
95

auth0-java-mvc-common

Contains common helper classes and api client logic that are used across our Java MVC libraries
Java
39
star
96

single-page-app-seed

A very opinionated seed for creating Single Page Apps that uses NO framework at all. Just a bunch of component libs
JavaScript
39
star
97

auth0-dotnet-templates

Auth0 Templates for .NET
C#
38
star
98

webtask-workshop

37
star
99

kbd

Styles for <kbd> tags.
HTML
37
star
100

express-oauth2-bearer

Experimental Middleware for express.js to validate access tokens.
JavaScript
36
star