Search code examples
javascriptnode.jsexpresscookies

Web cookies wrong maxAge


Im trying to set maxAge for my JWT cookie, i've configured 20 minutes to it, which is 1198 seconds. The variable maxAgeInSeconds is correct, but then the browser sets a wrong time (i think its due to the timezone offset)

Example cookie maxAge is stored as 20:15 PM when it should be 17:15 PM

Example JWT -> eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6Ijc5OTExNTI4LThjOGItNDcxNi05MTQ5LTRiMTJjMWJlYzFiNyIsIklzQWRtaW4iOnRydWUsIlJvbGVzIjpbIkFkbWluU29mdExpbmUiLCJVc3VhcmlvU29mdExpbmUiXSwiaWF0IjoxNzE0NDIwNTMwLCJleHAiOjE3MTQ0MjE3MzB9.Kj7nJqHHeBc5f5o0PllCa-eUrAbsRCmILiOvscpZoN4

cookie maxAge example

const accessToken = jwt.sign(
  {
    Id: user.UserId,
    Roles: roles
  },
  "SECRET",
  { expiresIn: "20m" }
)

const decodedJWT = utils.decodeJWT(accessToken);

// Convert to milliseconds
const expirationTime = decodedJWT.exp * 1000;

const currentTime = new Date().getTime();

// Convert to seconds
const maxAgeInSeconds = Math.floor((expirationTime - currentTime) / 1000); 

const serialized = serialize('token', accessToken, {
    httpOnly: true,
    secure: process.env.MODE === 'production',
    sameSite: 'strict',
    maxAge: maxAgeInSeconds,
    path: '/',
});

res.setHeader('Set-Cookie', serialized);

Solution

  • I'm not sure but i think that maxAge property should be passed in miliseconds.

    Maybe try to use built-in in express res.cookie() response method instead manually setting the header.

    Docs: https://expressjs.com/en/api.html#res.cookie

    Pay attention that maxAge property should be passed as miliseconds, not seconds!

    The usage will be almost the same:

    res.cookie('token', accessToken, {
        httpOnly: true,
        secure: process.env.MODE === 'production',
        sameSite: 'strict',
        maxAge: maxAgeInSeconds *1000, //milisecods!
        path: '/',
    });
    res.status(200).json({status: 'success'})