7

I've been using window.localstorage to save some data without problem, the data was persisting between sessions.

I decided to switch to using cookies, using 'react-cookie', code as follows:

import Cookies from 'react-cookie';

export default class Auth {
    static STORAGE_KEY: string = "token";

    static cookies = new Cookies();


    public static getToken() {
        var toRet = this.cookies.get(Auth.STORAGE_KEY);
        return toRet;
    }

    public static setToken(token: string) {
        this.cookies.set(Auth.STORAGE_KEY, token, { path: '/' });
    }

    public static removeToken(): void {
        this.cookies.remove(Auth.STORAGE_KEY, { path: '/' });
    }
}

If I call 'setToken' the value set persists, however if I close the brower and open it again that data is lost.

My root render function has the cookies provider as per the webpage https://www.npmjs.com/package/react-cookie:

import { CookiesProvider } from 'react-cookie';
export class Layout extends React.Component<{}, {}> {
    public render() {
        return <CookiesProvider> ( some stuff ) </CookiesProvider>
Ry-
  • 218,210
  • 55
  • 464
  • 476
meds
  • 21,699
  • 37
  • 163
  • 314
  • Cookies don't get deleted automatically unless you are in incognito mode, or you have configures your browser that way. Either way, how do you expect to solve this problem using programming? – Nisarg Shah Sep 16 '17 at 06:19

1 Answers1

17

The default cookie lifetime is “session”. You should set a maxAge:

this.cookies.set(Auth.STORAGE_KEY, token,
                 { path: '/', maxAge: 31536000 });

It’s in seconds.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • perfect, works exactly as expected. I'll mark yours as the 'answer' in 4 minutes when stackoverflow let's me. Thanks for the quick answer! – meds Sep 16 '17 at 06:29
  • @Kimmiekim: Which version of IE? – Ry- Dec 18 '18 at 02:36
  • @Ry- on IE11.. it works fine on chrome and firefox, but only on IE11, it deletes cookies on browser close.. – Kimmiekim Dec 18 '18 at 17:09
  • On IE you could try the `expires` (Date) parameter: absolute expiration date for the cookie. – ajr Apr 06 '20 at 08:40