sweetscript / next-app-session

A Next.js App router secure server-side session library
MIT License
28 stars 3 forks source link

expires cant set? #8

Open Jan-T-Berg opened 10 months ago

Jan-T-Berg commented 10 months ago
export const session = nextAppSession<MySessionData>({
  // Options
  name: 'SID',
  secret: process.env.JWT_SECRET,
  cookie: {
    httpOnly: process.env.NODE_ENV == 'production',
    secure: process.env.NODE_ENV == 'production',
    sameSite: 'strict',
    expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7), // 1 week
  },
});

I would like to set the session manually. Unfortunately, this does not work.

export type CookieOptions = {
    httpOnly: boolean;
    path: string;
    domain?: string | undefined;
    secure: boolean;
    sameSite?: boolean | 'lax' | 'strict' | 'none';
    maxAge?: number;
    expires?: Date | null;
};
majidkuhail commented 10 months ago

Hi @Jan-T-Berg

Thanks for flagging.

The expires property was excluded from the initialiser typescript definition because it might not make sense setting up an expiry date on the initialisation of the session function, and would make more sense to set it when session data is created. I understand that it's not possible to use expiries properly with the package yet, I'm working on updating the docs with a section about expiry and refactoring some logic to allow better expiry control.

However, You can use maxAge property instead of expires to achieve what you want. Just pass:

export const session = nextAppSession<MySessionData>({
  // Options
  name: 'SID',
  secret: process.env.JWT_SECRET,
  cookie: {
    httpOnly: process.env.NODE_ENV == 'production',
    secure: process.env.NODE_ENV == 'production',
    sameSite: 'strict',
    maxAge:  60 * 60 * 24 * 7, // 1 week,
  },
});
majidkuhail commented 10 months ago

Just noticed maxAge is not working as expected, I'll create an issue and push a fix for it.

majidkuhail commented 10 months ago

I've released a new version 1.0.7 that fixed the issue with maxAge not being set correctly.

Please keep in mind maxAge expects the value in seconds.

Jan-T-Berg commented 10 months ago

Hey,

That was really fast. Thanks for the quick fix. I had first tried this with maxAge, but since that didn't work, I just bet on expires. Thank you for taking on the topic.

Jan-T-Berg commented 10 months ago

expires would be important. Let's say I realise a login, I would like to use a cookie with an expiration. Of course I can write a token into the database and then create a session via the token cookie, but it would be easier if the cookie of the session remains stored and the user then simply realises this.