How to persist state through query string in url

In some cases when you do not have the option of cookies to manage state, query string can be a good option.

In this article, I am going to use some Javascript to persist state through a query string in the url. The Javascript code is added to head section of html when the desired query string is present in the url and then that Javascript will add that query string to all the internal urls on that page.

Here is the code-

const elements = document.querySelectorAll("a");
var url ='';
var theURL = '';
elements.forEach(function (element) {
    url = element.getAttribute('href');
    if ( url.startsWith('https://example.com') ) {
        try {
            theURL = new URL(url);
            if ( theURL ) {
                let params = new URLSearchParams(theURL.search);
                params.set( 'key', 'value' );
                theURL.search = params;
                element.setAttribute('href', theURL);
            }
        } catch(e) {
        }
    }
});

Now you can persist the query string throughout the user session. You can use the query string to identify the session details on the server.

Hope this helps.

Leave a Comment

Your email address will not be published. Required fields are marked *