vvo/iron-session

Static maxAge

jordanpurinton opened this issue · 1 comments

Each time I update the session I want to maintain the previous value of the Max Age value in the cookie. However, using the options presented in the documentation I can't seem to get this working. Can we looking into adding support for this?

vvo commented

Hey there, I just found a solution how to do this.
First, on login, you compute a date in milliseconds you want to use as the date you want the cookie to expire, no matter what. Then you store this value in the session object directly, and you update the config, something like:

function login() {
  const session = await getIronSession<SessionData>(cookies(), sessionOptions);
  const expirationTimestamp = Date.now() + 30 * 24 * 60 * 1000;
  session.isLoggedIn = true;
  session.counter = 0;
  session.expirationTimestamp = expirationTimestamp;

  session.updateConfig({
    ...sessionOptions,
    cookieOptions: {
      ...sessionOptions.cookieOptions,
      maxAge: undefined,
      expires: new Date(session.expirationTimestamp),
    },
  });
  await session.save();
}

Then everytime you call session.save(), make sure to:

function sessionAction() {
  const session = await getIronSession<SessionData>(cookies(), sessionOptions);
  session.counter++;

  session.updateConfig({
    ...sessionOptions,
    cookieOptions: {
      ...sessionOptions.cookieOptions,
      maxAge: undefined,
      expires: new Date(session.expirationTimestamp),
    },
  });
  await session.save();
}