0

I am creating a react application with using cookies.Here is my class.

export class Auth {
  static config = {
    domain: `${process.env.GRP_APP_HOST?.includes('localhost') ? '.' + process.env.GRP_APP_HOST : ''}`,
  };

  static setToken(token: string) {
    const now = new Date();
    const minutes = 30;
    now.setTime(now.getTime() + (minutes * 60 * 1000));

    if (token) {
      document.cookie = `auth_token=${token}; domain=${this.config.domain}; expires=${now.toUTCString()}`;
    }
  }

  static getToken() {
    return document.cookie
      .split('; ')
      .find(row => row.startsWith('auth_token='))
      ?.split('=')[1];
  }

  static clear() {
    document.cookie = 'auth_token=; Max-Age=0; expires = Thu, 01 Jan 1970 00:00:00 GMT;';
  }
}

I am setting the cookie to expire after 30 minutes. The problem is that currently, I am in GMT +4 timezone and the cookie expiration date is being calculated wrong ( -3.5 hours ).I know that cookies expiration date format should be UTC or GMT format. How should I set the correct format that will also cover the timezone differences ?

Norayr Ghukasyan
  • 1,298
  • 1
  • 14
  • 28
  • Does this answer your question? [How can I set a cookie with expire time?](https://stackoverflow.com/questions/13154552/how-can-i-set-a-cookie-with-expire-time) – Martheen Jul 22 '22 at 13:01
  • @Martheen Here also is the same.The expiration time is universal and in my case, if I use it and add 30 minutes of expiration time, it will be 3.5 hours behind my local time ( I am on GMT +4 ) – Norayr Ghukasyan Jul 22 '22 at 13:23
  • @Martheen I need to configure it the way it is taking into account the timezone and sets the correct time. In my case, it should be right after 30 minutes of my timezone. – Norayr Ghukasyan Jul 22 '22 at 13:24
  • Why not use max age? And the way things happens it seems either your/server/user OS clock is configured incorrectly – Martheen Jul 22 '22 at 13:25
  • They are set in the browser directly from frontend not from the server. – Norayr Ghukasyan Jul 22 '22 at 13:26

0 Answers0