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('') ) {
        try {
            theURL = new URL(url);
            if ( theURL ) {
                let params = new URLSearchParams(;
                params.set( 'key', 'value' );
       = 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.

By Abhineet Mittal

Abhineet is IIM Alumnus and Founder of popular Digital Publishing Platform, Sahityapedia. He is a technology enthusiast by hobby & an avid reader.