Open In App

What is express-session middleware in Express?

Last Updated : 25 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the Express web application, the express-session middleware is mainly used for managing the sessions for the user-specific data. In this article, we will see the use of express-session middleware for session management in Express with practical implementation.

Prerequisites

What is express-session Middleware?

The express-session middleware allows the creation and storage of the session data used for authentication or user preferences. Using this middleware, we can properly maintain the stateful interaction between the Express.js server and the client. Using the sessions the security of the application is maintained and interaction with the user is increased.

Steps to use express-session middleware in Express.js

Step 1: In the first step, we will create the new folder by using the below command in the VS Code terminal.

mkdir folder-name
cd folder-name

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init-y

Step 3: Now, we will install the express dependency for our project using the below command.

npm i express

Step 4: As we need to use the express-session middleware, we need to install it using npm. So for this article, we will be using third-party middleware as a express-session. So install it using the below command.

npm i express-session

Project Structure:

The updated dependencies in package.json file will look like.

"dependencies": {
"express": "^4.18.2",
"express-session": "^1.17.3"
}

Example: Write the following code in App.js file

Javascript




//app.js
const express = require('express');
const session = require('express-session');
const app = express();
const port = 3000;
// setting the session middleware
app.use(session({
    secret: 'gfg-key',
    resave: false,
    saveUninitialized: true
}));
// set session in the / route
app.get('/', (req, res) => {
    // session variable
    req.session.gfgUser = 'geeksforgeeks';
    res.send(`Hey Geek! Session is set! Now Go to
        <a href="/get">/get</a> to retrieve the session.`);
});
// get session in the /get route
app.get('/get', (req, res) => {
    // retrieve the session variable
    const gfgUser = req.session.gfgUser || 'No session set';
    res.send(`Session variable: ${gfgUser}`);
});
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});


To run the application, we need to start the server by using the below command.

node app.js

Output:

Output1



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads