Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express Session / Cookie maxAge property refreshes on request

Code in app.js

var cookieParser = require("cookie-parser")
var session = require("express-session")


app.use(cookieParser())

app.set('trust proxy', 1)
app.use(session(
  {
    "name": '***',
    "secret": '***',
    "cookie": {
      "maxAge": null,
      "expires": null,
      "httpOnly": true,
      "secure": true
    },
    "rolling": false,
    "saveUninitialized": false,
    "resave": false,

}))

When logging in this end point gets hit

req.session.username = email    // defaults to putting something in cookie
    req.session.cookie.maxAge = 1000 * 5
    req.session.touch()

Test: finding the time left for cookie/session

router.get('/refresh-session', function(req, res){
    if (req.session){
        console.log(req.session.username)
        console.log(req.session.cookie.maxAge)
    }

})

My goal is to display a popup to the user in react notifying them that their session is about to expire. I will be refreshing the maxAge every time they navigate to a new page... However, before that I need to find out what the actual current maxAge is. Doing so seems to refresh the maxAge of the cookie. But this maxAge refresh isn't actually effecting the expiration time.

For example: If maxAge is set to 5 seconds (testing purposes) then calling the method to check the maxAge will consistently be between 4800-5000 millis. However, after the 5 seconds - no matter how many times I refresh - the cookie does expire at 5 seconds (which is intended).

The thing is why id maxAge reseting?

I've looked around and found some unhelpful git pages. Here: https://github.com/expressjs/session/issues/189#issuecomment-182631933 - doesn't work https://github.com/expressjs/session/issues/2 - very unhelpful

Anyone run into this issue or can suggest alternatives?

like image 561
Captain Save A Hoe Avatar asked Nov 01 '25 13:11

Captain Save A Hoe


1 Answers

The req.session.cookie.maxAge tells how much time is left in the session. It is reset at end of request to original value. This is documented in the README.md.

Your frontend can not ask the backend for how much of session is still left, because the session is touched at the request. You can set the cookie.maxAge already at the session parameters, no need to postpone until login. Your frontend should keep own timer and reset it at every request to backend.

like image 163
Marko Kohtala Avatar answered Nov 04 '25 05:11

Marko Kohtala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!