0
0
ExpressHow-ToBeginner · 4 min read

How to Use Session in Express: Simple Guide with Example

To use sessions in Express, install and import express-session, then add it as middleware with a secret key. This middleware creates a req.session object to store user data across requests.
📐

Syntax

Use the express-session middleware by importing it and calling app.use(session({...})) with options:

  • secret: a string to sign the session ID cookie
  • resave: forces session to be saved even if unmodified (usually false)
  • saveUninitialized: saves new sessions that are unmodified (usually false)
  • cookie: options for the session cookie like maxAge
javascript
import session from 'express-session';

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 60000 }
}));
💻

Example

This example shows a simple Express app that uses sessions to count how many times a user visits the page. The count is stored in req.session and increases on each visit.

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

const app = express();

app.use(session({
  secret: 'my-secret',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 300000 }
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`Number of views: ${req.session.views}`);
  } else {
    req.session.views = 1;
    res.send('Welcome! This is your first visit.');
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // On first visit: "Welcome! This is your first visit." // On subsequent visits: "Number of views: 2", "Number of views: 3", etc.
⚠️

Common Pitfalls

  • Not setting a secret causes errors or insecure sessions.
  • Using resave: true unnecessarily can cause performance issues.
  • Forgetting to set saveUninitialized: false can create empty sessions.
  • Not handling cookies properly may cause sessions to expire too soon or not persist.
  • Sessions require cookies enabled in the browser to work.
javascript
/* Wrong way: Missing secret and default options */
app.use(session({}));

/* Right way: Set secret and options */
app.use(session({
  secret: 'my-secret',
  resave: false,
  saveUninitialized: false
}));
📊

Quick Reference

express-session options cheat sheet:

OptionDescriptionTypical Value
secretString to sign session ID cookieRequired string
resaveSave session even if unmodifiedfalse
saveUninitializedSave new but unmodified sessionsfalse
cookie.maxAgeSession cookie lifetime in ms60000 (1 minute)
cookie.secureSend cookie only over HTTPSfalse (true in production)

Key Takeaways

Use the express-session middleware with a secret to enable sessions in Express.
Store and access session data via req.session object in your routes.
Set resave and saveUninitialized to false for better performance and security.
Sessions depend on cookies, so ensure cookies are enabled in the client browser.
Configure cookie options like maxAge and secure for session lifetime and security.