How to use express-session in Node.js

To use express-session, you need to first install the express and express-session modules. You can do so by using the following command:

npm install express express-session

After installation is complete, you can include the express and express-session modules in your application.

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

Next, you need to configure and use the express-session middleware in your application. You can add the express-session middleware to your application using the app.use method.

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

In this configuration object, you must provide a “secret” option for encrypting session data. You can choose any string you like as the key. The “resave” option is a boolean value indicating whether to save the session on each request. The “saveUninitialized” option is also a boolean value indicating whether to add an uninitialized session on a request.

Once the configuration is completed, you can access and use the session in your route handler. The session will be provided through the req.session object, which you can manipulate as you would a regular JavaScript object. For example, you can add data to the session by setting properties.

app.get('/login', (req, res) => {
  req.session.username = 'john';
  res.send('Logged in successfully');
});

You can also retrieve data from the session by accessing its properties.

app.get('/profile', (req, res) => {
  const username = req.session.username;
  res.send(`Welcome ${username}`);
});

When users access the /login route, their username will be saved in the session. When they access the /profile route, their username will be retrieved from the session and displayed.

This is a basic example of using express-session. You can configure and use it according to your needs.

bannerAds