How to Set HttpOnly Cookie in Express: Simple Guide
In Express, set an HttpOnly cookie by using
res.cookie('name', 'value', { httpOnly: true }). This flag makes the cookie inaccessible to JavaScript, improving security against cross-site scripting attacks.Syntax
Use res.cookie(name, value, options) to set cookies in Express. The httpOnly option is a boolean that, when true, prevents client-side scripts from accessing the cookie.
name: The cookie's name as a string.value: The cookie's value as a string.options: An object to configure cookie behavior, includinghttpOnly.
javascript
res.cookie('token', 'abc123', { httpOnly: true });
Example
This example shows a simple Express server that sets an HttpOnly cookie named token when you visit the root URL. The cookie cannot be accessed by JavaScript in the browser.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { res.cookie('token', 'securevalue123', { httpOnly: true }); res.send('HttpOnly cookie has been set'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
When visiting http://localhost:3000, the response sets a cookie named 'token' with HttpOnly flag.
Common Pitfalls
Common mistakes when setting HttpOnly cookies include:
- Forgetting to set
httpOnly: true, which leaves the cookie accessible to JavaScript and vulnerable to attacks. - Not using
secure: truein production, which ensures cookies are sent only over HTTPS. - Setting cookies without a proper
pathordomain, causing unexpected behavior.
Always combine httpOnly with secure in production for best security.
javascript
/* Wrong way: cookie accessible by JavaScript */ res.cookie('token', 'value'); /* Right way: HttpOnly and secure cookie */ res.cookie('token', 'value', { httpOnly: true, secure: true });
Quick Reference
| Option | Description | Example |
|---|---|---|
| httpOnly | Prevents client-side JavaScript access | { httpOnly: true } |
| secure | Sends cookie only over HTTPS | { secure: true } |
| maxAge | Cookie expiration in milliseconds | { maxAge: 3600000 } |
| path | Limits cookie to a specific path | { path: '/' } |
| domain | Limits cookie to a specific domain | { domain: 'example.com' } |
Key Takeaways
Use res.cookie with { httpOnly: true } to set HttpOnly cookies in Express.
HttpOnly cookies protect against JavaScript access and reduce XSS risks.
Combine httpOnly with secure: true in production to ensure cookies are sent over HTTPS only.
Always specify cookie options like path and maxAge for better control.
Test cookies in browser DevTools under Application > Cookies to verify settings.