Module 44: Authentication

Lesson 3 of 5 · 15–25 minutes

Sessions and cookies

🏠The everyday picture

At a concert, your ticket is checked once at the gate, and you get a wristband. For the rest of the night, staff look at the wristband, not your ticket. A session is the wristband.

📘What it really is

res.cookie("sid", sessionId, {
  httpOnly: true,      // JavaScript can't read it (protects against XSS theft)
  secure: true,        // only sent over HTTPS
  sameSite: "lax",     // not sent with most cross-site requests (helps against CSRF)
  maxAge: 1000 * 60 * 60 * 8,
});

🖱️Try it

Add sign-in and sign-out routes. On sign-in, verify the password, create a random session id (crypto.randomUUID()), store it with the user id, and set it as an httpOnly cookie. Add middleware that sets req.user from the cookie, and a GET /me route returning the signed-in user (or 401). In developer tools, find the cookie under Application → Cookies, and confirm document.cookie in the console can't see it.

✅Quick check

What does httpOnly protect against?

Show the answer

JavaScript (including malicious injected scripts) reading the cookie and stealing the session.

Why delete the session on the server when signing out, not just the cookie?

Show the answer

If the cookie was copied, it would still work; deleting the session makes it useless everywhere.

← PreviousStoring passwords safely
ProLearners Assist