Home > Blockchain >  How do I set idle session timeout and max session timeout in nodejs express app?
How do I set idle session timeout and max session timeout in nodejs express app?

Time:11-26

I have a NodeJS Express App and need to set idle session timeout and max session timeout on the app. Is there any setting or option that can be used to set these values? I looked at cookie.expires and cookie.maxAge. Are these used to set the idle timeout and session timeout, respectively. Can someone please help me with this?

Thanks a ton in advance!

CodePudding user response:

A session vanishes when its session cookie expires in the user's browser. It also can expire after a certain amount of time if you implement that in your server.

To set an idle timeout of, let's say, 300 seconds, you do this. On every hit to your server you send the session cookie again with an expiration time of now 300 seconds. If the user doesn't hit the server again before the cookie expires, the next hit will not have the cookie and so the user won't appear to be logged in .

To set an overall timeout (max session timeout) you use server code. Put an expiration time on your session data. Thereafter whenever you look up the session data based on the session id in the session cookie check the expiration. If the session has expired, handle the hit to your server as if the user were not logged in.

CodePudding user response:

"Handling session can be done on both the side, browser, and server-side.

for the server-side, you have to use the express-session npm package here is the sample code for setting the expiration time of the session.

const express = require('express')
const session = require('express-session')
 // Use the session middleware
 const app = express()
 app.use(session({
  secret: 'its my secret',
  cookie: { maxAge: 60000 }, // value of maxAge is defined in milliseconds. 
  resave: false,
  rolling: false,
  saveUninitialized: true
}))

//above-defined code will set session which will get expired after 60 seconds.

The expires option should not be set directly; instead only use the maxAge option. resave Forces the session to be saved back to the session store, even if the session was never modified during the request. rolling: Force the session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. To set any value in session, use req.session. = "

  • Related