ExpressJS Cookies Management
Imagine you visit a coffee shop. The barista gives you a loyalty card and stamps it each time you buy coffee. On your fifth visit, you get a free coffee. That loyalty card works just like cookies in web development small pieces of data that a website stores on your browser to remember information about you.
What are Cookies?
Cookies are small text files stored on the user's browser by websites. They are used to remember stateful information (like login status, preferences, or shopping cart items) since HTTP is stateless it doesn't remember previous requests.
Installing Cookie Parser
Express doesn't handle cookies by default. You need the
cookie-parser middleware:npm install cookie-parserSetting Up Cookie Parser
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// Use cookie-parser middleware
app.use(cookieParser());
// Now you can access cookies via req.cookiesSetting Cookies
Use the
res.cookie() method to set a cookie:app.get('/set-cookie', (req, res) => {
// Basic cookie
res.cookie('username', 'John');
// Cookie with options
res.cookie('theme', 'dark', {
maxAge: 24 * 60 * 60 * 1000, // 1 day in milliseconds
httpOnly: true, // Can't be accessed by JavaScript
secure: false, // Set to true for HTTPS only
sameSite: 'lax' // CSRF protection
});
res.send('Cookies set!');
});Cookie Options Explained
- maxAge How long the cookie lives (in milliseconds)
- expires Specific expiration date
- httpOnly Prevents JavaScript access (security against XSS)
- secure Only send over HTTPS
- sameSite CSRF protection (strict, lax, none)
- domain Which domain the cookie belongs to
- path Which paths the cookie is sent to
Reading Cookies
With cookie-parser, all cookies sent by the browser are available in
req.cookies:app.get('/get-cookie', (req, res) => {
// Read all cookies
console.log(req.cookies);
// Read a specific cookie
const username = req.cookies.username;
const theme = req.cookies.theme;
if (username) {
res.send(`Welcome back, ${username}! Your theme is ${theme}`);
} else {
res.send('No cookies found');
}
});Clearing Cookies
To remove a cookie, use
res.clearCookie():app.get('/clear-cookie', (req, res) => {
// Clear a specific cookie
res.clearCookie('username');
res.clearCookie('theme');
res.send('Cookies cleared');
});Practical Example: Remember Me Functionality
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
// Login page
app.get('/login', (req, res) => {
// Check if already logged in via cookie
if (req.cookies.loggedIn === 'true') {
return res.redirect('/dashboard');
}
res.send(`
`);
});
// Handle login
app.post('/login', (req, res) => {
const { username, password, remember } = req.body;
// In a real app, you'd validate credentials against database
if (username === 'john' && password === 'secret') {
// Set cookie if remember me is checked
if (remember) {
res.cookie('loggedIn', 'true', {
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
httpOnly: true
});
res.cookie('username', username, {
maxAge: 7 * 24 * 60 * 60 * 1000
});
}
res.redirect('/dashboard');
} else {
res.send('Invalid credentials');
}
});
// Dashboard (protected)
app.get('/dashboard', (req, res) => {
if (req.cookies.loggedIn === 'true') {
res.send(`Welcome to your dashboard, ${req.cookies.username}! Logout`);
} else {
res.redirect('/login');
}
});
// Logout
app.get('/logout', (req, res) => {
res.clearCookie('loggedIn');
res.clearCookie('username');
res.send('Logged out! Login again');
});Two Minute Drill
- Cookies store small amounts of data on the client browser.
- Use
cookie-parsermiddleware to handle cookies in Express. - Set cookies with
res.cookie(name, value, options). - Read cookies from
req.cookies. - Delete cookies with
res.clearCookie(name). - Important options: maxAge, httpOnly, secure, sameSite.
- Cookies are commonly used for authentication, preferences, and tracking.
Need more clarification?
Drop us an email at career@quipoinfotech.com
