QA
Beginner LevelExpress JS

How do you read and set HTTP cookies in Express using cookie-parser?

❓ Interview Prompt: Explain cookie-parser middleware, reading req.cookies, setting cookies with res.cookie(), and HttpOnly / Secure flags.

By default, Express does not parse incoming HTTP cookies. Installing 'cookie-parser' populates 'req.cookies'.

Operations:

1
Setting Cookies: Use 'res.cookie(name, value, options)'. Set 'httpOnly: true' to prevent JavaScript XSS access, and 'secure: true' for HTTPS.
2
Reading Cookies: Access parsed cookies via 'req.cookies.cookieName'.
3
Clearing Cookies: Use 'res.clearCookie(name)'.

Code Implementation Example

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

const app = express();
app.use(cookieParser());

app.get('/set-cookie', (req, res) => {
  res.cookie('session_id', 'abc123xyz', {
    httpOnly: true, // XSS protection!
    secure: true,   // HTTPS only!
    maxAge: 3600000 // 1 hour
  });
  res.send('Cookie set securely');
});

app.get('/read-cookie', (req, res) => {
  const sessionId = req.cookies.session_id;
  res.json({ sessionId });
});
💡Reading and setting secure HTTP cookies with cookie-parser.
🎯 Interview Key Takeaway

Use cookie-parser to populate req.cookies. Always set httpOnly: true and secure: true on res.cookie().

#cookie-parser#res.cookie#Cookies#Beginner
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?