QA
Intermediate LevelExpress JS

How does Express cookie signing prevent client-side cookie tampering?

❓ Interview Prompt: Explain cookie signing, HMAC-SHA256 signatures, signedCookies, and detecting client-side cookie tampering.

Plain HTTP cookies can be edited easily by users in browser developer tools. Signed Cookies append a cryptographic HMAC-SHA256 signature to the cookie value.

How it Works:

1
Initialize 'cookie-parser("secret-key")'.
2
Set signed cookies: 'res.cookie("role", "admin", { signed: true })'.
3
Express appends '.s:signature' to the cookie value. When reading via 'req.signedCookies', Express recalculates the signature. If tampered with, 'req.signedCookies.role' evaluates to 'false'!

Code Implementation Example

javascript
import express from 'express';
import cookieParser from 'cookie-parser';

const app = express();
app.use(cookieParser('my-secret-key'));

app.get('/set-signed', (req, res) => {
  res.cookie('tier', 'premium', { signed: true });
  res.send('Signed cookie issued');
});

app.get('/read-signed', (req, res) => {
  // Returns 'premium' if authentic, or false if tampered by user!
  const tier = req.signedCookies.tier;
  res.json({ tier });
});
💡Issuing and verifying tamper-proof signed cookies.
🎯 Interview Key Takeaway

Use res.cookie(name, val, { signed: true }) and req.signedCookies to detect and reject tampered client cookies.

#signedCookies#Cookies#Security#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?