0
0
NodejsHow-ToBeginner · 4 min read

How to Use Session in Node.js with express-session

To use session in Node.js, install and use the express-session middleware with Express. It stores user data on the server between requests, enabling features like login persistence.
📐

Syntax

Use the express-session middleware by importing it and configuring it with options like secret, resave, and saveUninitialized. Then add it to your Express app with app.use().

  • secret: A string to sign the session ID cookie.
  • resave: Forces session to be saved even if unmodified.
  • saveUninitialized: Saves new sessions that are unmodified.
javascript
import express from 'express';
import session from 'express-session';

const app = express();

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

Example

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

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

const app = express();

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

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`Number of visits: ${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 // When visiting http://localhost:3000 multiple times: // First visit: "Welcome! This is your first visit." // Subsequent visits: "Number of visits: 2", "Number of visits: 3", etc.
⚠️

Common Pitfalls

  • Not setting a secret causes errors or insecure sessions.
  • Using resave: true unnecessarily can cause performance issues.
  • Forgetting to use saveUninitialized: true can prevent sessions from being saved initially.
  • Not using HTTPS with cookies can expose session data.
  • Not clearing sessions on logout leaves user data accessible.
javascript
/* Wrong: Missing secret */
app.use(session({
  resave: false,
  saveUninitialized: true
}));

/* Right: Include secret */
app.use(session({
  secret: 'your-secret',
  resave: false,
  saveUninitialized: true
}));
📊

Quick Reference

Remember these key options when using express-session:

  • secret: Required string to sign cookies.
  • resave: Usually false to avoid unnecessary saves.
  • saveUninitialized: true to save new sessions.
  • cookie.secure: Set to true in production with HTTPS.

Key Takeaways

Use the express-session middleware to enable sessions in Node.js with Express.
Always set a strong secret to secure session cookies.
Configure resave and saveUninitialized options properly to optimize performance.
Store session data on the server to keep user state between requests.
Clear sessions on logout to protect user privacy.