Sessions in Express Js

  • Sessions in Express.js are used to maintain state and user data across multiple requests. Unlike cookies, which are stored on the client side, session data is stored on the server side. Express.js does not have built-in support for sessions, but various middleware, such as `express-session`, can be used to implement session handling.
  • Let's go through an example using the `express-session` middleware to illustrate how sessions work in an Express.js application:
Install `express-session`:
  • First, you need to install the `express-session` middleware. Open your terminal and run the following command:

    npm install express-session


Create an Express App (`app.js`):


    // app.js

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

    const app = express();
    const PORT = 3000;

    // Use express-session middleware
    app.use(session({
        secret: 'my-secret-key', // A secret key used to sign the session ID cookie
        resave: false, // Forces the session to be saved back to the session store, even if it wasn't modified during the request
        saveUninitialized: true, // Forces a session that is "uninitialized" to be saved to the store
    }));

    // Route to set session data
    app.get('/set-session', (req, res) => {
        // Set a session variable
        req.session.user = 'john-doe';
        res.send('Session data has been set!');
    });

    // Route to read session data
    app.get('/get-session', (req, res) => {
        // Read the session variable
        const userName = req.session.user;

        if (userName) {
            res.send(`Hello, ${userName}!`);
        } else {
            res.send('No session data found.');
        }
    });

    // Route to clear session data
    app.get('/clear-session', (req, res) => {
        // Clear the session
        req.session.destroy((err) => {
            if (err) {
                res.send('Error clearing session.');
            } else {
                res.send('Session has been cleared!');
            }
        });
    });

    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });

  • In this example: We use the `express-session` middleware to handle sessions. The middleware is configured with a `secret` key used to sign the session ID cookie, `resave` to control whether the session should be saved even if not modified, and `saveUninitialized` to control whether a new but not modified session should be saved.
  • The `/set-session` route sets a session variable named 'user' with the value 'john-doe'.
  • The `/get-session` route reads and displays the value of the 'user' session variable.
  • The `/clear-session` route destroys the session, effectively clearing all session data.
  • Run the Application: Run your application using the command:

    node app.js

  • Test the Routes: Visit the following URLs in your browser or use tools like Postman:
    • http://localhost:3000/set-session: This will set the 'user' session variable.
    • http://localhost:3000/get-session: This will read and display the value of the 'user' session variable.
    • http://localhost:3000/clear-session: This will clear the session.
Observations:
  • The `/set-session` route sets the 'user' session variable.
  • The `/get-session` route reads and displays the value of the 'user' session variable.
  • The `/clear-session` route clears the session.
  • This example demonstrates the use of sessions in Express.js using the `express-session` middleware. Sessions allow you to store and retrieve user-specific data across multiple requests, making them useful for implementing features like user authentication and maintaining user state.

No comments:

Post a Comment