Session in Express

A session is a feature in Express that let you maintaining state and user-specific data across multiple requests. sessions stores information at a server side with a unique session identifier. In a session you assign a unique session id to the client. After that client makes all request to the server with that unique id.

To use session in a Express, you have to install express-session package, It is a middleware that is used to provides a simple API for creating, reading, and updating session data.

npm install express-session

Example:

Javascript




//app.js
  
const express = require('express');
const session = require('express-session');
const app = express();
  
// Middleware to enable sessions
app.use(session({
    secret: 'secret_key',
    resave: false,
    saveUninitialized: true,
}));
  
//Route to set the session
app.get('/setSession', (req, res) => {
    // Setting session data
    req.session.username = 'w3wiki';
    res.send('Session set successfully!');
});
  
//Route to retrieve the session
app.get('/getSession', (req, res) => {
    // Retrieving session data
    const username = req.session.username;
    res.send(`Username from session: ${username}`);
});
  
//Route to destroy the session
app.get('/destroySession', (req, res) => {
    // Destroying the session
    req.session.destroy((err) => {
        if (err) {
            console.error(err);
        } else {
            res.send('Session destroyed successfully!');
        }
    });
});
  
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});


To Run the Application, Type the following command in terminal:

node index.js

Output

sessions example output

Difference between sessions and cookies in Express

Express.js is a popular framework for Node.js, that is used to create web applications. It provides tools to manage user sessions and cookies. The session and cookies are used to maintain the state and manage user authentication. In this article, we will learn about what sessions and cookies in Express and their differences.

Table of Content

  • Cookies in Express
  • Session in Express
  • Difference between Session and Cookies in Express

Similar Reads

Cookies in Express:

Cookies are small pieces of data that are stored on the client side (browser) in the form of a key-value pair. Cookies are used for session management, user preference,a and tracking of user behavior. when user loads the website a cookie is sent with the request that helps us to track the user’s actions....

Session in Express:

...

Difference between Session and Cookies in Express

A session is a feature in Express that let you maintaining state and user-specific data across multiple requests. sessions stores information at a server side with a unique session identifier. In a session you assign a unique session id to the client. After that client makes all request to the server with that unique id....