Skip to content

Custom way of session rolling #1094

@jakub-msqt

Description

@jakub-msqt

My goal is to extend the session expiration when 2/3 of its duration has passed instead of doing this on every request.

For that, I've kept the rolling option disabled and I've written a custom middleware as follows:

export const sessionTouchMiddleware = (req: Request, _res: Response, next: NextFunction) => {
  if (!req.session.userId || !req.session.cookie) {
    return next()
  }

  const { originalMaxAge, expires } = req.session.cookie

  if (!originalMaxAge || !expires) {
    return next()
  }

  const sessionStart = expires.getTime() - originalMaxAge
  const elapsedMs = Date.now() - sessionStart

  // Touch the session if two-thirds of its lifespan elapsed
  if (elapsedMs >= originalMaxAge * (2 / 3)) {
    req.session.cookie.maxAge = originalMaxAge
    req.session.touch()
  }

  next()
}

The above has no effect. I'm using connect-pg-simple store. Any help is appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions