How to Set Secure Cookie in Express: Simple Guide
In Express, set a secure cookie by using
res.cookie() with the secure: true option, which ensures cookies are sent only over HTTPS. Also, use httpOnly: true to prevent client-side scripts from accessing the cookie for better security.Syntax
The res.cookie(name, value, options) method sets a cookie in Express. The name is the cookie's key, value is the cookie's content, and options is an object to configure cookie behavior.
- secure: When
true, cookie is sent only over HTTPS. - httpOnly: When
true, cookie is inaccessible to JavaScript in the browser. - maxAge: Sets cookie expiration in milliseconds.
- sameSite: Controls cross-site sending of cookies.
javascript
res.cookie('token', 'value', { secure: true, httpOnly: true, maxAge: 3600000, sameSite: 'strict' });
Example
This example shows how to set a secure, HTTP-only cookie named sessionId that expires in one hour. It uses Express to send the cookie only over HTTPS connections.
javascript
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.cookie('sessionId', 'abc123', { secure: true, // cookie sent only over HTTPS httpOnly: true, // inaccessible to client JS maxAge: 3600000, // expires in 1 hour sameSite: 'strict' // restrict cross-site sending }); res.send('Secure cookie set'); }); app.listen(3000, () => { console.log('Server running on https://localhost:3000'); });
Output
Server running on https://localhost:3000
When visiting https://localhost:3000, the browser receives a secure, HTTP-only cookie named 'sessionId'.
Common Pitfalls
Common mistakes when setting secure cookies include:
- Setting
secure: trueon a server without HTTPS, causing cookies not to be sent. - Omitting
httpOnly: true, which exposes cookies to client-side scripts and increases risk of attacks. - Not setting
sameSite, which can lead to CSRF vulnerabilities.
Always ensure your server uses HTTPS before enabling secure.
javascript
/* Wrong: secure cookie on HTTP server - cookie won't be sent */ res.cookie('token', 'value', { secure: true }); /* Right: use secure only on HTTPS server */ res.cookie('token', 'value', { secure: true, httpOnly: true, sameSite: 'lax' });
Quick Reference
Tips for setting secure cookies in Express:
- Use
secure: trueonly if your site uses HTTPS. - Always set
httpOnly: trueto protect cookies from JavaScript access. - Set
sameSiteto'strict'or'lax'to reduce CSRF risks. - Use
maxAgeorexpiresto control cookie lifetime.
Key Takeaways
Set
secure: true to send cookies only over HTTPS for safety.Use
httpOnly: true to prevent client-side JavaScript from accessing cookies.Configure
sameSite to protect against cross-site request forgery.Do not enable
secure on non-HTTPS servers or cookies won't be sent.Always set cookie expiration with
maxAge or expires.