How to use cookie-parser in Express
Cookie parsing is essential for handling user sessions, authentication tokens, and user preferences in Express applications that rely on HTTP cookies. With over 25 years of backend development experience and as the creator of CoreUI, I’ve implemented cookie-based authentication in countless web applications. The most reliable approach is using the cookie-parser middleware to automatically parse cookie headers and make them accessible via req.cookies. This provides secure, efficient cookie handling with support for signed cookies and proper security measures.
Use cookie-parser middleware to automatically parse HTTP cookies and make them available in Express route handlers.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
// Initialize cookie-parser with secret for signed cookies
app.use(cookieParser('your-secret-key'))
// Set a cookie
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'john_doe', {
maxAge: 900000, // 15 minutes
httpOnly: true,
secure: process.env.NODE_ENV === 'production'
})
res.json({ message: 'Cookie set successfully' })
})
// Read cookies
app.get('/profile', (req, res) => {
const username = req.cookies.username
if (!username) {
return res.status(401).json({ error: 'Not authenticated' })
}
res.json({ user: username, message: 'Welcome back!' })
})
// Clear a cookie
app.post('/logout', (req, res) => {
res.clearCookie('username')
res.json({ message: 'Logged out successfully' })
})
This implementation shows cookie-parser’s core functionality: parsing incoming cookies into req.cookies, setting cookies with security options like httpOnly and secure, and clearing cookies on logout. The secret key enables signed cookie support for tamper detection, and the security options protect against XSS and ensure HTTPS-only transmission in production.
Best Practice Note:
This cookie management pattern is used in CoreUI’s authentication systems for secure session handling. Always use httpOnly cookies for sensitive data, set appropriate expiration times, and use secure flag in production to prevent cookie theft and session hijacking.



