Express Session Management

📘 Express.js 👁 40 views 📅 Nov 05, 2025
⏱ Estimated reading time: 3 min

Sessions allow you to store user data on the server between HTTP requests. This is essential for authentication, shopping carts, and other stateful applications.


1. Install Required Packages

npm install express express-session
  • express-session – Middleware for session handling

  • Optionally, use connect-mongo or connect-redis for persistent session storage


2. Basic Session Setup

const express = require('express'); const session = require('express-session'); const app = express(); app.use(express.json()); app.use(session({ secret: 'mysecretkey', // Secret key for signing the session ID resave: false, // Do not save session if unmodified saveUninitialized: true, // Save new sessions cookie: { maxAge: 60000 } // Session expiration in milliseconds })); 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! First visit.'); } }); app.listen(3000, () => console.log('Server running on port 3000'));
  • req.session – Access or modify session data

  • cookie.maxAge – Set session expiration


3. User Login with Sessions

// Dummy user const user = { id: 1, username: 'admin', password: '1234' }; app.post('/login', (req, res) => { const { username, password } = req.body; if (username === user.username && password === user.password) { req.session.userId = user.id; // Store user info in session return res.send('Logged in successfully'); } res.status(401).send('Invalid credentials'); }); // Protected route app.get('/dashboard', (req, res) => { if (!req.session.userId) return res.status(401).send('Unauthorized'); res.send(`Welcome user ${req.session.userId} to the dashboard`); });
  • Only logged-in users can access protected routes

  • Session persists until expiration or logout


4. Logging Out

app.post('/logout', (req, res) => { req.session.destroy(err => { if (err) return res.status(500).send('Could not log out'); res.send('Logged out successfully'); }); });
  • Destroys the session and clears cookies


5. Storing Sessions in a Database

  • For production, store sessions in a database instead of memory to persist across server restarts.

Example with MongoDB:

npm install connect-mongo
const MongoStore = require('connect-mongo'); app.use(session({ secret: 'mysecretkey', resave: false, saveUninitialized: false, store: MongoStore.create({ mongoUrl: 'mongodb://localhost:27017/express_sessions' }), cookie: { secure: false, maxAge: 3600000 } }));
  • MongoStore.create() stores session data in MongoDB

  • For production, set secure: true if using HTTPS


6. Best Practices

  1. Use a strong secret for signing sessions

  2. Store sessions in a persistent store (MongoDB, Redis)

  3. Set cookie options:

    • httpOnly: true – Prevent JavaScript access

    • secure: true – Send cookies only over HTTPS

  4. Expire sessions after inactivity

  5. Avoid storing sensitive info directly in session


7. Example Project Structure

express-session-app/ │ ├─ app.js // Express setup & session configuration ├─ routes/ │ └─ auth.js // Login, logout, and protected routes └─ package.json
  • Keeps session logic modular and maintainable

  • Easy to scale with persistent session stores


Session management in Express.js ensures stateful user interactions, making authentication and personalized experiences possible.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes