NestJS — Enterprise Node.js

Cookies, Sessions & Stateful HTTP

18 min Lesson 57 of 80

Cookies, Sessions & Stateful HTTP

REST APIs are often stateless, but real applications still need cookies and sessions for browser authentication, CSRF tokens, OAuth flows, flash messages, and MVC pages. NestJS supports them through the underlying platform middleware or Fastify plugins.

Core idea

This feature is about controlling how the application is organized and how it behaves at runtime. These are the points a developer should understand before using it in a real project:

  • Cookies are sent by the browser on matching requests and should be marked HttpOnly, Secure, and SameSite whenever possible.
  • Signed cookies protect integrity but do not encrypt the value; never store sensitive data directly inside them.
  • Sessions store only an identifier in the browser and keep server-side state in a session store.
  • A database or Redis-backed session store is required for multiple application instances.
  • Session-heavy APIs need explicit logout, rotation after privilege changes, and short lifetimes for high-risk workflows.

Practical example

The following example shows the idea in a practical NestJS project. The goal is not to memorize the snippet, but to understand where it belongs in the architecture:

async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(cookieParser(process.env.COOKIE_SECRET)); app.use(session({ name: 'sid', secret: process.env.SESSION_SECRET!, resave: false, saveUninitialized: false, cookie: { httpOnly: true, secure: true, sameSite: 'lax' }, store: new RedisStore({ client: redisClient }), })); await app.listen(3000); }
Design note: Use cookies and sessions intentionally. Browser-facing apps benefit from them; pure machine-to-machine APIs are usually better served by bearer tokens or mTLS.

Production checklist

  • Set HttpOnly, Secure, and SameSite on authentication cookies.
  • Use a shared session store in horizontally scaled deployments.
  • Rotate session identifiers after login and privilege elevation.
  • Do not store secrets or large user profiles inside cookies.
Rule of thumb: If the feature makes boundaries clearer and tests easier, it is probably the right choice. If it hides dependencies or makes tracing harder, redesign.

Summary

This lesson covers an advanced NestJS area that matters when building enterprise applications. Focus on clear boundaries, testable behavior, and choosing the right tool for the context instead of using every feature everywhere.