Skip to content

Express.js: How to Store, Retrieve and Delete Session Data

Last updated on July 11, 2023

In Express.js, you can store, retrieve, and delete session data using middleware and session management libraries. One popular library for session management is “express-session.”

Here’s how you can use it to store, retrieve, and delete session data.

Let’s change the directory to project and Install the express-session package:

$ cd project_dir
$ npm install express-session

Now import the library and configure express-session in your Express.js application, as shown below.

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

const app = express();

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

In the configuration above, you provide a secret key that will be used to sign the session ID cookie. The resave option determines whether the session should be saved to the session store on every request, even if it hasn’t been modified. The saveUninitialized option controls whether a session should be saved to the store if it’s new but not modified.

Store session data:

app.get('/set-session', (req, res) => {
  req.session.username = 'Joel'; // Store username in session
  res.send('Session data set');
});

In this example, the username “Joel” is stored in the session object (req.session.username).

Retrieve session data:

app.get('/get-session', (req, res) => {
  const username = req.session.username; // Retrieve username from session
  res.send(`Username: ${username}`);
});

In this example, the username is retrieved from the session object (req.session.username).

Delete session data:

app.get('/clear-session', (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      console.error('Error destroying session:', err);
    }
    res.send('Session cleared');
  });
});

In this example, the destroy method is called on the session object (req.session.destroy()) to remove the session from the session store. The callback function is executed once the session is destroyed.

Remember that the session data is stored on the server side, and the session ID is stored as a cookie on the client side. Make sure to handle session data securely, protect the session ID cookie from attacks like session hijacking, and configure options such as session expiration and cookie settings to suit your application’s security requirements.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments