Script Valley
JWT & Session Auth: Deep Dive
Session-Based AuthenticationLesson 3.2

backing sessions with Redis using connect-redis

default MemoryStore limitations, connect-redis setup, RedisStore configuration, session TTL in Redis, production readiness, session key naming

Backing Sessions with Redis

Redis Session Store

The default MemoryStore stores sessions in Node.js process memory. It leaks memory over time, does not survive server restarts, and cannot be shared across multiple instances. Use Redis in production.

const { createClient } = require('redis');
const RedisStore = require('connect-redis').default;

const redisClient = createClient({
  url: process.env.REDIS_URL
});
await redisClient.connect();

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    secure: true,
    sameSite: 'strict',
    maxAge: 24 * 60 * 60 * 1000
  }
}));

Sessions are stored in Redis as hash keys prefixed sess: by default. Each session has a TTL matching maxAge โ€” Redis automatically expires them, so there is no cleanup job to write.

With Redis backing sessions, you can run multiple Node.js instances behind a load balancer and any instance can serve any user's request โ€” a prerequisite for horizontal scaling.

One Redis instance is a single point of failure. For high availability, use Redis Sentinel or Redis Cluster. For development and staging, a single instance is fine.

Up next

session fixation attacks and how to prevent them

Sign in to track progress

backing sessions with Redis using connect-redis โ€” Session-Based Authentication โ€” JWT & Session Auth: Deep Dive โ€” Script Valley โ€” Script Valley