react-cookie unable to set expires or maxAge

24.2k Views Asked by At

I cannot seem to set the expiration for a cookie with react-cookie... here is my setup:

import { Cookies } from 'react-cookie'
const cookies = new Cookies()
import moment from 'moment'

The following attempts have failed:

cookies.set('cookieName', {key: value}, {path: '/', expires: new Date(Date.now()+2592000)})
cookies.set('cookieName', {key: value}, {path: '/', expires: moment().add(30, "days")})
cookies.set('cookieName', {key: value}, {path: '/', maxAge: 2592000})

Chrome continues to present:

Expires
When the browsing session ends
5

There are 5 best solutions below

3
On

It seems that Cookies from react-cookie has been moved to the universal-cookie package. So the following should work:

import Cookies from 'universal-cookie';

const cookies = new Cookies();
cookies.set('cookieName', {key: value}, {path: '/', expires: new Date(Date.now()+2592000)});
0
On

Example with expire after one year

import Cookies from 'universal-cookie';

const cookies = new Cookies();
const current = new Date();
const nextYear = new Date();

nextYear.setFullYear(current.getFullYear() + 1);

cookies.set('cookieName', true, {
    path: '/',
    expires: nextYear,
});

Here you can see more on how to use Date.set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear

0
On

Ok, so this may be a simple solution for some of you coming to this thread. (Myself included) I had my app running with universal-cookies without a maxAge property in the .set method before adding a max age of 30 days or 2592000 seconds. When I added maxAge: 2592000 to my set cookie method the browser said that it was still going to expire at the end of the session. The fix for me was to clear the app data in the Dev tools -> Application -> Storage -> Clear Site Data then re log in to my app and the cookies were set to expire in 30 days correctly. For reference:

cookies.set("loggedinUserId", response.data.userID, { path: '/', maxAge: 2592000 });
0
On

I've been trying to figure out what I was doing wrong and I think I found it.

First, some users are stating that maxAge property in the .set method is the solution. Well, this could work but if the user reloads the browser, the cookie will disappear and this would make no sense.

The solution is to play around with the expires property. I did this:

import Cookies from "universal-cookie";

const cookies = new Cookies();
const expirationDate = new Date();

// (Just change 7 for the number of days you want to let this cookie exist)
expirationDate.setDate(expirationDate.getDate() + 7);

const cookieExists = cookies.get("myCookie");

if (!cookieExists) {
  cookies.set("myCookie", `ImTheValue`, { path: '/', expires: expirationDate });
}

As you can see, cookieExists makes the validation of the cookie easier. If the cookie doesn't exist, it will create it. If it does, it won't set a new expiration date.

This would do the trick!

I Hope this can be useful to anyone out there with the same problem I had.

0
On

A little late, but if anyone out there is still having trouble with this. In universal-cookie try using the maxAge option instead of expires.

Here's a snippet of how I got mine to work.

cookies.set("theme", 0, {
    path: "/",
    maxAge: 1000000
});

Being honest you're better off using the normal cookie setting stuff. Info Here

You're gonna have to use document.cookie anyway to interact with your already set cookie right from loading anyways. Here's a snippet of my code for that. Along with the useState hook for reference.

Like shown in this doc, document.cookie shows you a list of all cookies output like this.

cookieOne=1; cookieTwo=poopy; cookieThree=etc

So, write something like this out. Substituting "theme" for your cookie name. This code will give you that value.

const docThemeCookie = document.cookie
  .split("; ")
  .find((row) => row.startsWith("theme"))
  .split("=")[1];

You'll get a string back no matter what, so if its a int or anything else convert appropriately. Here's my useState hook with my cookie needing to be an int.

const [theme, setTheme] = useState(parseInt(docThemeCookie, 10));

Hope that helps whoever is still stuck!

TLDR;

Use maxAge instead of expires.

Use document.cookie to check initial cookie value for state.