How to keep a cookie value when user visit other pages?

I want to maintain a cookie that is set to not to disappear when a user visit other pages. The situation in my code is that it gets a parameter of the page location and saves it into the / path.

Here’s my code:

window.onload = function() {
    try {
        var url_string = (window.location.href).toLowerCase();
        var url = new URL(url_string);
        // Get gclid,token or fbclid parameters
        var gclid = url.searchParams.get("gclid");
        var token = url.searchParams.get("token");
        var fbclid = url.searchParams.get("fbclid");

        // token expires in 6 hours
        document.cookie = `gclid=${gclid}; max-age=21600` + ";path=/";
        document.cookie = `token=${token}; max-age=21600` + ";path=/";
        document.cookie = `fbclid=${fbclid}; max-age=21600` + ";path=/";

    } catch (err) {
        console.log("Issues with Parsing URL Parameter's - " + err);

Example:   // saves the cookie value

When going to other pages it also sets a value to null because the cookie is coming from the url parameters.

the gclid=123 is stored in a cookie in the path /. But when I go to other pages like

the gclid cookie will be equal/set to null.

The situation here in my code is that everytime the user visits a pages the url.searchParams searches for the desired parameter and if it does found those parameter the cookie will be sit to null.

How do I keep the previous value of the cookie gclid if the new gclid contains a null value in my page? And updates the gclid if it does not contains a null value.

1 thought on “How to keep a cookie value when user visit other pages?”

Leave a Comment