0
0
ExpressHow-ToBeginner · 3 min read

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, including httpOnly.
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: true in production, which ensures cookies are sent only over HTTPS.
  • Setting cookies without a proper path or domain, 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

OptionDescriptionExample
httpOnlyPrevents client-side JavaScript access{ httpOnly: true }
secureSends cookie only over HTTPS{ secure: true }
maxAgeCookie expiration in milliseconds{ maxAge: 3600000 }
pathLimits cookie to a specific path{ path: '/' }
domainLimits 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.