0
0
ExpressHow-ToBeginner · 4 min read

How to Use express-session for Session Management in Express

Use express-session middleware in your Express app by importing it, configuring session options like secret, and adding it with app.use(). This enables session data storage per user, allowing you to track user state across requests.
📐

Syntax

The basic syntax to use express-session involves importing the package, configuring it with options, and applying it as middleware in your Express app.

  • secret: A string to sign the session ID cookie, keeping it secure.
  • resave: Forces session to be saved back to the store even if it was never modified during the request.
  • saveUninitialized: Forces a session that is "uninitialized" to be saved to the store.
  • cookie: Options to configure the session cookie like expiration and security.
javascript
import express from 'express';
import session from 'express-session';

const app = express();

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

Example

This example shows a simple Express server using express-session to count how many times a user has visited the page during their session.

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

const app = express();

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}));

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

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 When visiting http://localhost:3000 multiple times, the page shows: - First visit: "Welcome! This is your first visit." - Subsequent visits: "Number of views: X" where X increments each time
⚠️

Common Pitfalls

Common mistakes when using express-session include:

  • Setting cookie.secure to true without HTTPS, causing cookies not to be saved.
  • Not providing a secret, which is required for signing the session ID cookie.
  • Using resave: true unnecessarily, which can cause performance issues.
  • Forgetting to use saveUninitialized: true when you want to save new sessions.

Always ensure your session middleware is added before your routes.

javascript
/* Wrong way: cookie.secure true without HTTPS */
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true } // This will block cookies on HTTP
}));

/* Right way: set secure false for HTTP or use HTTPS */
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}));
📊

Quick Reference

Remember these key points when using express-session:

  • secret: Always set a strong secret string.
  • cookie.secure: Use true only with HTTPS.
  • resave: Usually set to false to avoid unnecessary session saves.
  • saveUninitialized: Set to true to save new sessions, or false to comply with laws like GDPR.

Key Takeaways

Use express-session middleware with a secret to enable session management in Express.
Set cookie.secure to false for HTTP during development, true only with HTTPS in production.
Add session middleware before defining routes to ensure sessions work correctly.
Avoid resave: true unless necessary to improve performance.
Use saveUninitialized according to your app's privacy needs.