node js express session expiration

To set up session expiration in Node.js with Express, you can follow these steps:

  1. Install the necessary dependencies:
  2. To handle sessions, you can use the express-session package. Install it by running npm install express-session.

  3. Import the required modules:

  4. In your Node.js file, import the modules by adding the following lines of code at the beginning: const session = require('express-session'); const app = express(); // assuming you have already imported the `express` module

  5. Configure the session middleware:

  6. Set up the session middleware by adding the following line of code before your routes: app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 60000 } // adjust the `maxAge` value to set the expiration time in milliseconds }));

  7. Implement session expiration logic:

  8. You can use the setTimeout function to implement session expiration. Inside your route or middleware, add the following code: setTimeout(() => { req.session.destroy((err) => { if (err) { console.log(err); } }); }, req.session.cookie.maxAge);

This code will destroy the session after the specified maxAge time.

  1. Handle session expiration:
  2. You can handle session expiration by checking if the session exists before accessing any session data. If the session doesn't exist, you can redirect the user to a login page or perform any other desired action.

That's it! By following these steps, you can set up session expiration in Node.js using Express.

Please note that you may need to adjust the code according to your specific requirements.