0
0
NestJSframework~15 mins

Session-based authentication in NestJS - Deep Dive

Choose your learning style9 modes available
Overview - Session-based authentication
What is it?
Session-based authentication is a way to keep users logged in by saving their login status on the server. When a user logs in, the server creates a session and stores it with a unique ID. This ID is sent to the user's browser as a cookie. On later requests, the browser sends the cookie back, so the server knows who the user is without asking for login again. This method helps websites remember users safely during their visit.
Why it matters
Without session-based authentication, users would have to log in every time they visit a new page or refresh the site, which is frustrating. It solves the problem of remembering who a user is across multiple requests without sending sensitive information like passwords each time. This makes websites more user-friendly and secure by keeping login data on the server, reducing risks of exposure.
Where it fits
Before learning session-based authentication, you should understand HTTP basics, cookies, and how web servers handle requests. After mastering this, you can explore token-based authentication like JWT, OAuth, and advanced security practices such as refresh tokens and multi-factor authentication.
Mental Model
Core Idea
Session-based authentication works by storing a user's login state on the server and using a cookie to link the user's browser to that stored state.
Think of it like...
It's like checking into a hotel: the front desk gives you a key card (cookie) that you carry around. The hotel keeps your reservation details (session) safely at the front desk. Whenever you come back to the front desk, showing your key card lets them know who you are without asking again.
┌─────────────┐       ┌───────────────┐       ┌───────────────┐
│   Browser   │──────▶│   Server      │──────▶│ Session Store │
│ (User side) │ Cookie│ (Handles req) │ Stores│ (Memory/DB)   │
└─────────────┘       └───────────────┘       └───────────────┘
       ▲                     │                      ▲
       │                     │                      │
       └─────────────────────┴──────────────────────┘
                 Cookie with session ID links user to session
Build-Up - 6 Steps
1
FoundationUnderstanding HTTP and Cookies
🤔
Concept: Learn how HTTP requests and responses work and how cookies store small pieces of data in the browser.
HTTP is the language browsers and servers use to talk. Each time you visit a page, your browser sends a request, and the server sends back a response. Cookies are small text files the server asks the browser to save. They are sent back with every request to the same server, allowing the server to recognize the browser.
Result
You understand that cookies are the main tool to remember users between different page visits.
Knowing how cookies travel with requests is key to understanding how session-based authentication keeps users logged in.
2
FoundationWhat is a Session on the Server?
🤔
Concept: A session is a stored record on the server that holds information about a user’s login state and other data.
When a user logs in, the server creates a session object with a unique ID. This session stores data like user ID and login time. The server keeps this session in memory or a database. The session ID is sent to the browser as a cookie, linking the browser to the session.
Result
You see that the server holds the real user data, and the browser only holds a reference (session ID).
Understanding that the server keeps the sensitive data safe while the browser holds only a pointer prevents security risks.
3
IntermediateImplementing Sessions in NestJS
🤔Before reading on: do you think NestJS manages sessions automatically or requires explicit setup? Commit to your answer.
Concept: NestJS uses middleware to handle sessions, requiring explicit setup with packages like express-session.
In NestJS, you add session support by installing express-session and configuring it in your main app module. You set options like secret keys and cookie settings. When a user logs in, you save their info in req.session. On later requests, you check req.session to see if the user is logged in.
Result
Your NestJS app can now remember logged-in users across requests using sessions.
Knowing that session management is middleware-based in NestJS helps you control and customize authentication behavior.
4
IntermediateSecuring Sessions with Cookies
🤔Before reading on: do you think cookies used for sessions should be accessible by JavaScript or not? Commit to your answer.
Concept: Cookies for sessions should be secure, HttpOnly, and have proper expiration to protect user data.
Set cookie options like HttpOnly to prevent JavaScript access, Secure to allow only HTTPS, and SameSite to control cross-site sending. These settings reduce risks like cross-site scripting (XSS) and cross-site request forgery (CSRF). Expiration controls how long a session lasts.
Result
Sessions are safer from common web attacks when cookies are properly configured.
Understanding cookie security settings is crucial to protect users and prevent session hijacking.
5
AdvancedSession Store Options and Scaling
🤔Before reading on: do you think storing sessions in server memory is good for large apps? Commit to your answer.
Concept: For large or distributed apps, sessions should be stored in shared stores like Redis instead of server memory.
By default, sessions may be stored in server memory, which is lost on restart and doesn't work well with multiple servers. Using external stores like Redis or databases allows sessions to persist and be shared across servers, enabling scaling and reliability.
Result
Your app can handle many users and servers without losing session data.
Knowing the limits of in-memory sessions prevents bugs and downtime in production systems.
6
ExpertHandling Session Fixation and Logout
🤔Before reading on: do you think simply deleting a session cookie logs a user out securely? Commit to your answer.
Concept: Proper logout requires destroying the session on the server, not just deleting the cookie, to prevent session fixation attacks.
Session fixation happens when an attacker tricks a user into using a known session ID. To prevent this, regenerate session IDs on login and destroy sessions on logout. Just deleting the cookie leaves the session active on the server, which is unsafe. Use req.session.destroy() in NestJS to fully log out.
Result
Users are securely logged out, and attackers cannot reuse old sessions.
Understanding session fixation and proper logout prevents serious security vulnerabilities in your app.
Under the Hood
When a user logs in, the server creates a session object with a unique ID and stores it in memory or a database. This ID is sent to the browser as a cookie. On each request, the browser sends the cookie back. The server reads the cookie, finds the matching session, and loads the stored user data. This way, the server knows who the user is without needing credentials every time. The session data is kept server-side, so sensitive info never travels over the network after login.
Why designed this way?
Session-based authentication was designed to solve the stateless nature of HTTP, which forgets users between requests. Storing session data on the server keeps sensitive information safe and allows easy invalidation. Alternatives like token-based auth came later to solve scaling and statelessness issues, but sessions remain simple and secure for many apps.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Browser     │       │   Server      │       │ Session Store │
│  (Client)    │       │ (NestJS App)  │       │ (Memory/Redis)│
└──────┬────────┘       └──────┬────────┘       └──────┬────────┘
       │ Cookie with SID         │ Reads cookie          │
       │────────────────────────▶│                      │
       │                         │ Looks up session      │
       │                         │──────────────────────▶│
       │                         │                      │
       │                         │ Session data returned │
       │                         │◀─────────────────────│
       │                         │                      │
       │                         │ Uses session info to  │
       │                         │ authenticate request  │
       │                         │                      │
Myth Busters - 4 Common Misconceptions
Quick: Does deleting the session cookie on the browser fully log out the user? Commit yes or no.
Common Belief:Deleting the session cookie on the browser logs the user out completely.
Tap to reveal reality
Reality:Deleting the cookie only removes the reference on the client; the session still exists on the server and can be reused if the cookie is restored or intercepted.
Why it matters:This can lead to security risks where attackers reuse sessions, so proper logout must destroy the session server-side.
Quick: Are sessions stored on the client side? Commit yes or no.
Common Belief:Sessions are stored on the client side inside cookies.
Tap to reveal reality
Reality:Only the session ID is stored in the cookie on the client; the actual session data is stored securely on the server.
Why it matters:Thinking session data is client-side can lead to insecure designs exposing sensitive information.
Quick: Can session-based authentication scale easily across many servers without extra setup? Commit yes or no.
Common Belief:Session-based authentication works out of the box on multiple servers without changes.
Tap to reveal reality
Reality:Sessions stored in server memory do not share state across servers; you need a shared session store like Redis for scaling.
Why it matters:Without shared stores, users may lose login state or face inconsistent behavior in multi-server setups.
Quick: Is it safe to allow JavaScript to access session cookies? Commit yes or no.
Common Belief:Allowing JavaScript to read session cookies is safe and convenient.
Tap to reveal reality
Reality:Allowing JavaScript access (not HttpOnly) exposes cookies to cross-site scripting attacks, risking session theft.
Why it matters:This can lead to account hijacking and serious security breaches.
Expert Zone
1
Session regeneration on login prevents session fixation attacks by assigning a new session ID after authentication.
2
Using rolling sessions extends session expiration on user activity, improving user experience without compromising security.
3
Properly configuring SameSite cookie attribute balances security and usability, especially for cross-origin requests.
When NOT to use
Session-based authentication is less suitable for APIs or mobile apps where statelessness and scalability are priorities. In those cases, token-based authentication like JWT or OAuth is preferred because it avoids server-side session storage and works better with distributed systems.
Production Patterns
In production NestJS apps, sessions are often stored in Redis for scalability. Middleware like passport.js integrates with sessions for flexible authentication strategies. Sessions are secured with HTTPS, HttpOnly, and SameSite cookies. Logout endpoints destroy sessions server-side. Session expiration and renewal policies are tuned for security and user convenience.
Connections
Token-based authentication (JWT)
Alternative approach to session-based authentication with stateless tokens.
Understanding sessions helps grasp why tokens store user info client-side and how statelessness affects scaling and security.
HTTP Cookies
Sessions rely on cookies to link browser requests to server-stored data.
Knowing cookie properties like HttpOnly and SameSite is essential to secure session management.
Hotel Check-in Systems (Hospitality)
Both use a token (key card or cookie) to identify a guest/user and grant access.
Recognizing this pattern across domains shows how tokens link identity to stored information securely and conveniently.
Common Pitfalls
#1Assuming deleting the cookie logs out the user fully.
Wrong approach:res.clearCookie('connect.sid'); // only removes cookie on client
Correct approach:req.session.destroy(err => { if (err) throw err; res.clearCookie('connect.sid'); });
Root cause:Misunderstanding that session data lives on the server and must be destroyed there to end the session.
#2Storing sessions in server memory for a multi-server app.
Wrong approach:app.use(session({ secret: 'secret', resave: false, saveUninitialized: false })); // default memory store
Correct approach:app.use(session({ store: new RedisStore({ client: redisClient }), secret: 'secret', resave: false, saveUninitialized: false }));
Root cause:Not realizing that server memory is local and lost on restart or across servers.
#3Setting cookies without security flags.
Wrong approach:app.use(session({ cookie: { maxAge: 60000 } })); // no HttpOnly or Secure
Correct approach:app.use(session({ cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60000 } }));
Root cause:Ignoring cookie security settings exposes sessions to theft via XSS or CSRF.
Key Takeaways
Session-based authentication stores user login data on the server and uses cookies to link the browser to that data.
Cookies carry only a session ID, keeping sensitive information safe on the server side.
Proper cookie security settings like HttpOnly and Secure are essential to protect sessions from attacks.
For scalable apps, sessions should be stored in shared stores like Redis, not server memory.
Secure logout requires destroying the session on the server, not just deleting the cookie on the client.