Javascript cookie not working on another page

December 26, 2021 • Category - Web Development, Javascript • 4,149 views
ShareShare on FacebookShare on Twitter

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');

0 Comments


Leave a Comment

Share your questions, thoughts and ideas while maintaining a considerate tone towards others, thank you.

All fields are required - your email address will not be published.