Session Management in Node.js

Session management in Node.js is essential for maintaining state between HTTP requests, especially in web applications that require user authentication. Node.js, being stateless by nature, needs external tools to manage sessions, such as express-session.

Installing the Middleware

To get started, you need to install the express-session package:

npm install express express-session

Configuring express-session

Once installed, we can configure express-session in our Express server:

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
  secret: 'my-secret-key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false } // set to true if using HTTPS
}));

Using the Session

After configuration, we can access and modify session data via req.session:

app.get('/login', (req, res) => {
  req.session.user = 'Mario';
  res.send('User logged in');
});

app.get('/profile', (req, res) => {
  if (req.session.user) {
    res.send(`Profile of ${req.session.user}`);
  } else {
    res.send('User not authenticated');
  }
});

Session Persistence

For production environments, it is recommended to use a persistent store like connect-redis or connect-mongo, instead of the default memory store:

npm install connect-redis redis
const RedisStore = require('connect-redis').default;
const session = require('express-session');
const redis = require('redis');

let redisClient = redis.createClient();

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: 'my-secret-key',
  resave: false,
  saveUninitialized: false
}));

Conclusion

Session management in Node.js with express-session is simple and powerful. It allows you to maintain user state and build secure and efficient web applications. However, for greater scalability and security, it is advisable to integrate an external storage solution and use HTTPS in production.

Back to top