skip to content

Every deploy of an Express dashboard using express-session signs all users out; what in the session wiring causes it, and how do you fix it?

level: seniorimportance: must knowfreq 48%

answer

  1. where the records live
  2. what signs the cookie
  3. stable across instances and releases
  4. RedisStore, secret array, prefix

basics

~20 s

Sessions die with the process when express-session runs on its default MemoryStore, and cookies stop verifying when the secret changes per deploy. Wire connect-redis RedisStore, keep the secret stable and rotate it as an array.

solid answer

~40 s

Two wiring faults cause it. First, no `store` was passed, so express-session uses an in-process `MemoryStore` that every restart empties; browsers keep sending valid cookies that now point at nothing. The fix is a shared store such as connect-redis's `RedisStore`, with `resave: false` and `saveUninitialized: false`. Second, the `secret` that signs the session-ID cookie changes per deploy — generated at boot, or replaced in config — so every existing cookie fails verification and the user gets a fresh, empty session even though the record is still in Redis. Keep the secret identical across instances and releases, and rotate it as an array with the new secret first: express-session signs with the first element and verifies with all. Also keep the cookie `name` and the store `prefix` stable, because changing either orphans existing sessions.

code

javascript · 20 lines
javascript
const express = require('express')
const session = require('express-session')
const { RedisStore } = require('connect-redis')
const { createClient } = require('redis')

const redisClient = createClient({ url: process.env.REDIS_URL })
redisClient.connect().catch(console.error)

const app = express()
app.set('trust proxy', 1)

app.use(session({
  store: new RedisStore({ client: redisClient, prefix: 'dashboard:' }),
  // newest secret first; older ones still verify existing cookies
  secret: process.env.SESSION_SECRETS.split(','),
  name: 'dashboard.sid',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true, httpOnly: true, sameSite: 'lax', maxAge: 8 * 60 * 60 * 1000 }
}))

go deeper

for a junior

Recall that sessions need a shared store and a stable secret to survive a restart.

for a middle

Explain how the signed cookie is verified, why a changed secret discards every session, and how RedisStore, prefix and ttl fit together.

for a senior

Work the incident: separate store loss from signature failure by checking whether records still exist, then fix secret handling, naming and rotation.

for a principal

Own the secret lifecycle and the session settings as shared platform configuration, so no team can ship a per-process secret or an unnamed store.

## The scenario A dashboard runs on Express 5 with **express-session**, and its login handler stores the user ID in the session. After every deploy, every user is signed out. Some users also report random logouts between deploys when the app runs on more than one instance. Nothing in the logs looks like an error. Several independent wiring faults produce exactly this, and a real incident is often two of them at once. ## Cause 1: the default store If the `session()` call has no `store`, express-session creates a **MemoryStore**: a plain object in the Node process's heap. A deploy starts new processes, so the map is empty. Browsers still send their `connect.sid` cookie, the signature still verifies, but there is no record for that ID, so express-session starts a new, empty session. With several instances, each one has its own map, which explains the random logouts too. express-session prints a warning about this only when `NODE_ENV` is `production`, so a container without that variable starts silently. **Fix: an external store.** connect-redis exports a `RedisStore` class that takes a connected Redis client: - `client` — the connected client instance; - `prefix` — the key prefix, default `sess:`, useful when several apps share one Redis; - `ttl` — seconds to keep a record when the session cookie has no expiry, default `86400` (one day); when the cookie has an `expires`, connect-redis uses the time remaining instead; - `touch` support — connect-redis implements `touch` as an `EXPIRE`, so with `resave: false` an active but unchanged session keeps its TTL fresh (`disableTouch` turns that off). Pair it with `resave: false` and `saveUninitialized: false`, which is what connect-redis's own setup example uses. ## Cause 2: a secret that changes The session cookie holds the ID plus an **HMAC signature** computed with the `secret` option. On each request express-session verifies that signature; if it does not match, the cookie is ignored and a new session begins. The README states it plainly: changing the secret value invalidates all existing sessions. Common ways a deploy changes it: 1. The secret is generated at start-up, for example with `crypto.randomBytes`, so each process has its own. 2. A pipeline injects a new value on each release. 3. Instances read different values, so a cookie signed by one instance fails on another. With a Redis store in place, this cause is easy to misread: the records are all still in Redis, yet everyone is signed out, because no browser presents a cookie that verifies. **Fix: a stable secret, rotated as an array.** Load the secret from configuration, identical on every instance. To rotate it without a mass logout, pass an array with the **new secret first**: express-session signs new cookies with the first element and accepts a signature from any element. Remove the old secret once cookies signed with it have aged out. The general reasoning about signing keys and their rotation belongs to the framework-neutral session-identifier material; here it is the option's shape that matters. ## Cause 3: renamed keys Two quieter renames orphan every session too: - changing the cookie `name` (default `connect.sid`) — browsers still send the old name, which the new release no longer reads; - changing the connect-redis `prefix` — the new release looks up `newprefix:<id>` while the records sit under the old prefix. ## A checklist for deploy-proof sessions | Setting | Deploy-proof value | What goes wrong otherwise | |---|---|---| | `store` | a shared store such as `RedisStore` | MemoryStore is emptied by every restart | | `secret` | from config, the same on all instances; an array when rotating | every cookie fails verification | | `name` | fixed across releases | old cookies are ignored | | RedisStore `prefix` | fixed across releases | old records are never found | | `resave` / `saveUninitialized` | `false` / `false` | a write per request and a record per cookieless request | | `cookie.maxAge` | set deliberately | the Redis record falls back to the one-day `ttl` | Two checks confirm a fix before the next deploy: restart one instance and verify a signed-in browser stays signed in, and send the same cookie to two instances and verify both recognise it. What happens when the Redis tier itself is unavailable, and whether Redis is the right home for sessions at all, are store-selection questions for the framework-neutral session-store material.

  • Users who stay idle for a day are signed out even though cookie.maxAge is unset; why?
    Without `cookie.maxAge` or `expires`, connect-redis gives each record its `ttl`, which defaults to 86400 seconds. Each request by an active user refreshes it through `touch` or a save, but a user idle for longer than a day finds the Redis key expired, while the browser cookie, which has no expiry, is still sent. Set `cookie.maxAge` or `ttl` deliberately to match the intended session length.
  • How do you remove an old secret from the array safely?
    Keep the old secret in second place until every cookie signed with it has expired or been re-signed, which is bounded by the cookie's `maxAge` or the store's TTL. Then drop it. Removing it earlier signs out anyone still presenting a cookie signed only with the old value.
  • Why do some users get logged out randomly between deploys when the app runs on several instances?
    If any instance still runs on MemoryStore, or instances read different secrets, a request that lands on a different instance either finds no record or fails signature verification. A shared store and one secret list on every instance make any instance able to serve any session.

  • Moving to Redis alone guarantees sessions survive every deploy.
  • A random secret generated at start-up is the most secure setting.
  • To rotate the secret, put the new one last in the array.
  • connect-redis keeps records forever unless cookie.maxAge is set.
  • Renaming the session cookie is harmless because the store still has the data.