Backend Secure Cookie Configuration — Hardening Cookie-Based Sessions
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Backend Secure Cookie. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Secure cookie configuration prevents Session Hijacking, CSRF, and information disclosure through cookie attributes.
// Secure cookie configuration
const session = require('express-session');
const RedisStore = require('connect-redis').default;
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
name: '__Host-session', // Cookie prefix prevents overwrite by subdomains
resave: false,
saveUninitialized: false,
rolling: true, // Reset expiry on each request
cookie: {
httpOnly: true, // Not accessible via JavaScript
secure: true, // Only sent over HTTPS
sameSite: 'strict', // Not sent on cross-site requests
path: '/', // Scoped to entire site
domain: process.env.COOKIE_DOMAIN, // Explicit domain
maxAge: 24 * 60 * 60 * 1000, // 24 hours
signed: true // Signed to detect tampering
}
}));
// Set custom cookies with security attributes
function setSecureCookie(res, name, value, options = {}) {
res.cookie(name, value, {
httpOnly: true,
secure: true,
sameSite: options.sameSite || 'lax',
path: options.path || '/',
domain: options.domain,
maxAge: options.maxAge || 3600000,
signed: true,
...options
});
}
// Cookie signing verification
function verifyCookie(req, res, next) {
// Access signed cookies
const sessionCookie = req.signedCookies['__Host-session'];
if (!sessionCookie) {
return res.status(401).json({ error: 'Invalid session' });
}
// Verify cookie integrity
if (!req.session || !req.session.userId) {
res.clearCookie('__Host-session');
return res.status(401).json({ error: 'Session expired' });
}
next();
}
// Anti-tampering with cookie signature
const cookieParser = require('cookie-parser');
app.use(cookieParser(process.env.COOKIE_SECRET));
// Prefix security
// __Host- prefix requires: secure, path=/, no domain
// __Secure- prefix requires: secure
// Set cookie with __Host- prefix
res.cookie('__Host-auth', token, {
secure: true,
httpOnly: true,
sameSite: 'strict',
path: '/',
maxAge: 900000
});
Secure cookie configuration protects session data from interception, tampering, and cross-site attacks.
← Previous
Backend API Key Security — Securing API Key Authentication
Next →
Backend CORS Security — Configuring CORS for API Security
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro