Next-authmiddleware


Securing pages and API routes

You can easily protect client and server side rendered pages and API routes with NextAuth.js.

You can find working examples of the approaches shown below in the example project.

tip

The methods and both return an if a session is valid and if a session is invalid or has expired.

Securing Pages​

If data on a page is fetched using calls to secure API routes - i.e. routes which use or to access the session - you can use the React Hook to secure pages.

pages/client-side-example.js

Next.js (Middleware)​

With NextAuth.js 4.2.0 and Next.js 12, you can now protect your pages via the middleware pattern more easily. If you would like to protect all pages, you can create a file at the root or in the src directory (same level as your ) which looks like this:

/middleware.js

If you only want to secure certain pages, export a object with a :

For the time being, the middleware only supports as session strategy.

More details can be found here.

tip

To include all nested routes (sub pages like , ) you can pass to .

For other patterns check out the Next.js Middleware documentation.

You can protect server side rendered pages using the metho

Options

Environment Variables​

NEXTAUTH_URL​

When deploying to production, set the environment variable to the canonical URL of your site.

If your Next.js application uses a custom base path, specify the route to the API endpoint in full. More information about the usage of custom base path here.

e.g.

tip

When you're using a custom base path, you will need to pass the page prop to the . More information here.

note

Using System Environment Variables we automatically detect when you deploy to Vercel so you don't have to define this variable. Make sure Automatically expose System Environment Variables is checked in your Project Settings.

NEXTAUTH_SECRET​

Used to encrypt the NextAuth.js JWT, and to hash email verification tokens. This is the default value for the option in NextAuth and Middleware. Alternatively, you can also set , which is an alias, and is the preferred naming going forward.

tip

You can run - our CLI - in your project's root, and it will autogenerate a random value and put it in your file.

NEXTAUTH_URL_INTERNAL​

If provided, server-side calls will use this instead of . Useful in environments when the server doesn't

Context Provider

In your app’s entrypoint, you’ll see that your application is wrapped in a SessionProvider↗:

This context provider allows your application to access the session data from anywhere in your application, without having to pass it down as props:

Sometimes you might want to request the session on the server. To do so, prefetch the session using the helper function that provides, and pass it down to the client using :

Inclusion of on the Session

Create T3 App is configured to utilise the session callback↗ in the NextAuth.js config to include the user’s ID within the object.

This is coupled with a type declaration file to make sure the is typed when accessed on the object. Read more about ↗ on NextAuth.js’s docs.

The same pattern can be used to add any other data to the object, such as a field, but should not be misused to store sensitive data on the client.

Usage with tRPC

When using NextAuth.js with tRPC, you can create reusable, protected procedures using middleware↗. This allows you to create procedures that can only be accessed by authenticated users. sets all of this up for you, allowing you to easily access the session object within authenticated proc

Next.js

tip

You can create a helper function so you don't need to pass around:

auth.ts

When calling from the server-side i.e. in Route Handlers, React Server Components, API routes or in , we recommend using this function instead of to retrieve the object. This method is especially useful when you are using NextAuth.js with a database. This method can drastically reduce response time when used over on server-side, due to avoiding an extra to an API Route (this is generally not recommended in Next.js). In addition, or changed something.

requires passing the same object you would pass to when initializing NextAuth.js. To do so, you can export your NextAuth.js options in the following way:

In :

In API Routes:​

In App Router:​

You can also use in Next.js' server components:

info

In contrast to , which will return a only returns a .

danger

Currently, the underlying Next.js method only provides read accessThis means that the value is stripped away from in Server Components. Furthermore, there is a hard expiry on sessions, after which the user will be required to sign in again. (The default expiry is 30 days).

Caching​

Note that using this f

NextAuth.js

Open Source.Full Stack.Own Your Data.

Easy

  • Built in support for popular services
    (Google, Facebook, Auth0, Apple…)
  • Built in email / passwordless / magic link
  • Use with any username / password store
  • Use with OAuth 1.0 & 2.0 services

Flexible

  • Built for Serverless, runs anywhere
  • Bring Your Own Database - or none!
    (MySQL, Postgres, MSSQL, MongoDB…)
  • Choose database sessions or JWT
  • Secure web pages and API routes

Secure

  • HTTP POST + CSRF Token validation
  • JWT with JWS / JWE / JWK
  • Tab syncing, auto-revalidation, keepalives

Add authentication in minutes!

Server /pages/api/auth/[...nextauth].js

Client (App) /pages/_app.jsx

Client (Page) /pages/index.js

NextAuth.js is an open source people project.


next-authmiddleware