Javascript cookie not working on another page

Solution

When you set a cookie you should specify an expire time and a path. If you don’t specify a path the cookie is accessible only by the current page.

As per the MDN Web docs:

Cookie path – If not specified, defaults to the current path of the current document location.

An example of setting a maximum age and path:

// Set cookie with path.
document.cookie = "theme=dark; Max-Age=604800; path=/";

By setting path=/, the cookie is now available from every page in your application/domain. If you do not specify the path then the current cookie is saved just for the current page and you can’t access it from other pages.

Alternative option

A handy, lightweight JavaScript API for handling cookies is available here.

If using this API, then you can create a cookie, valid across the entire site with the following code:

// Set cookie.
Cookies.set('name', 'value');

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.