Skip to main content

Next.js

Official

Authentication for Next.js with full App Router and server-component support.

Keeping sessions in Redis

~7 min

By default the SDK encrypts the whole session, tokens included, into the session cookie. With a `storage`, the access, refresh, and ID tokens are kept in Redis, or any other key-value store, and the cookie carries only a sealed reference to the session. A token reaches the browser only if the application sends it there itself.

Session cookie (default)Storage
Cookie contentsThe encrypted tokens and claimsAn encrypted reference to the session
Cookie sizeGrows with the tokens, chunked past 4 KBA few hundred bytes
Several instancesWork, the cookie carries everythingShare sessions through the storage
End a session from the serverOnly by recording a logout that refuses the cookie, as back-channel logout doesDelete it from the storage
InfrastructureNoneA store every instance can reach

Keep sessions in Redis

1

Install a Redis client

The SDK does not depend on a Redis client, so install the one the application uses. Both ioredis and redis (node-redis) work.

bash
npm install ioredis
2

Create the storage

createRedisStorage() turns a Redis client into a storage. Create it once, in a module the provider and the proxy both import. Pass { prefix: 'my-app:' } as the second argument when several applications share one Redis database.

lib/storage.ts
ts
import Redis from 'ioredis'
import { createRedisStorage } from '@thunderid/nextjs/server'
export const storage = createRedisStorage(new Redis(process.env.REDIS_URL!))
3

Pass the storage to the provider

The provider keeps the storage on the server. It is not passed to client components.

app/layout.tsx
tsx
import { ThunderIDProvider } from '@thunderid/nextjs/server'
import { storage } from '@/lib/storage'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<ThunderIDProvider storage={storage}>{children}</ThunderIDProvider>
</body>
</html>
)
}
4

Pass the storage to the proxy

Next.js bundles the server components and the proxy separately, so the proxy needs the storage too. Add it as the second argument of the proxy you already have, keeping its handler. When a request reaches code that was not given the storage, the SDK logs an error asking for the same storage on both, and the request looks signed out.

proxy.ts
ts
import { createRouteMatcher, thunderIDProxy } from '@thunderid/nextjs/server'
import { storage } from '@/lib/storage'
const isProtectedRoute = createRouteMatcher(['/dashboard(.*)'])
export default thunderIDProxy(
async (thunderid, request) => {
if (isProtectedRoute(request)) {
return thunderid.protectRoute()
}
},
{ storage },
)
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}
Note

A TCP Redis client such as ioredis does not run on the Edge runtime. On Next.js 16 the proxy runs on the Node.js runtime. On Next.js 15.5 or later, set runtime to nodejs in the config of middleware.ts. On earlier releases, use a Redis client that talks HTTP.

Check it works

1

Sign in

In the browser's developer tools, open the session cookie. It is a single cookie of a few hundred bytes, with no .0, .1 chunks.

2

List the sessions in Redis

One key appears per signed-in session, named thunderid:0:<client id>:session:<session id>. It holds the session's tokens, and under claims, what the session cookie used to carry. With a prefix, put it in front of the pattern.

bash
redis-cli -u "$REDIS_URL" --scan --pattern 'thunderid:*:*:session:*'
redis-cli -u "$REDIS_URL" TTL <key>
3

End the session from the server

Delete the key. The next request is signed out, in every browser tab and on every instance.

bash
redis-cli -u "$REDIS_URL" DEL <key>

How sessions behave with storage

Sign-inWrites the session to the storage and sets the reference cookie. The sign-in in progress, with the PKCE verifier, is kept there for 15 minutes, so the callback can reach any instance
Token refreshThe proxy writes the new tokens to the storage. When two instances refresh at once and the refresh token rotates, the one whose refresh fails uses the tokens the other stored, if they are there by then
Sign-out`signOutAction()` deletes the session from the storage, so a copy of a reference cookie stops working. When it cannot, it keeps the cookies and reports failure, so the user can sign out again
Back-channel logoutRemoves the session from the storage and records the logout there, so it reaches every instance
Existing sessionsA cookie issued before `storage` was configured carries its own session and is still read until it expires
Removing storageSessions that hold a reference cookie are signed out
Refresh during sign-outA refresh that read the session just before sign-out removed it can write it back, within one storage round trip

Split the storage or use another store

1

Give each kind of data its own storage

storage also takes a storage for each kind of data: session (sessions and their tokens), sessionState (a sign-in in progress), transient, and persisted. A kind left out goes to session. Without session, sessions stay in the cookie and the kinds left out stay in the memory of the process. Every instance needs the same session and sessionState storage, since a sign-in can finish on a different instance from the one where it started.

lib/storage.ts
ts
export const storage = {
session: createRedisStorage(sessionsRedis),
sessionState: createRedisStorage(shortLivedRedis),
}
2

Use a store other than Redis

Any object that implements Storage works. setData receives the time to live in seconds, and getData returns '{}' for a missing key and throws only when the read fails. A client that parses JSON values on read, such as @upstash/redis by default, needs that turned off (automaticDeserialization).

lib/storage.ts
ts
import type { Storage } from '@thunderid/nextjs/server'
export const storage: Storage = {
getData: async (key) => (await myStore.get(key)) ?? '{}',
setData: (key, value, ttlSeconds) => myStore.set(key, value, { ttl: ttlSeconds }),
removeData: (key) => myStore.delete(key),
}

Beyond this guide

Storage reference

Middleware

Back-channel logout

Express SDK

ThunderID LogoThunderID Logo

Product

DocsAPIsSDKs
© Copyright Linux Foundation Europe.For web site terms of use, trademark policy and other project policies please see https://linuxfoundation.eu/en/policies.