Home  Express   How to dele ...

How to delete a session variable in Express

To delete a session variable in Express using express-session, you can use the delete operator to remove a specific property from the session object. Additionally, if you want to destroy the entire session, you can use the req.session.destroy() method. Here are the steps to delete a session variable:

Step-by-Step Guide

  1. Install express-session (if you haven't already):

    npm install express-session
    
  2. Set Up Express and express-session:

    Here’s a basic setup with routes for adding, deleting, and viewing session variables:

    const express = require('express');
    const session = require('express-session');
    
    const app = express();
    
    // Configure session middleware
    app.use(session({
        secret: 'your-secret-key', // Replace with your secret key
        resave: false,
        saveUninitialized: true,
        cookie: { secure: false } // Set to true if using HTTPS
    }));
    
    // Middleware to add session variables for demonstration
    app.use((req, res, next) => {
        if (!req.session.views) {
            req.session.views = 0;
        }
        req.session.views++;
        req.session.username = 'user123'; // Example variable
        next();
    });
    
    // Route to display session variables
    app.get('/session-info', (req, res) => {
        res.json(req.session); // Sends the session object as a JSON response
    });
    
    // Route to delete a specific session variable
    app.get('/delete-username', (req, res) => {
        delete req.session.username; // Delete the 'username' variable
        res.send('Username session variable deleted');
    });
    
    // Route to destroy the entire session
    app.get('/destroy-session', (req, res) => {
        req.session.destroy(err => {
            if (err) {
                return res.status(500).send('Failed to destroy session');
            }
            res.send('Session destroyed');
        });
    });
    
    // Start the server
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
    
  3. Explanation:

    • Session Configuration: Configures the session middleware.
    • Middleware to Add Session Variables: Adds example session variables (views and username).
    • Route to Display Session Variables: Sends the session object as a JSON response.
    • Route to Delete a Specific Session Variable:
      app.get('/delete-username', (req, res) => {
          delete req.session.username;
          res.send('Username session variable deleted');
      });
      
      • This route deletes the username variable from the session.
    • Route to Destroy the Entire Session:
      app.get('/destroy-session', (req, res) => {
          req.session.destroy(err => {
              if (err) {
                  return res.status(500).send('Failed to destroy session');
              }
              res.send('Session destroyed');
          });
      });
      
      • This route destroys the entire session, removing all session variables.
  4. Testing:

    • View Session Variables: Navigate to http://localhost:3000/session-info to see the current session variables.
    • Delete a Session Variable: Navigate to http://localhost:3000/delete-username to delete the username session variable. Then, check http://localhost:3000/session-info again to verify that the username variable is deleted.
    • Destroy the Session: Navigate to http://localhost:3000/destroy-session to destroy the session. Again, check http://localhost:3000/session-info to verify that all session variables are removed.
Published on: Jun 29, 2024, 04:14 PM  
 

Comments

Add your comment