0
0
ExpressHow-ToBeginner · 4 min read

How to Use cookie-session in Express for Simple Session Management

To use cookie-session in Express, first install it with npm install cookie-session. Then, require and use it as middleware by calling app.use(cookieSession({ keys: ['your-secret-key'] })) to enable cookie-based session management.
📐

Syntax

The cookie-session middleware is used by calling app.use(cookieSession(options)). The options object configures the session behavior:

  • keys: An array of secret keys to sign and verify cookies for security.
  • name: (Optional) The name of the cookie (default is session).
  • maxAge: (Optional) How long the cookie lasts in milliseconds.
  • secure: (Optional) If true, cookie is only sent over HTTPS.
javascript
const cookieSession = require('cookie-session');

app.use(cookieSession({
  name: 'session',
  keys: ['secretKey1', 'secretKey2'],
  maxAge: 24 * 60 * 60 * 1000 // 24 hours
}));
💻

Example

This example shows a simple Express app using cookie-session to count how many times a user visits the page. The count is stored in the session cookie and increments on each visit.

javascript
import express from 'express';
import cookieSession from 'cookie-session';

const app = express();

app.use(cookieSession({
  name: 'session',
  keys: ['mySecretKey'],
  maxAge: 24 * 60 * 60 * 1000 // 24 hours
}));

app.get('/', (req, res) => {
  if (!req.session.views) {
    req.session.views = 1;
  } else {
    req.session.views++;
  }
  res.send(`You visited this page ${req.session.views} times.`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 When visiting http://localhost:3000 repeatedly, the page shows: "You visited this page 1 times." "You visited this page 2 times." "You visited this page 3 times." and so on.
⚠️

Common Pitfalls

  • Not setting keys in options causes the session cookie to be unsigned and insecure.
  • Using secure: true without HTTPS will prevent cookies from being sent in development.
  • Modifying req.session incorrectly, like replacing it entirely, can break session persistence.
  • Forgetting to call app.use(cookieSession(...)) before routes means sessions won't work.
javascript
/* Wrong: Missing keys - insecure cookie */
app.use(cookieSession({
  name: 'session'
}));

/* Right: Provide keys for signing */
app.use(cookieSession({
  name: 'session',
  keys: ['secureKey']
}));
📊

Quick Reference

OptionDescriptionExample
keysArray of secret keys to sign cookieskeys: ['key1', 'key2']
nameCookie name (default 'session')name: 'mySession'
maxAgeCookie lifetime in millisecondsmaxAge: 86400000
secureSend cookie only over HTTPSsecure: true
httpOnlyPrevent client JS access to cookiehttpOnly: true

Key Takeaways

Always provide the 'keys' option to securely sign session cookies.
Use 'cookie-session' middleware before defining routes to enable sessions.
Store small session data directly in cookies; avoid large objects.
Set 'maxAge' to control how long sessions last in the browser.
Remember 'secure: true' requires HTTPS to send cookies.