HTTP is stateless (Chapter S2 02: Features, HLD LLD and Planning): every request arrives as if the server had never seen you before. So after a successful login, how does the server know that your next request comes from the same person? This chapter answers that with cookies and JSON Web Tokens (JWT), then protects DevTinder's routes with an authentication middleware.
In this chapter you'll learn
- authentication vs authorization
- two ways to remember a logged-in user: sessions and tokens
- what cookies are, and the attributes that make them safe (
HttpOnly,Secure,SameSite) - what a JWT is, how it's built, signed and verified
- a login that sets a JWT cookie, and a
userAuthmiddleware that protects routes - moving logic into the model with schema methods
- the main attacks (XSS, CSRF, stolen tokens) and how to defend against them
Before you start: read Chapter S2 05: Middlewares and Error Handlers (middleware) and Chapter S2 09: Encrypting Passwords (login with bcrypt).
Authentication vs authorization
- Authentication (AuthN): who are you? Proving your identity: logging in with email and password.
- Authorization (AuthZ): what are you allowed to do? Checking permissions: can this user review this connection request?
Authentication always comes first. In status codes: failing authentication is 401; failing authorization is 403 (Chapter S2 05: Middlewares and Error Handlers).
How does the server remember you?
After POST /login succeeds, the server gives the client something to show on every later request, like a wristband at a concert: you show your ticket once at the gate, then just flash the wristband.
There are two main designs:
| Session-based | Token-based (JWT) | |
|---|---|---|
| What the client keeps | a random session ID | a token that itself contains the user ID, signed by the server |
| What the server keeps | a session store (memory, Redis, DB) mapping ID → user | nothing; it just checks the signature |
| Checking a request | look the session ID up in the store | verify the token's signature, no lookup needed |
| Logging out | delete the session: instant | the token stays valid until it expires (more below) |
| Scaling to many servers | every server needs the shared session store | any server with the secret can verify |
DevTinder uses JWTs, stored in a cookie.
Cookies
A cookie is a small piece of data that a server asks the browser to store, and that the browser then sends back automatically with every request to that site.
- The server responds with a header:
Set-Cookie: token=eyJhbGci... - The browser saves it.
- On every later request to the same site, the browser adds:
Cookie: token=eyJhbGci...
Your frontend code doesn't have to do anything; the browser handles it.
Cookie attributes that matter
| Attribute | What it does | Why you want it |
|---|---|---|
HttpOnly | JavaScript on the page can't read the cookie (document.cookie won't show it) | if an attacker injects a script into your site (XSS), they can't steal the token |
Secure | sent only over HTTPS | nobody on the network can read it in transit |
SameSite=Lax / Strict | not sent on requests started by other websites | blocks most CSRF attacks (explained below) |
Expires / Max-Age | when the browser deletes it | limits how long a stolen cookie is useful |
Path, Domain | which URLs it's sent to | keep it as narrow as possible |
Why a cookie and not localStorage? Both live in the browser. The real advantage is HttpOnly: an HttpOnly cookie can't be read by JavaScript at all, while anything in localStorage can be read by any script on the page, including an injected one.
JSON Web Tokens (JWT)
A JWT is a compact string with three parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NzAyYTFmNCIsImlhdCI6MTc5NjE5NTAyNSwiZXhwIjoxNzk2MjgxNDI1fQ.4k9ZQ2...
└────────── header ──────────────┘ └──────────────────────── payload ───────────────────────┘ └ signature ┘eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NzAyYTFmNCIsImlhdCI6MTc5NjE5NTAyNSwiZXhwIjoxNzk2MjgxNDI1fQ.4k9ZQ2...
└────────── header ──────────────┘ └──────────────────────── payload ───────────────────────┘ └ signature ┘| Part | Contains |
|---|---|
| Header | the token type and the signing algorithm, e.g. { "alg": "HS256", "typ": "JWT" } |
| Payload | the claims: data about the user, e.g. { "_id": "6702a1f4...", "iat": 1796195025, "exp": 1796281425 } (iat = issued at, exp = expires at, both in seconds) |
| Signature | a cryptographic HMAC of the header and payload, made with the server's secret key |
Signed, not encrypted
The header and payload are just Base64URL-encoded JSON, an encoding, not encryption. Anyone holding the token can read them:
// decoding the payload needs no secret at all
Buffer.from(token.split(".")[1], "base64url").toString();
// → {"_id":"6702a1f4c3e9b8a1d2f4e5a6","iat":1796195025,"exp":1796281425}// decoding the payload needs no secret at all
Buffer.from(token.split(".")[1], "base64url").toString();
// → {"_id":"6702a1f4c3e9b8a1d2f4e5a6","iat":1796195025,"exp":1796281425}(Paste any token into jwt.io to see the same thing.)
What the signature guarantees is that nobody changed it. Change one character of the payload (say, to someone else's _id) and the signature no longer matches. We tested it: jwt.verify throws JsonWebTokenError: invalid signature.
So:
- ✅ the server can trust the payload of a valid token, without a database lookup
- ❌ never put secrets in the payload (passwords, private data); put only an ID and harmless claims
Creating and verifying tokens
npm install jsonwebtoken cookie-parsernpm install jsonwebtoken cookie-parserconst jwt = require("jsonwebtoken");
// sign: create a token (synchronous when you don't pass a callback)
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: "1d" });
// verify: check signature AND expiry; returns the payload, or THROWS
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log(decoded._id);const jwt = require("jsonwebtoken");
// sign: create a token (synchronous when you don't pass a callback)
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: "1d" });
// verify: check signature AND expiry; returns the payload, or THROWS
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log(decoded._id);jwt.verify throws:
TokenExpiredError: jwt expiredwhen theexptime has passedJsonWebTokenError: invalid signaturewhen it was tampered with or signed with a different secret
The secret must be secret
Anyone who knows the secret can sign their own tokens for any user ID, and log in as anyone. The original course notes hardcode a short secret ("999@Akshad") in the source; once that code is on GitHub, the secret is public. Use a long random value from an environment variable (Chapter S2 06: Database, Schema, Models & Mongoose):
# generate once, then put it in .env as JWT_SECRET=...
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"# generate once, then put it in .env as JWT_SECRET=...
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"Login: create the JWT and set the cookie
Building on the login from Chapter S2 09: Encrypting Passwords:
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
app.use(express.json());
app.use(cookieParser()); // needed to READ cookies (req.cookies)
app.post("/login", async (req, res) => {
try {
const { emailId, password } = req.body;
const user = await User.findOne({ emailId });
if (!user) throw new Error("Invalid credentials");
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) throw new Error("Invalid credentials");
// create the token...
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1d",
});
// ...and send it in a cookie
res.cookie("token", token, {
httpOnly: true, // JS can't read it
secure: process.env.NODE_ENV === "production", // HTTPS only in production
sameSite: "lax", // blocks most CSRF
maxAge: 24 * 60 * 60 * 1000, // 1 day, same as the JWT
});
res.send("Login successful!");
} catch (err) {
res.status(401).send("ERROR: " + err.message);
}
});const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
app.use(express.json());
app.use(cookieParser()); // needed to READ cookies (req.cookies)
app.post("/login", async (req, res) => {
try {
const { emailId, password } = req.body;
const user = await User.findOne({ emailId });
if (!user) throw new Error("Invalid credentials");
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) throw new Error("Invalid credentials");
// create the token...
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1d",
});
// ...and send it in a cookie
res.cookie("token", token, {
httpOnly: true, // JS can't read it
secure: process.env.NODE_ENV === "production", // HTTPS only in production
sameSite: "lax", // blocks most CSRF
maxAge: 24 * 60 * 60 * 1000, // 1 day, same as the JWT
});
res.send("Login successful!");
} catch (err) {
res.status(401).send("ERROR: " + err.message);
}
});res.cookie(name, value, options)is built into Express. You don't need any package to set a cookie.- Reading cookies is different: without the
cookie-parsermiddleware,req.cookiesisundefined. With it,req.cookies.tokenholds the value. - Keep the cookie lifetime and the JWT lifetime the same. (The original code sets an 8-hour cookie with a 1-day JWT, which works but is confusing.)
Protecting routes: the userAuth middleware
Now write the check once, as middleware (Chapter S2 05: Middlewares and Error Handlers), and put it in front of every route that needs a logged-in user:
// src/middlewares/auth.js
const jwt = require("jsonwebtoken");
const User = require("../models/user");
const userAuth = async (req, res, next) => {
try {
const { token } = req.cookies;
if (!token) {
return res.status(401).send("Please login!");
}
const decoded = jwt.verify(token, process.env.JWT_SECRET); // throws if invalid/expired
const user = await User.findById(decoded._id);
if (!user) {
return res.status(401).send("User not found");
}
req.user = user; // hand the logged-in user to the route handler
next();
} catch (err) {
res.status(401).send("ERROR: " + err.message);
}
};
module.exports = { userAuth };// src/middlewares/auth.js
const jwt = require("jsonwebtoken");
const User = require("../models/user");
const userAuth = async (req, res, next) => {
try {
const { token } = req.cookies;
if (!token) {
return res.status(401).send("Please login!");
}
const decoded = jwt.verify(token, process.env.JWT_SECRET); // throws if invalid/expired
const user = await User.findById(decoded._id);
if (!user) {
return res.status(401).send("User not found");
}
req.user = user; // hand the logged-in user to the route handler
next();
} catch (err) {
res.status(401).send("ERROR: " + err.message);
}
};
module.exports = { userAuth };// a protected route
app.get("/profile", userAuth, (req, res) => {
res.send(req.user); // userAuth already loaded the user
});// a protected route
app.get("/profile", userAuth, (req, res) => {
res.send(req.user); // userAuth already loaded the user
});Things to notice:
- 401, not 400, for missing, invalid or expired tokens. The frontend uses 401 to know it should send the user to the login page (Chapter S2 17: DevTinder UI - Part 3).
req.user = user: middleware can attach data toreq, and every later handler can use it. Route handlers never trust a user ID from the body or URL to decide "who am I"; they usereq.user.- Loading the user from the database on every request costs one query, but it means a deleted user is locked out immediately.
Schema methods: moving logic into the model
Signing tokens and checking passwords are things a user does. Mongoose lets you attach such functions to every document with schema.methods:
// src/models/user.js
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
userSchema.methods.getJWT = function () {
const user = this; // the document the method was called on
return jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: "1d" });
};
userSchema.methods.validatePassword = async function (passwordInputByUser) {
const user = this;
return bcrypt.compare(passwordInputByUser, user.password);
};// src/models/user.js
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
userSchema.methods.getJWT = function () {
const user = this; // the document the method was called on
return jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: "1d" });
};
userSchema.methods.validatePassword = async function (passwordInputByUser) {
const user = this;
return bcrypt.compare(passwordInputByUser, user.password);
};The login route becomes shorter and easier to read:
const user = await User.findOne({ emailId });
if (!user) throw new Error("Invalid credentials");
const isPasswordValid = await user.validatePassword(password);
if (!isPasswordValid) throw new Error("Invalid credentials");
const token = user.getJWT();
res.cookie("token", token, { httpOnly: true, sameSite: "lax", maxAge: 86400000 });const user = await User.findOne({ emailId });
if (!user) throw new Error("Invalid credentials");
const isPasswordValid = await user.validatePassword(password);
if (!isPasswordValid) throw new Error("Invalid credentials");
const token = user.getJWT();
res.cookie("token", token, { httpOnly: true, sameSite: "lax", maxAge: 86400000 });Write schema methods with function, never an arrow function. Inside a method, this must be the document; arrow functions don't have their own this, so this._id would be undefined.
Schema methods give you encapsulation (user logic lives in the user model), reuse (any route can call user.getJWT()) and readability.
Security: the attacks to know
| Attack | What happens | Defence |
|---|---|---|
| XSS (Cross-Site Scripting) | attacker's JavaScript runs on your site and steals tokens or acts as the user | HttpOnly cookies; React escapes output by default; never insert untrusted HTML |
| CSRF (Cross-Site Request Forgery) | another website makes the user's browser send a request to your API, with the cookie attached automatically | SameSite=Lax/Strict cookies; CSRF tokens for sensitive forms |
| Token theft in transit | someone on the network reads the cookie | Secure flag + HTTPS everywhere (Chapter S3 03: Adding a custom Domain name) |
| Stolen token | whoever has the token is that user until it expires | short expiry; refresh tokens; server-side revocation for sensitive apps |
| Leaked secret | attacker signs tokens for any user | long random secret in env vars; rotate it if leaked |
Access tokens and refresh tokens
Larger apps often use two tokens:
- a short-lived access token (5–15 minutes) sent with every request
- a long-lived refresh token (days or weeks), stored more carefully, used only to get a new access token
If an access token is stolen, it's useful for minutes, not days. Refresh tokens can be stored in the database, so they can be revoked. DevTinder keeps it simple with one token valid for a day.
Try it on its own
Here is the whole login flow from this chapter in one file, with no DevTinder code and no database (users live in an array). Run it to see cookies and JWTs work before you wire them into a real project:
npm install express cookie-parser jsonwebtoken bcryptjsnpm install express cookie-parser jsonwebtoken bcryptjs// auth-demo.js: login with a JWT in a cookie, then a protected route
const express = require("express");
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const SECRET = "change-me"; // in real apps: process.env.JWT_SECRET
const app = express();
app.use(express.json());
app.use(cookieParser()); // fills req.cookies
// a fake "database": one user whose password is "secret123"
const users = [{ id: 1, email: "asha@example.com", passwordHash: bcrypt.hashSync("secret123", 10) }];
app.post("/login", async (req, res) => {
const user = users.find((u) => u.email === req.body.email);
const ok = user && (await bcrypt.compare(req.body.password, user.passwordHash));
if (!ok) return res.status(401).json({ error: "Invalid credentials" });
const token = jwt.sign({ id: user.id }, SECRET, { expiresIn: "1h" });
res.cookie("token", token, { httpOnly: true, sameSite: "strict" });
res.json({ message: "Logged in" });
});
// middleware: let the request through only with a valid token
function requireAuth(req, res, next) {
try {
const { id } = jwt.verify(req.cookies.token, SECRET); // throws if missing, forged or expired
req.user = users.find((u) => u.id === id);
next();
} catch {
res.status(401).json({ error: "Please log in" });
}
}
app.get("/profile", requireAuth, (req, res) => {
res.json({ email: req.user.email });
});
app.listen(3000, () => console.log("Listening on 3000"));// auth-demo.js: login with a JWT in a cookie, then a protected route
const express = require("express");
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const SECRET = "change-me"; // in real apps: process.env.JWT_SECRET
const app = express();
app.use(express.json());
app.use(cookieParser()); // fills req.cookies
// a fake "database": one user whose password is "secret123"
const users = [{ id: 1, email: "asha@example.com", passwordHash: bcrypt.hashSync("secret123", 10) }];
app.post("/login", async (req, res) => {
const user = users.find((u) => u.email === req.body.email);
const ok = user && (await bcrypt.compare(req.body.password, user.passwordHash));
if (!ok) return res.status(401).json({ error: "Invalid credentials" });
const token = jwt.sign({ id: user.id }, SECRET, { expiresIn: "1h" });
res.cookie("token", token, { httpOnly: true, sameSite: "strict" });
res.json({ message: "Logged in" });
});
// middleware: let the request through only with a valid token
function requireAuth(req, res, next) {
try {
const { id } = jwt.verify(req.cookies.token, SECRET); // throws if missing, forged or expired
req.user = users.find((u) => u.id === id);
next();
} catch {
res.status(401).json({ error: "Please log in" });
}
}
app.get("/profile", requireAuth, (req, res) => {
res.json({ email: req.user.email });
});
app.listen(3000, () => console.log("Listening on 3000"));Run node auth-demo.js. In a second terminal, curl plays the browser. -c jar.txt saves cookies to a file and -b jar.txt sends them back, which is what a browser does for you automatically:
curl localhost:3000/profile
curl -X POST localhost:3000/login -H "Content-Type: application/json" -d '{"email":"asha@example.com","password":"wrong"}'
curl -c jar.txt -X POST localhost:3000/login -H "Content-Type: application/json" -d '{"email":"asha@example.com","password":"secret123"}'
curl -b jar.txt localhost:3000/profilecurl localhost:3000/profile
curl -X POST localhost:3000/login -H "Content-Type: application/json" -d '{"email":"asha@example.com","password":"wrong"}'
curl -c jar.txt -X POST localhost:3000/login -H "Content-Type: application/json" -d '{"email":"asha@example.com","password":"secret123"}'
curl -b jar.txt localhost:3000/profileOutput:
{"error":"Please log in"}
{"error":"Invalid credentials"}
{"message":"Logged in"}
{"email":"asha@example.com"}{"error":"Please log in"}
{"error":"Invalid credentials"}
{"message":"Logged in"}
{"email":"asha@example.com"}- The first
/profilefails: there is no cookie yet, sojwt.verifythrows andrequireAuthanswers401. - A wrong password gets the same vague message as an unknown email, so attackers can't find out which emails exist.
- After login,
jar.txtholds thetokencookie, marked#HttpOnly_: page JavaScript can't read it. - The last request sends the cookie back.
requireAuthverifies it, puts the user onreq.userand callsnext(), so the route handler runs.
Common mistakes
- Hardcoding the JWT secret in source code.
- Forgetting
cookie-parser:req.cookiesisundefinedand every request looks logged out. - Cookies without
HttpOnly/Secure/SameSite. - Putting sensitive data in the JWT payload: anyone can decode it.
- Using arrow functions in
schema.methods. - Answering 400 for auth failures, instead of 401.
- Trusting a user ID from the request body instead of
req.userfrom the middleware.
Key takeaways
- Authentication = who you are (401 when it fails); authorization = what you may do (403).
- Sessions keep state on the server; JWTs carry signed state in the token, so the server stays stateless.
- A JWT is header.payload.signature: readable by anyone, but tamper-proof thanks to the signature.
res.cookie()is built in;cookie-parseris needed to read cookies.- Set cookies with
HttpOnly,Secure,SameSiteand a sensible expiry; keep the secret in an env var. - A
userAuthmiddleware verifies the token, loads the user intoreq.user, and protects any route it's placed in front of.
Interview questions
Q1. What is the difference between authentication and authorization?
Authentication verifies who the user is (login with credentials, verifying a token). Authorization decides what an authenticated user is allowed to do (roles, ownership checks). Failed authentication → 401; failed authorization → 403.
Q2. What is a JWT and what are its parts?
A JSON Web Token is a compact, URL-safe token with three Base64URL-encoded parts: the header (algorithm, type), the payload (claims such as user ID, iat, exp) and the signature (an HMAC or digital signature over header and payload, using a secret or private key). The signature lets the server detect tampering.
Q3. Is a JWT encrypted?
No, a normal (JWS) JWT is only signed. Anyone can Base64-decode the header and payload and read them. The signature guarantees integrity (it wasn't modified), not confidentiality. Don't put secrets in the payload. Encrypted tokens (JWE) exist but are rarely used for basic auth.
Q4. Session-based vs token-based authentication: what's the difference?
With sessions, the server stores session data and gives the client a random session ID (usually in a cookie); each request is checked by looking up the session. With JWTs, the server signs a token containing the user's identity; it verifies the signature on each request without storing anything. Sessions are easy to revoke but need shared storage across servers; JWTs are stateless and scale easily but are hard to revoke before expiry.
Q5. What do the HttpOnly, Secure and SameSite cookie attributes do?
HttpOnly hides the cookie from client-side JavaScript (document.cookie), which protects it from theft via XSS. Secure sends it only over HTTPS. SameSite controls whether it's sent on cross-site requests: Strict never, Lax only on top-level navigations (safe GET links), None always (requires Secure). This mainly protects against CSRF.
Q6. Where should you store a JWT in the browser: localStorage or a cookie?
An HttpOnly, Secure, SameSite cookie is generally safer: JavaScript can't read it, so XSS can't steal it, and SameSite mitigates CSRF. localStorage is readable by any script on the page, so a single XSS bug exposes the token. Cookies need CSRF protection, which SameSite largely provides.
Q7. What are access tokens and refresh tokens?
An access token is short-lived (minutes) and sent with every API request. A refresh token is long-lived, stored securely (often an HttpOnly cookie, and in the database), and used only to obtain new access tokens. This limits the damage from a stolen access token, and allows revocation by deleting refresh tokens on the server.
Q8. What is CSRF, and how do you prevent it?
Cross-Site Request Forgery: a malicious site makes the victim's browser send a request to your site, and the browser automatically includes the victim's cookies, so the request is authenticated. Prevent it with SameSite=Lax or Strict cookies, anti-CSRF tokens, checking the Origin/Referer header, and never changing data with GET requests.
What's next
app.js is getting long. In Chapter S2 11: Diving into the APIs and Express router you'll split the APIs into Express routers (auth, profile, requests, users), and build the logout and profile edit APIs.