Cookies, Sessions & Stateful HTTP
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:
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.
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.