Express Cookie Parser
Introduction
Cookies are small pieces of data stored on the client's browser that help maintain state information in web applications. They're essential for tracking sessions, saving user preferences, implementing authentication, and more.
In Express.js, the cookie-parser
middleware simplifies working with cookies by parsing the Cookie header from the client and exposing the cookie data in the req.cookies
object. This middleware is crucial for applications that need to read or set cookies.
This guide will teach you how to use the cookie-parser
middleware in your Express applications, from basic setup to advanced usage patterns.
Prerequisites
Before diving into cookie-parser, you should have:
- Basic knowledge of JavaScript
- Node.js installed on your system
- Familiarity with Express.js basics
Installing cookie-parser
Let's start by installing the middleware:
npm install cookie-parser
Basic Usage
Here's how to set up cookie-parser in your Express application:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// Add cookie-parser middleware
app.use(cookieParser());
app.get('/', (req, res) => {
console.log('Cookies: ', req.cookies);
res.send('Cookie parser is working!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, when a request is made to your server, cookie-parser will parse any cookies sent by the client and make them available in the req.cookies
object.
Setting Cookies
To set cookies from your Express server, use the res.cookie()
method:
app.get('/set-cookie', (req, res) => {
// Set a cookie named 'username'
res.cookie('username', 'john_doe', {
maxAge: 900000, // Cookie expires after 15 minutes
httpOnly: true // Cookie is not accessible via JavaScript
});
res.send('Cookie has been set!');
});
Reading Cookies
After setting up cookie-parser, you can easily access cookies sent by the client:
app.get('/get-cookies', (req, res) => {
// Get the username cookie, if available
const username = req.cookies.username || 'Guest';
res.send(`Hello, ${username}!`);
});
Signed Cookies
For enhanced security, cookie-parser allows you to sign cookies to prevent tampering. First, initialize cookie-parser with a secret:
// The secret string is used for signing cookies
app.use(cookieParser('my-secret-key'));
Now you can set and verify signed cookies:
// Setting a signed cookie
app.get('/set-signed-cookie', (req, res) => {
res.cookie('user_role', 'admin', { signed: true });
res.send('Signed cookie has been set!');
});
// Reading a signed cookie
app.get('/get-signed-cookie', (req, res) => {
// Signed cookies are available in req.signedCookies
const role = req.signedCookies.user_role || 'user';
res.send(`Your role is: ${role}`);
});
If a signed cookie has been tampered with, it won't be available in req.signedCookies
.
Cookie Options
When setting cookies, you can provide various options to control their behavior:
res.cookie('preferences', JSON.stringify({ theme: 'dark' }), {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: true, // Not accessible via JavaScript
secure: true, // Only sent over HTTPS
sameSite: 'strict', // CSRF protection
path: '/dashboard', // Cookie is available only on this path
domain: '.example.com' // Cookie is available on all subdomains
});
Clearing Cookies
To clear a cookie, use the res.clearCookie()
method:
app.get('/logout', (req, res) => {
// Clear the username cookie
res.clearCookie('username');
// Make sure to use the same options that were used when setting the cookie
res.clearCookie('preferences', {
path: '/dashboard',
domain: '.example.com'
});
res.send('Logged out successfully');
});
Complete Example: Authentication Flow
Here's a more practical example showing a simplified authentication flow using cookies:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// Use cookie parser with a secret
app.use(cookieParser('auth-secret-key'));
app.use(express.json());
// Fake user database
const users = {
'[email protected]': 'password123'
};
// Login route
app.post('/login', (req, res) => {
const { email, password } = req.body;
if (users[email] && users[email] === password) {
// Set authentication cookie on successful login
res.cookie('authenticated', true, {
signed: true,
httpOnly: true,
maxAge: 3600000 // 1 hour
});
res.cookie('email', email, {
maxAge: 3600000 // 1 hour
});
res.json({ success: true, message: 'Login successful' });
} else {
res.status(401).json({ success: false, message: 'Invalid credentials' });
}
});
// Protected route
app.get('/profile', (req, res) => {
// Check for authenticated cookie
if (req.signedCookies.authenticated) {
const email = req.cookies.email;
res.send(`Welcome to your profile, ${email}!`);
} else {
res.status(401).send('Please login to view this page');
}
});
// Logout route
app.get('/logout', (req, res) => {
res.clearCookie('authenticated');
res.clearCookie('email');
res.send('Logged out successfully');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Best Practices for Using Cookies
-
Use HTTPS: Always set the
secure: true
option in production to ensure cookies are only sent over HTTPS connections. -
Set HttpOnly Flag: For cookies containing sensitive information like session IDs, use
httpOnly: true
to prevent access from JavaScript. -
Use SameSite Attribute: Set
sameSite: 'strict'
orsameSite: 'lax'
to protect against Cross-Site Request Forgery (CSRF) attacks. -
Minimize Cookie Size: Keep cookies small as they are sent with every HTTP request to your domain.
-
Set Expiration Dates: Use the
maxAge
orexpires
options to ensure cookies are not stored indefinitely. -
Sign or Encrypt Sensitive Cookies: Use signed cookies for data that shouldn't be tampered with, or consider encryption for sensitive data.
Common Issues and Solutions
Cookies Not Being Set
If cookies aren't being set, check:
- The response hasn't been sent before you call
res.cookie()
- Your domain configuration is correct
- You're not in an iframe with third-party cookie blocking
Cookies Not Being Sent Back
If cookies aren't being sent back to the server:
- Verify the cookie hasn't expired
- Check if the path and domain match
- For secure cookies, ensure you're using HTTPS
- For SameSite cookies, check that the request meets the SameSite requirements
Summary
The cookie-parser
middleware simplifies working with cookies in Express applications:
- It parses incoming Cookie headers and makes them available in
req.cookies
- It supports signed cookies for enhanced security
- It works seamlessly with Express's
res.cookie()
andres.clearCookie()
methods - It's essential for implementing sessions, authentication, and user preferences
When using cookies, remember to follow security best practices, particularly for sensitive applications. Cookies are powerful but should be used responsibly.
Additional Resources
Exercises
-
Create a simple Express application that sets a welcome cookie on a user's first visit and displays a different message on subsequent visits.
-
Implement a theme switcher using cookies to remember the user's preferred theme (light/dark).
-
Create a shopping cart using cookies to store the cart items between page loads.
-
Extend the authentication example to include different user roles and permission levels stored in signed cookies.
-
Build a GDPR-compliant cookie consent mechanism that sets different types of cookies based on user consent.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)