1 year ago

#76868

test-img

Eulavo

Express-Session: How to keep session alive?

I'm currently using express-session with connect-mongodb-session to store sessions and cookies.

This is my implementation:

app.js

const store = new MongoDBStore({
    uri: mongoURI,
    collection: 'mySessions'
});

app.use(session({
    secret: 'whatever',
    store: store,
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 30000 // only 30 secs to to help with testing
    }
}))

app.use(express.urlencoded({ extended: true }))

app.use(async (req, res, next) => {
    console.log('req.session', req.session)
    try {
        if (req.session && req.session.userId) {
            const user = await User.findById(req.session.userId)
            req.user = user
            req.session.auth = true
            res.locals.auth = req.session.auth
        } else {
            res.locals.auth = null
        }

        next()

    } catch (error) {
        console.log('auth middleware error', error)
    }
})

Right now I'm using 30 seconds for maxAge so I can test the behaviour of the app.

What happens is if the user closes the browser and comes back before 30 seconds, they remain logged in. Else, the cookie is no longer valid and the user has to log in again. This is ok.

However, if the user is browsing and, after 30 seconds, they make any request, the cookie is no longer active.

I'd like to make like this: If the user is using the app, but the 30 seconds maxAge is done, the session and cookie are renewed automatically, with a renewed maxAge, so the user doesn't have to log in again while he is using the app.

But if the user closed the browser and came back after maxAge, they are required to login again (which already happens).

Thank you.

node.js

session

cookies

0 Answers

Your Answer

Accepted video resources