githubEdit

triangleNext.js

Use oidc-spa in a Next.js App Router app.

Before you start

circle-exclamation

The example

This example shows the minimum wiring needed for a Next.js App Router app.

Installation

Note: Zodarrow-up-right is optional but highly recommended. Writing validators manually is error-prone, and skipping validation means losing early guarantees about what your auth server provides. You can use another validator though, it doesn't have to be Zod.

Required wiring

Initialize early on the client

Use instrumentation-client.ts to run oidcEarlyInit() as early as possible.

Wrap the app

Wrap the whole app in OidcInitializationGate.

In the example, this happens in app/layout.tsxarrow-up-right.

Add Next-specific adapters

The OidcInitializationGate and withLoginEnforced utils exported by oidc-spa cannot be used directly in Next.js as-is.

They need Next-specific adapters.

In the example, that adaptation lives in lib/oidc.tsxarrow-up-right.

Keep oidc-spa on the client

Anything that touches oidc-spa must run on the client.

Add "use client"; to those modules.

Important limitation

Next.js cannot know who the user is at render time when auth is handled by oidc-spa in the browser.

In practice, that means you give up most SSR auth-at-render-time benefits.

You should treat this setup as a SPA architecture running inside Next.js.

Routes in the example

  • / public landing page with login and logout controls

  • /protected guarded page using the custom Next-compatible withLoginEnforced

  • /admin-only guarded page with a simple role check

Creating an API server

Now that authentication is handled, there’s one last piece of the puzzle: your resource server, the backend your app will communicate with.

This can be any type of service: a REST API, tRPC server, or WebSocket endpoint, as long as it can validate access tokens issued by your IdP.

If you’re building it in JavaScript or TypeScript (for example, using Express), oidc-spa provides ready-to-use utilities to decode and validate access tokens on the server side.

You’ll find the full documentation here:

arrow-right-arrow-leftBackend Token Validationchevron-right

Last updated

Was this helpful?