Q24: How do you set, read, and clear HTTP cookies in Express?
Difficulty:EasyTopic:Cookie Management
Reading cookies requires the cookie-parser middleware, whereas setting and clearing cookies is natively supported by res.cookie() and res.clearCookie().
Setting Secure HTTP-Only Cookies
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/set-cookie', (req, res) => {
res.cookie('token', 'abc123secret', {
httpOnly: true, // Prevents client-side JS read access
secure: true, // Transmitted only over HTTPS
sameSite: 'strict',
maxAge: 3600000 // 1 hour expiration
});
res.send('Cookie set');
});
app.get('/read-cookie', (req, res) => {
console.log(req.cookies.token); // Read cookie parsed by middleware
res.send('Cookie read');
});💡 Setting httpOnly and secure flags protects cookies against client-side script theft.
Key Takeaways
- Always use
httpOnly: trueon auth token cookies to mitigate XSS exposure. - Use
cookie-parsermiddleware to parse incoming cookie headers intoreq.cookies.