Skip to main content

Express

Official

Middleware to protect Express routes and APIs with ThunderID.

Keeping sessions in Redis

~2 min

The Express session cookie carries only a session id. The tokens behind it live in the client's storage, which by default is the memory of the Node.js process, so a restart signs everyone out and each instance sees only its own sessions. Give the SDK a `storage` to keep them in Redis, or any other key-value store, instead.

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

Pass the storage to the middleware

createRedisStorage() turns a Redis client into a storage. Pass { prefix: 'my-app:' } as its second argument when several applications share one Redis database.

src/server.ts
ts
import Redis from 'ioredis'
import { createRedisStorage, thunderID } from '@thunderid/express'
app.use(
thunderID({
baseUrl: process.env.THUNDERID_BASE_URL,
clientId: process.env.THUNDERID_CLIENT_ID,
clientSecret: process.env.THUNDERID_CLIENT_SECRET,
storage: createRedisStorage(new Redis(process.env.REDIS_URL)),
}),
)
3

Check it works

Sign in, restart the server, and reload. You stay signed in. Each session is kept under <vendor>:0:<client id>:session:<session id>, where <vendor> is the configured vendor, thunderid by default.

bash
redis-cli -u "$REDIS_URL" --scan --pattern 'thunderid:*:*:session:*'

What is kept in Redis

TokensKept in the storage. The cookie is unchanged
Sign-in in progressKept in the storage for 15 minutes, as long as the sign-in cookie, so the callback can land on any instance
Embedded flow sessions and the back-channel logout indexKept in the storage, so `handleFlow()` and `handleBackchannelLogout()` work across instances
LifetimeA session expires `sessionCookie.expiryTime` seconds after it was last written
Client configurationStays in process memory. The client secret is never written to the storage

Beyond this guide

Client configuration

Storage reference

Next.js sessions in Redis

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.