Idle Timeout in Express

Idle Timeout was not possible in express sessions until recently. You could set maxAge on the session’s cookie, but that would make the cookie expire after the given time regardless of activity. But it is more usual to want to expire the session after a certain amount of time with no activity. That is now possible with the rolling option.

Suppose you want to log users out automatically if they haven’t used your app for half an hour. You can do this with the following settings:

var idleTimeoutSeconds = 1800;

app.use(session({
resave: true,
cookie: {
maxAge: idleTimeoutSeconds * 1000,
},
rolling: true,

// … the rest of your options

}));

The rolling option is documented here but there’s a gotcha which is not mentioned: you have to set resave to true. It’s not obvious why this would be the case, since even without resave the session data is saved on change, and the rolling option appears to produce a change in the session upon every request. But without resave: true, I found that the session was expiring after the given time regardless of activity.

Leave a Comment

Your email address will not be published.

89 + = 93