Skip to content
Related Articles

Related Articles

Improve Article

How to expire session after 1 min of inactivity in express-session of Express.js ?

  • Last Updated : 09 Sep, 2021

In this article, we will see how to expire the session after 1 min of inactivity in express-session of Express.js.

Prerequisites

Requires Modules:

npm install express
npm install express-session

Call API:

var session = require('express-session')

To expire the session after 1 min of inactivity in express-session of Express.js we use expires: 60000 in the middleware function.



Project Structure:

Below example illustrates above approach:

Example:

Filename: app.js

Javascript




// Call Express Api.
var express = require('express'),
 
    // Call express Session Api.
    session = require('express-session'),
 
    app = express();
 
// Session Setup
app.use(
    session({
 
        // It holds the secret key for session
        secret: "I am girl",
 
        // Forces the session to be saved
        // back to the session store
        resave: true,
 
        // Forces a session that is "uninitialized"
        // to be saved to the store
        saveUninitialized: false,
        cookie: {
 
            // Session expires after 1 min of inactivity.
            expires: 60000
        }
    })
);
 
// Get function in which send session as routes.
app.get('/session', function (req, res, next) {
 
    if (req.session.views) {
 
        // Increment the number of views.
        req.session.views++
 
        // Session will expires after 1 min
        // of in activity
        res.write(
'
<p> Session expires after 1 min of in activity: '
+ (req.session.cookie.expires) + '</p>
')
        res.end()
    } else {
        req.session.views = 1
        res.end(' New session is started')
    }
})
 
// The server object listens on port 3000.
app.listen(3000, function () {
    console.log("Express Started on Port 3000");
});

Run index.js file using below command:

node app.js

Now to set your session, just open the browser and type this URL :

http://localhost:3000/session
 

Output: After 1 min of inactivity it will start the new session,old session is expired.




My Personal Notes arrow_drop_up
Recommended Articles
Page :