Node.js Course
Node.js
/
Intermediate

Sessions & Cookies

Definition

A stateful authentication mechanism where the server stores user data in its memory (or a database/Redis) and gives the client a tiny unique ID (stored in a cookie) to reference that memory.

Explain Like I'm New

JWTs are like passports; all the information is carried by the user. Sessions are like a coat check at a club. The server takes your coat (your user data), puts it in a secure closet, and hands you a tiny numbered ticket (the Session ID Cookie). When you want your data, you hand the server the ticket, and the server looks up your data in its closet.

Real World Example

Using the `express-session` package. The user logs in, and you write `req.session.userId = user._id`. Node automatically generates a random cookie, sends it to the browser, and saves the user data in Redis.

Common Use Cases

  • •Traditional monolithic web apps
  • •Applications requiring strict, instant logout/revocation capabilities

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is a Cookie?

intermediate

  • What is the primary difference between JWT and Session authentication?

advanced

  • Why is storing Sessions in the default Node.js memory dangerous in production?

Flash Cards

Question

What is a Cookie?

Click to reveal answer
Answer

A small piece of text data that a server sends to a user's web browser. The browser automatically saves it and sends it back to the server with every future request.

Question

JWT vs Session?

Click to reveal answer
Answer

JWT is Stateless (the server remembers nothing, all data is in the token). Sessions are Stateful (the server stores the data, the token is just a random ID pointer).

Question

Why is memory storage dangerous?

Click to reveal answer
Answer

Two reasons. 1: If the Node server crashes, all memory is wiped, logging every single user out instantly. 2: If you scale horizontally (run 3 Node servers), Server A doesn't share memory with Server B. A user logged into Server A will be 'unauthenticated' if the load balancer routes their next request to Server B. You MUST store sessions in an external database like Redis.