Learn How to Implement Redis Sessions in NestJS
server-side session
Overview
A web application needs to remember who a user is between requests. The classic answer is a server-side session: the server keeps the user's data, and the browser holds only a small cookie with a session ID. The default session store in Express keeps everything in the memory of one Node process, which is lost on every restart and cannot be shared between several instances. Redis solves both problems. It is a fast in-memory data store with built-in expiry, so sessions survive restarts, can be shared by any number of NestJS instances, and expire on their own. In this material you will learn how to run Redis, connect to it from NestJS, configure express-session with connect-redis, type the session data, build login and logout, protect routes with guards, set safe cookie options, control session lifetime, revoke a user's sessions from the server, test the whole flow, and avoid the common mistakes.
Who this is for: Backend developers who know the basics of NestJS (modules, controllers, providers) and want server-side sessions backed by Redis.
Prerequisites: Node.js 18 or later, basic TypeScript, and the basics of NestJS. Docker is useful for running Redis, but not required.
What you will be able to do after this material:
- Explain how sessions, cookies, and Redis fit together
- Run Redis and connect to it from NestJS with a clean provider
- Configure
express-sessionwith a Redis store - Add typed data to
req.session - Build login and logout that resist session fixation
- Protect routes with guards, roles, and a current-user decorator
- Set secure cookie, CORS, and proxy options
- Control idle and absolute session lifetime
- List and revoke sessions for a user
- Test and debug sessions
Structure:
| Module | Topic |
|---|---|
| 1 | How sessions and Redis work |
| 2 | Project setup and Redis |
| 3 | A Redis provider in NestJS |
| 4 | Session middleware |
| 5 | Typing the session data |
| 6 | Login and logout |
| 7 | Guards and decorators |
| 8 | Cookies, CORS, and proxies |
| 9 | Session lifetime |
| 10 | Managing sessions in Redis |
| 11 | Testing and common problems |
| 12 | Capstone project and best practices |
This lesson uses NestJS with the default Express adapter. Fastify needs different session packages.
Module 1: How Sessions and Redis Work
Objectives
- Describe the session flow
- Compare sessions with tokens
- Explain why Redis suits session storage
Lesson
The session flow has four steps:
| Step | What happens |
|---|---|
| 1. Login | The server checks the credentials and creates a session record |
| 2. Cookie | The server sends a cookie holding only the session ID, signed with a secret |
| 3. Next requests | The browser sends the cookie, and the server loads the record by ID |
| 4. Logout or expiry | The record is deleted, and the ID stops working |
The data (user ID, role) stays on the server. The browser only holds an opaque ID, so nothing sensitive is exposed, and the server can end a session at any time.
Sessions compared with JWT tokens:
| Point | Server-side session | Stateless JWT |
|---|---|---|
| Where the data lives | On the server (Redis) | Inside the token |
| Logging a user out everywhere | Easy: delete the records | Hard: tokens stay valid until they expire |
| Revoking one device | Easy | Needs a deny list |
| Server lookup per request | One Redis read | None |
| Token size | Tiny cookie | Larger |
| Best for | Browser apps, admin tools, anything needing instant revocation | Service-to-service calls, mobile APIs |
Neither is always better. Sessions in Redis give instant control, at the price of one fast lookup per request.
Why Redis for sessions:
| Reason | Benefit |
|---|---|
| In-memory speed | Sub-millisecond reads |
| Built-in expiry (TTL) | Sessions clean themselves up |
| Shared by all instances | Any server can handle any request |
| Survives app restarts | Users stay logged in during deployments |
| Simple key-value model | One key for each session |
The default MemoryStore in express-session is not meant for production. It leaks memory, loses every session on restart, and cannot be shared between processes.
Takeaway
A session keeps user data on the server and only an ID in the cookie, and Redis provides a fast, shared, self-expiring home for that data.
Exercise 1
List two situations where you would choose sessions over JWT, and one where you would choose JWT.
Module 2: Project Setup and Redis
Objectives
- Create the project and install the packages
- Run Redis locally
- Configure environment variables
Lesson
Create a project and install the packages:
npm i -g @nestjs/cli
nest new session-demo
cd session-demo
npm i express-session connect-redis redis @nestjs/config bcrypt class-validator class-transformer
npm i -D @types/express-session @types/bcrypt
| Package | Role |
|---|---|
express-session |
The session middleware |
connect-redis |
Stores sessions in Redis |
redis |
The Redis client (node-redis) |
@nestjs/config |
Reads environment variables |
bcrypt |
Hashes passwords |
class-validator, class-transformer |
Validates request bodies |
Run Redis with Docker. Create docker-compose.yml:
services:
redis:
image: redis:7-alpine
command: ["redis-server", "--requirepass", "devpassword"]
ports:
- "6379:6379"
volumes:
- redis-data:/data
volumes:
redis-data:
docker compose up -d
docker compose exec redis redis-cli -a devpassword ping # PONG
Environment variables. Create .env, and keep it out of version control:
NODE_ENV=development
PORT=3000
REDIS_URL=redis://:devpassword@localhost:6379/0
SESSION_SECRET=change-this-to-a-long-random-string
SESSION_TTL_HOURS=8
CORS_ORIGIN=http://localhost:5173
Generate a strong secret with node -e "console.log(require('crypto').randomBytes(48).toString('hex'))".
Load the configuration in app.module.ts:
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}
TypeScript note. With import session from "express-session", set "esModuleInterop": true in tsconfig.json. Without it, write import * as session from "express-session".
Takeaway
Install the session packages, run Redis with a password, and keep the secret and the URL in environment variables.
Exercise 2
Start Redis with Docker, confirm it answers PING, and store and read a key with redis-cli.
Module 3: A Redis Provider in NestJS
Objectives
- Create one shared Redis client
- Inject it where it is needed
- Close it cleanly on shutdown
Lesson
Create the client once, and share it through a NestJS provider. First, a token and a type:
// src/redis/redis.constants.ts
import { createClient } from "redis";
export const REDIS_CLIENT = "REDIS_CLIENT";
export type RedisClient = ReturnType<typeof createClient>;
Then a global module:
// src/redis/redis.module.ts
import { Global, Inject, Module, OnApplicationShutdown } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { createClient } from "redis";
import { REDIS_CLIENT, RedisClient } from "./redis.constants";
@Global()
@Module({
providers: [
{
provide: REDIS_CLIENT,
inject: [ConfigService],
useFactory: async (config: ConfigService): Promise<RedisClient> => {
const client = createClient({ url: config.getOrThrow<string>("REDIS_URL") });
client.on("error", (error) => console.error("Redis error:", error.message));
await client.connect();
return client;
},
},
],
exports: [REDIS_CLIENT],
})
export class RedisModule implements OnApplicationShutdown {
constructor(@Inject(REDIS_CLIENT) private readonly client: RedisClient) {}
async onApplicationShutdown(): Promise<void> {
await this.client.quit();
}
}
Import it in AppModule:
imports: [ConfigModule.forRoot({ isGlobal: true }), RedisModule],
Why this design:
| Choice | Reason |
|---|---|
| A factory provider | The connection is asynchronous, and Nest waits for it before starting |
| One client for the app | Redis connections are reused, so there is no connection for each request |
@Global() |
Any module can inject the client without importing RedisModule |
An error listener |
An unhandled client error would crash the process |
quit() on shutdown |
Pending commands finish before the connection closes |
Use the client in any service:
@Injectable()
export class CacheService {
constructor(@Inject(REDIS_CLIENT) private readonly redis: RedisClient) {}
async ping() {
return this.redis.ping();
}
}
Enable shutdown hooks in main.ts with app.enableShutdownHooks(), so that onApplicationShutdown runs when the process receives a stop signal.
Connection resilience. The client reconnects automatically. For production, add a reconnect strategy and a connect timeout:
createClient({
url,
socket: { connectTimeout: 5000, reconnectStrategy: (retries) => Math.min(retries * 100, 3000) },
});
Takeaway
Create one Redis client with an async provider, share it through a global module, and close it on shutdown.
Exercise 3
Add an endpoint that returns the result of ping(), and stop Redis to see how the app behaves.
Module 4: Session Middleware
Objectives
- Configure
express-sessionwith a Redis store - Choose each option on purpose
- Keep the setup reusable for tests
Lesson
Session middleware is registered on the Express app in main.ts. Put the setup in its own function, so that tests can reuse it:
// src/session.setup.ts
import { INestApplication } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import session from "express-session";
import { RedisStore } from "connect-redis";
import { REDIS_CLIENT, RedisClient } from "./redis/redis.constants";
export function setupSession(app: INestApplication) {
const config = app.get(ConfigService);
const redis = app.get<RedisClient>(REDIS_CLIENT);
const isProduction = config.get("NODE_ENV") === "production";
const ttlHours = Number(config.get("SESSION_TTL_HOURS") ?? 8);
app.use(
session({
store: new RedisStore({ client: redis, prefix: "sess:" }),
name: "sid",
secret: config.getOrThrow<string>("SESSION_SECRET"),
resave: false,
saveUninitialized: false,
rolling: true,
cookie: {
httpOnly: true,
secure: isProduction,
sameSite: "lax",
maxAge: ttlHours * 60 * 60 * 1000,
},
}),
);
}
connect-redis version 7 exports the store as a default (import RedisStore from "connect-redis"), and version 8 uses the named export shown here. Check the README of the version you install.
Use it in main.ts:
import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import { ValidationPipe } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { AppModule } from "./app.module";
import { setupSession } from "./session.setup";
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const config = app.get(ConfigService);
app.set("trust proxy", 1);
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
app.enableShutdownHooks();
setupSession(app);
await app.listen(config.get("PORT") ?? 3000);
}
bootstrap();
The options and why:
| Option | Value | Reason |
|---|---|---|
store |
RedisStore |
Sessions live in Redis, not in memory |
prefix |
"sess:" |
Groups the keys, and avoids clashes with other data |
name |
"sid" |
A neutral cookie name that does not reveal the stack |
secret |
From the environment | Signs the cookie so it cannot be forged |
resave |
false |
Do not rewrite unchanged sessions to Redis |
saveUninitialized |
false |
Do not create sessions for visitors who never log in |
rolling |
true |
Renew the cookie on each response (idle timeout, Module 9) |
cookie.httpOnly |
true |
JavaScript in the page cannot read the cookie |
cookie.secure |
true in production |
The cookie is sent only over HTTPS |
cookie.sameSite |
"lax" |
Limits cross-site requests (Module 8) |
cookie.maxAge |
Hours in milliseconds | Session lifetime |
The secret can be an array for rotation. The first one signs new cookies, and the others are still accepted for verification:
secret: [config.getOrThrow("SESSION_SECRET"), config.get("SESSION_SECRET_OLD")].filter(Boolean),
saveUninitialized: false matters. With true, every anonymous request (including health checks and crawlers) would create a Redis key.
Takeaway
Register express-session with a RedisStore, a secret from the environment, and safe cookie options, in a function that tests can reuse.
Exercise 4
Add the session setup, call a route that sets req.session.views, and look at the key in Redis.
Module 5: Typing the Session Data
Objectives
- Add your own fields to
req.session - Keep the stored data small
- Share the types across the project
Lesson
By default, req.session knows nothing about your fields, and TypeScript rejects req.session.userId. Extend the SessionData interface of express-session:
// src/types/express-session.d.ts
import "express-session";
declare module "express-session" {
interface SessionData {
userId?: number;
role?: "user" | "admin";
loggedInAt?: number;
userAgent?: string;
ip?: string;
}
}
Make sure the file is included by tsconfig.json (the default include covers src). Now the fields are typed:
req.session.userId = 42;
req.session.role = "admin";
What to store. Keep the session small, and store identifiers, not objects.
| Store | Do not store |
|---|---|
| User ID | The whole user record |
| Role (if checks must be fast) | Passwords or password hashes |
| Login time, IP, user agent | Tokens, card numbers, or other secrets |
| Small preferences | Large lists or files |
The user record can change while the session is alive (a role change, a ban). Store the ID, and load the current record when you need it:
const user = await this.users.findById(req.session.userId);
If you copy a role into the session for speed, remember that it is stale until the next login (Module 10 shows how to revoke).
Session ID and data. The browser holds the ID in the cookie, and Redis holds the data under sess:<id>:
sess:Zy3... -> {"cookie":{...},"userId":42,"role":"user","loggedInAt":1735689600000}
Where the session is available. req.session exists in controllers and guards through the Express request. Type the request with Request from express:
import { Request } from "express";
@Get("me")
me(@Req() req: Request) {
return { userId: req.session.userId };
}
Takeaway
Extend SessionData for type safety, and store only small identifiers, never secrets or whole records.
Exercise 5
Add the type declaration and a GET /whoami route that returns the stored userId, or null.
Module 6: Login and Logout
Objectives
- Validate credentials with a service
- Create a safe session on login
- Destroy it completely on logout
Lesson
A users service (replace the in-memory list with your database):
// src/users/users.service.ts
import { Injectable } from "@nestjs/common";
export interface User {
id: number;
email: string;
passwordHash: string;
role: "user" | "admin";
}
@Injectable()
export class UsersService {
private readonly users: User[] = [
{ id: 1, email: "ada@example.com", passwordHash: "$2b$10$replace-with-a-real-bcrypt-hash", role: "admin" },
];
async findByEmail(email: string) {
return this.users.find((user) => user.email === email) ?? null;
}
async findById(id: number) {
return this.users.find((user) => user.id === id) ?? null;
}
}
Create real hashes with bcrypt.hash(password, 10) when users register.
An auth service:
// src/auth/auth.service.ts
import { Injectable } from "@nestjs/common";
import * as bcrypt from "bcrypt";
import { UsersService } from "../users/users.service";
@Injectable()
export class AuthService {
constructor(private readonly users: UsersService) {}
async validate(email: string, password: string) {
const user = await this.users.findByEmail(email);
const hash = user?.passwordHash ?? "$2b$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalid";
const valid = await bcrypt.compare(password, hash);
return user && valid ? user : null;
}
}
Comparing against a dummy hash when the user does not exist keeps the response time similar, so attackers cannot tell which emails exist.
A request body:
// src/auth/login.dto.ts
import { IsEmail, IsString, MinLength } from "class-validator";
export class LoginDto {
@IsEmail() email: string;
@IsString() @MinLength(8) password: string;
}
The controller. Two details matter: regenerate the session ID on login, to prevent session fixation, and wait for the save before responding:
// src/auth/auth.controller.ts
import { Body, Controller, HttpCode, Post, Req, Res, UnauthorizedException } from "@nestjs/common";
import { Request, Response } from "express";
import { AuthService } from "./auth.service";
import { LoginDto } from "./login.dto";
@Controller("auth")
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post("login")
@HttpCode(200)
async login(@Body() dto: LoginDto, @Req() req: Request) {
const user = await this.auth.validate(dto.email, dto.password);
if (!user) throw new UnauthorizedException("Invalid email or password");
await new Promise<void>((resolve, reject) =>
req.session.regenerate((error) => (error ? reject(error) : resolve())),
);
req.session.userId = user.id;
req.session.role = user.role;
req.session.loggedInAt = Date.now();
req.session.userAgent = req.get("user-agent");
req.session.ip = req.ip;
await new Promise<void>((resolve, reject) =>
req.session.save((error) => (error ? reject(error) : resolve())),
);
return { id: user.id, email: user.email };
}
@Post("logout")
@HttpCode(200)
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
await new Promise<void>((resolve, reject) =>
req.session.destroy((error) => (error ? reject(error) : resolve())),
);
res.clearCookie("sid");
return { ok: true };
}
}
Session fixation is an attack where the attacker plants a known session ID in the victim's browser, and then uses it after the victim logs in. Calling regenerate issues a new ID at login, so the planted ID becomes useless.
Logout must do three things: delete the record in Redis (destroy), clear the cookie in the browser (clearCookie, with the same name and options as the original), and return a clear response.
Register the controller, the service, and the users service in an AuthModule, and import it in AppModule.
Try it:
curl -i -c cookies.txt -H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"correct-password"}' \
http://localhost:3000/auth/login
curl -b cookies.txt http://localhost:3000/whoami
curl -b cookies.txt -X POST http://localhost:3000/auth/logout
Takeaway
Validate credentials, regenerate the session ID on login, wait for the save, and destroy the record and the cookie on logout.
Exercise 6
Implement login and logout, confirm the key appears in Redis after login and disappears after logout.
Module 7: Guards and Decorators
Objectives
- Protect routes with a guard
- Add role checks
- Read the current user cleanly
Lesson
A guard decides whether a request may continue. A session guard checks that the session holds a user:
// src/auth/session-auth.guard.ts
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { Request } from "express";
@Injectable()
export class SessionAuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
if (!request.session?.userId) throw new UnauthorizedException("Please log in");
return true;
}
}
Apply it to a route or a whole controller:
@UseGuards(SessionAuthGuard)
@Get("profile")
profile(@Req() req: Request) {
return this.users.findById(req.session.userId!);
}
A role guard with a decorator:
// src/auth/roles.decorator.ts
import { SetMetadata } from "@nestjs/common";
export const Roles = (...roles: string[]) => SetMetadata("roles", roles);
// src/auth/roles.guard.ts
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express";
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.getAllAndOverride<string[]>("roles", [context.getHandler(), context.getClass()]);
if (!roles || roles.length === 0) return true;
const request = context.switchToHttp().getRequest<Request>();
if (!request.session?.role || !roles.includes(request.session.role)) {
throw new ForbiddenException("Not allowed");
}
return true;
}
}
@UseGuards(SessionAuthGuard, RolesGuard)
@Roles("admin")
@Get("admin/reports")
reports() {
return { ok: true };
}
The status codes have different meanings: 401 means "not logged in", and 403 means "logged in, but not allowed".
A current-user decorator removes repeated code:
// src/auth/current-user-id.decorator.ts
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
export const CurrentUserId = createParamDecorator((_data: unknown, context: ExecutionContext) => {
return context.switchToHttp().getRequest().session?.userId as number | undefined;
});
@UseGuards(SessionAuthGuard)
@Get("profile")
profile(@CurrentUserId() userId: number) {
return this.users.findById(userId);
}
Protect everything by default. Register the guard globally, and mark the public routes:
// app.module.ts
providers: [{ provide: APP_GUARD, useClass: SessionAuthGuard }],
// public.decorator.ts
export const IS_PUBLIC = "isPublic";
export const Public = () => SetMetadata(IS_PUBLIC, true);
In the guard, read the metadata with Reflector and return true for public routes. Then a forgotten @UseGuards cannot leave a route open, and login carries @Public().
Takeaway
Use guards for authentication and roles, decorators for readable controllers, and consider a global guard with a @Public() exception.
Exercise 7
Add a protected /profile route and an admin-only route, and test the 401 and 403 responses.
Module 8: Cookies, CORS, and Proxies
Objectives
- Set cookie flags for production
- Allow a browser front end to send the cookie
- Make HTTPS work behind a proxy
Lesson
Cookie flags:
| Flag | Purpose | Recommendation |
|---|---|---|
httpOnly |
Hides the cookie from JavaScript | Always true |
secure |
Sends the cookie only over HTTPS | true in production |
sameSite |
Controls cross-site sending | "lax" for most apps, "strict" for the most sensitive, "none" (with secure) only for true cross-site use |
maxAge |
Lifetime in milliseconds | Hours, not months |
domain, path |
Scope of the cookie | Leave the defaults unless you need subdomains |
CORS. When a front end on another origin calls your API, enable CORS with credentials, and name the origin exactly (a wildcard is not allowed with credentials):
app.enableCors({
origin: config.getOrThrow<string>("CORS_ORIGIN"),
credentials: true,
});
The front end must ask the browser to send the cookie:
fetch("http://localhost:3000/profile", { credentials: "include" });
// axios: axios.get(url, { withCredentials: true })
SameSite=Lax cookies work between ports of localhost, since they count as the same site. For a front end and an API on different registrable domains, you need sameSite: "none" with secure: true, or better, put both behind one domain with a reverse proxy.
Behind a proxy or load balancer (Nginx, a cloud load balancer, Heroku, and similar), the app sees plain HTTP, so secure cookies would not be set. Tell Express to trust the proxy:
app.set("trust proxy", 1);
The proxy must pass the original scheme (X-Forwarded-Proto):
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
}
Use the number of proxies you trust, not true, because a blanket trust lets clients fake their IP address.
CSRF. Cookies are sent automatically, so another site can try to make the browser send a request to your API. SameSite=Lax blocks most such attacks, since it withholds the cookie on cross-site POST requests. For stronger protection, add a CSRF token (the double-submit pattern, with a maintained library), and check the Origin header on state-changing requests. Never change data in GET routes.
Rate-limit the login route with @nestjs/throttler, to slow down password guessing:
@Throttle({ default: { limit: 5, ttl: 60_000 } })
@Post("login")
Takeaway
Use httpOnly, secure, and sameSite, enable CORS with credentials for a named origin, trust the proxy, and add CSRF and rate limits.
Exercise 8
Call the API from a small front end with credentials: "include", and confirm the cookie is stored and sent.
Module 9: Session Lifetime
Objectives
- Distinguish idle and absolute timeouts
- Use
rollingandtouch - Control the Redis TTL
Lesson
There are two kinds of timeout:
| Timeout | Meaning | Example |
|---|---|---|
| Idle | The session ends after a period of no activity | 30 minutes without a request |
| Absolute | The session ends a fixed time after login, whatever the activity | 12 hours after login |
Idle timeout. With rolling: true, each response renews the cookie, and the store refreshes the key's expiry. Set the cookie lifetime to the idle limit:
cookie: { maxAge: 30 * 60 * 1000 },
rolling: true,
connect-redis sets the Redis TTL from the cookie's maxAge (or its ttl option, in seconds, when the cookie has none), and it extends the TTL on each request.
Absolute timeout. The idle timeout alone lets an active user stay logged in forever. Store the login time (Module 5), and reject old sessions in the guard:
const absoluteLimit = 12 * 60 * 60 * 1000;
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
const { userId, loggedInAt } = request.session ?? {};
if (!userId || !loggedInAt) throw new UnauthorizedException();
if (Date.now() - loggedInAt > absoluteLimit) {
request.session.destroy(() => undefined);
throw new UnauthorizedException("Session expired, please log in again");
}
return true;
}
"Remember me." Let the user choose a longer lifetime at login:
req.session.cookie.maxAge = dto.remember ? 30 * 24 * 60 * 60 * 1000 : undefined;
When maxAge is undefined, the cookie is a browser-session cookie and disappears when the browser closes, while the Redis store falls back to its ttl option. Set a sensible ttl in RedisStore:
new RedisStore({ client: redis, prefix: "sess:", ttl: 60 * 60 * 24 })
Reduce Redis writes with touch. By default, every request refreshes the TTL. If that is too chatty, use disableTouch: true in RedisStore and rolling: false, and accept a fixed lifetime from login.
Anonymous sessions. If you need pre-login data (a shopping cart), enable saveUninitialized: true for those routes only, or create the session explicitly when needed, and give it a short TTL.
Check the lifetime in Redis:
redis-cli -a devpassword --scan --pattern "sess:*"
redis-cli -a devpassword TTL "sess:<id>"
A positive TTL counts down in seconds, -1 means no expiry (a problem), and -2 means the key does not exist.
Redis memory policy. If Redis runs out of memory with allkeys-lru, it may evict live sessions. Prefer a dedicated Redis for sessions, give it enough memory, and use volatile-lru or volatile-ttl, so that only keys with a TTL are evicted.
Takeaway
Use an idle timeout through maxAge and rolling, add an absolute limit in the guard, and verify the TTL in Redis.
Exercise 9
Set a one-minute idle timeout, wait, and confirm the session is rejected. Then add a two-minute absolute limit.
Module 10: Managing Sessions in Redis
Objectives
- Track the sessions of each user
- Revoke all sessions of a user
- Inspect Redis safely
Lesson
Sometimes the server must end sessions: a password change, a ban, "log out of all devices". Because sessions live in Redis, you can delete them directly. The challenge is finding the sessions of one user, since the keys are named by session ID. The solution is an index: a Redis set per user that holds their session IDs.
// src/auth/session-registry.service.ts
import { Inject, Injectable } from "@nestjs/common";
import { REDIS_CLIENT, RedisClient } from "../redis/redis.constants";
@Injectable()
export class SessionRegistryService {
constructor(@Inject(REDIS_CLIENT) private readonly redis: RedisClient) {}
private key(userId: number) {
return `user_sessions:${userId}`;
}
async add(userId: number, sessionId: string, ttlSeconds: number) {
await this.redis.sAdd(this.key(userId), sessionId);
await this.redis.expire(this.key(userId), ttlSeconds);
}
async remove(userId: number, sessionId: string) {
await this.redis.sRem(this.key(userId), sessionId);
}
async revokeAll(userId: number, exceptSessionId?: string) {
const ids = (await this.redis.sMembers(this.key(userId))).filter((id) => id !== exceptSessionId);
if (ids.length > 0) {
await this.redis.del(ids.map((id) => `sess:${id}`));
await this.redis.sRem(this.key(userId), ids);
}
return ids.length;
}
}
Register the session after login (once the new ID exists), and remove it on logout:
// in login, after req.session.save(...)
await this.registry.add(user.id, req.sessionID, 8 * 60 * 60);
// in logout, before destroy
await this.registry.remove(req.session.userId!, req.sessionID);
Log out everywhere (for example, after a password change):
@UseGuards(SessionAuthGuard)
@Post("logout-all")
async logoutAll(@Req() req: Request, @CurrentUserId() userId: number) {
const count = await this.registry.revokeAll(userId, req.sessionID);
return { revoked: count };
}
The exceptSessionId argument keeps the current device logged in.
Revoke after a ban or a role change from an admin action: call revokeAll(userId) without an exception, and the user's next request is rejected, since the session key no longer exists. This is the instant control that stateless tokens lack.
Stale entries. The set can hold IDs of sessions that already expired. They do no harm, since deleting a missing key is a no-op, and the set itself expires through its own TTL. When you list devices, filter out IDs whose key no longer exists:
const keys = ids.map((id) => `sess:${id}`);
const values = await this.redis.mGet(keys);
const active = values.filter(Boolean).map((json) => JSON.parse(json as string));
Show each device's userAgent, ip, and loggedInAt (stored in Module 5), so users can recognize and end sessions themselves.
Inspect Redis safely. Use SCAN, never KEYS, on a real server, because KEYS blocks Redis while it walks every key:
redis-cli -a devpassword --scan --pattern "sess:*" | head
redis-cli -a devpassword GET "sess:<id>"
redis-cli -a devpassword SMEMBERS "user_sessions:1"
redis-cli -a devpassword TTL "sess:<id>"
Treat session data as sensitive when you inspect or log it. A session ID in a log file is as dangerous as a password, so never log cookies or full session keys.
Count active sessions for monitoring with a scan, or keep a counter in the registry.
Takeaway
Index sessions by user with a Redis set, so that you can list devices and revoke sessions instantly, and use SCAN to inspect Redis.
Exercise 10
Log in from two clients, call logout-all from one, and confirm that the other one receives a 401.
Module 11: Testing and Common Problems
Objectives
- Test the session flow end to end
- Diagnose frequent issues
- Apply short fixes
Lesson
An end-to-end test logs in, keeps the cookie, and calls a protected route. supertest's agent stores cookies between requests. Reuse setupSession, so the test runs the same middleware as production:
// test/auth.e2e-spec.ts
import { Test } from "@nestjs/testing";
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import { AppModule } from "../src/app.module";
import { setupSession } from "../src/session.setup";
describe("Sessions", () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
setupSession(app);
await app.init();
});
afterAll(async () => {
await app.close();
});
it("rejects an anonymous request", async () => {
await request(app.getHttpServer()).get("/profile").expect(401);
});
it("logs in, reads the profile, and logs out", async () => {
const agent = request.agent(app.getHttpServer());
await agent.post("/auth/login").send({ email: "ada@example.com", password: "correct-password" }).expect(200);
await agent.get("/profile").expect(200);
await agent.post("/auth/logout").expect(200);
await agent.get("/profile").expect(401);
});
});
Use a separate Redis database for tests (for example redis://...:6379/1), and clear it before each run, so tests never touch real sessions. Keep secure: false outside production, since test requests use plain HTTP.
Common problems:
| Problem | Cause | Fix |
|---|---|---|
req.session is undefined |
The middleware is not registered, or registered after the routes | Call setupSession(app) before app.listen, and in tests too |
| The cookie is not stored in the browser | secure: true over HTTP, or CORS without credentials |
secure only in production, and credentials: "include" plus credentials: true |
| The cookie is never set behind a proxy | The app thinks the request is HTTP | app.set("trust proxy", 1) and X-Forwarded-Proto |
| A new session on every request | Cookie not sent, secure mismatch, or a changing secret |
Check the browser's cookie and the Set-Cookie header |
TypeScript error on req.session.userId |
SessionData not extended |
Add the declare module file |
import session fails |
esModuleInterop is off |
Turn it on, or use import * as session |
RedisStore is not a constructor |
Default versus named export differs between versions | Match the import to your connect-redis version |
| Sessions vanish after a restart | MemoryStore still in use |
Pass store: new RedisStore(...) |
| Logout does not log the user out | Cookie not cleared, or destroy not awaited |
clearCookie("sid") and await destroy |
| Session data missing right after login | The response was sent before the save finished | Await req.session.save |
Many sess: keys for anonymous visitors |
saveUninitialized: true |
Set it to false |
| Sessions expire too early or never | Wrong maxAge or ttl |
Check TTL in Redis |
| Users are logged out randomly | Redis evicts keys under memory pressure | Increase memory, use volatile-lru, use a dedicated instance |
Redis error: ECONNREFUSED |
Redis is not running, or the URL is wrong | Check Docker and REDIS_URL |
| 401 in the browser but 200 in curl | Cross-site cookie blocked (SameSite) |
Same domain, or sameSite: "none" with secure: true |
| The app crashes on a Redis error | No error listener |
Add client.on("error", ...) |
Debug checklist: look at the Set-Cookie header of the login response, check the browser's stored cookie, read the key in Redis with GET, and check its TTL.
Takeaway
Test the session flow end to end with a cookie-keeping agent, and use the checklist (header, cookie, key, TTL) to find problems.
Exercise 11
Write the e2e test, then break it on purpose by removing setupSession, and read the error.
Module 12: Capstone Project and Best Practices
Capstone project
Build a small API with Redis sessions:
- Run Redis with Docker, with a password, and configure the environment variables.
- Create the global Redis provider with an error listener and a clean shutdown.
- Add
setupSessionwithRedisStore, safe cookie options, andtrust proxy. - Type the session data with
SessionData. - Implement login (with
regenerate) and logout (withdestroyandclearCookie). - Protect routes with a global guard and a
@Public()decorator, and add a role guard. - Add idle and absolute timeouts, and verify the TTL in Redis.
- Track sessions per user, add
logout-all, and list active devices. - Add CORS with credentials, a login rate limit, and a CSRF strategy.
- Write e2e tests with a cookie-keeping agent, and a short note on the production settings.
Best Practices Summary
- Use a Redis store, never the default
MemoryStore, in any real environment. - Create one Redis client with an async provider, handle its errors, and close it on shutdown.
- Keep the secret in the environment, make it long and random, and rotate it with an array.
- Set
httpOnly,securein production, andsameSite, and trust only the proxies you have. - Set
saveUninitialized: false, so anonymous traffic creates no keys. - Regenerate the session ID on login, and destroy the session and clear the cookie on logout.
- Await
save,regenerate, anddestroy, which are callback-based. - Store small identifiers in the session, and load fresh data from the database.
- Use an idle timeout and an absolute timeout, and verify the TTL in Redis.
- Index sessions by user, so that you can revoke them on password changes and bans.
- Protect every route by default, and return 401 for "not logged in" and 403 for "not allowed".
- Hash passwords with a slow algorithm, rate-limit login, and add CSRF protection.
- Use TLS (
rediss://) and a password for Redis, and keep it off the public internet. - Use
SCAN, neverKEYS, and never log session IDs. - Test the flow end to end, with a separate Redis database.
Quick Reference
| Task | Code |
|---|---|
| Install | npm i express-session connect-redis redis |
| Types | npm i -D @types/express-session |
| Client | createClient({ url }), await client.connect() |
| Store | new RedisStore({ client, prefix: "sess:" }) |
| Middleware | app.use(session({ store, secret, resave: false, saveUninitialized: false })) |
| Trust proxy | app.set("trust proxy", 1) |
| Cookie | { httpOnly: true, secure: true, sameSite: "lax", maxAge } |
| Session type | declare module "express-session" { interface SessionData { ... } } |
| New ID on login | req.session.regenerate(cb) |
| Save | req.session.save(cb) |
| Logout | req.session.destroy(cb), res.clearCookie("sid") |
| Guard | @UseGuards(SessionAuthGuard) |
| Roles | @Roles("admin") with RolesGuard |
| CORS | app.enableCors({ origin, credentials: true }) |
| Index sessions | redis.sAdd("user_sessions:1", sessionId) |
| Revoke | redis.del(ids.map((id) => "sess:" + id)) |
| Inspect | redis-cli --scan --pattern "sess:*" |
| Check TTL | redis-cli TTL "sess:<id>" |
| Test | request.agent(app.getHttpServer()) |
Summary
Redis sessions give a NestJS application server-side control with the speed and sharing of an in-memory store. Create one Redis client with an async provider, plug it into express-session through connect-redis, and configure the cookie with httpOnly, secure, and sameSite, a secret from the environment, and saveUninitialized: false. Type the session data, store only small identifiers, and implement login with regenerate and logout with destroy and clearCookie, awaiting the callback-based calls. Protect routes with guards, a role guard, and a global default with a @Public() exception, and make cookies work in real deployments with CORS credentials, a trusted proxy, CSRF protection, and login rate limits. Control idle and absolute lifetimes, index each user's sessions in a Redis set to revoke them instantly, inspect Redis with SCAN, and test the whole flow with a cookie-keeping agent. A strong session design is short-lived, revocable, and observable.
This lesson is part of the NestJS Course and TypeScript Course offered by Wisen IT Solutions, Chennai, India.
About the author
- AI enthusiast and academic researcher with a focus on deep learning, computer vision, and NLP. I write about IEEE-aligned project ideas, model architectures, and practical AI implementation guides for final year engineering students. Helping students bridge the gap between research papers and real-world code.
Comments
Join the discussionNo comments yet. Be the first to comment.



