BytesFor Developers
HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
Back to full course
PrevNext

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: true on auth token cookies to mitigate XSS exposure.
  • Use cookie-parser middleware to parse incoming cookie headers into req.cookies.

STAY UPDATED WITH BYTES!

AboutPrivacyTermsCookies & ads

© 2026 Bytes4Dev. All rights reserved.

v.0.4.0