---
title: Add Pagination To URL
slug: template-js/add-pagination-to-url
docTags: 
createdAt: 2022-09-13T00:28:50.000Z
---



There are times when it is beneficial to have the users selected pagination captured and stored as part of the URL.

For Example :

- Allow for consistent tracking of the selected page of results.
- Reusable 'landing  page' links
- SEO

To accomplish this we will add in a custom override module that will:

1. Intercept the outgoing query
2. Analyze the existing URL string
3. Update the localstorage of selected page value
4. Apply the page offset to the outgoing query
5. Update the existing URL string

See : [Custom Overrides](docId:_bc3GcThleEaToYujDtuE) for details on preparing for Klevu JS overriding


## Template JS Override

Add the supporting module `addPaginationToURL` and apply it to the landing page override.

**Note :** the same `addPaginationToURL` module can be used on Category pages by applying the override to the `catnav` scope as well.

**Full Example**

:::CodeblockTabs
JavaScript

```html
<script type="text/javascript">

klevu.modifyRequest("landing,catnav", function(data, scope){
    // Apply the selected page value from the current URL string            
    klevu.search.modules.addPaginationToURL.base.getAndUpdatePagination(data, scope);
});

klevu.afterTemplateRender("landing,catnav", function(data, scope){
    // Add selected page value to the URL string
    klevu.search.modules.addPaginationToURL.base.setPagination(data, scope);
});

</script>

<script type="text/javascript">

// addPaginationToURL module
(function(klevu) {
  klevu.extend(true, klevu.search.modules, {
      addPaginationToURL: {
          base: {
              setPagination: function(data, scope, queryId) {
                  var hasPaginationEnabled = klevu.getSetting(klevu, "settings.theme.modules.pagination.searchResultsPage.enable");
                  if (hasPaginationEnabled === true) {
                      var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                      if (queryId && queryId.length) {
                          activeQueryId = queryId;
                      }
                      var paginationQueryParam = activeQueryId + "PgNo";
                      var activeQueryMeta = klevu.getObjectPath(data, "template.query." + activeQueryId + ".meta");
                      var paginationValuesQueryParam = 0;
                      if (activeQueryMeta) {
                          var productListLimit = activeQueryMeta.noOfResults;
                          paginationValuesQueryParam = Math.ceil(activeQueryMeta.offset / productListLimit) + 1;
                      }
                      var searchPath = window.location.search;
                      var updatedPath;
                      
                      // write to the URL if we're on page 2 or above
                      if (paginationValuesQueryParam > 1) {
                          updatedPath = klevu.dom.helpers.updateQueryStringParameter(searchPath, paginationQueryParam, paginationValuesQueryParam);

                      // otherwise remove the pagination from URL
                      } else {
                          updatedPath = searchPath.replace(new RegExp('[?&]' + paginationQueryParam + '=[^&]*'), '');
                          if (updatedPath.charAt(0) === '&') {
                              updatedPath = '?' + updatedPath.substring(1);
                          }
                      }
                      
                      if ('undefined' !== typeof window.history && 'undefined' !== typeof window.history.replaceState) {
                          window.history.replaceState({}, "", updatedPath);
                      } else {
                          console.log("This browser does not have the support of window.history or window.history.replaceState");
                      }
                  }
              },
              getAndUpdatePagination: function(data, scope, queryId) {
                  var hasAlreadyTriggered = klevu.getObjectPath(scope.kScope, "element.kScope.getAndUpdatePaginationTriggered");
                  if (hasAlreadyTriggered === true) {
                      return;
                  }
                  var matchedQueryParamId = ""
                    , matchedQueryParamValue = "";
                  var recordQueries = klevu.getObjectPath(data, "request.current.recordQueries");
                  if (recordQueries && recordQueries.length) {
                      klevu.each(recordQueries, function(key, query) {
                          if (query.id) {
                              var paginationFromURL = klevu.dom.helpers.getQueryStringValue(query.id + "PgNo");
                              if (paginationFromURL && paginationFromURL.length) {
                                  matchedQueryParamId = query.id;
                                  matchedQueryParamValue = paginationFromURL;
                              }
                          }
                      })
                  }
                  klevu.setObjectPath(scope.kScope, "element.kScope.getAndUpdatePaginationTriggered", true);
                  var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                  if (queryId && queryId.length) {
                      activeQueryId = queryId;
                  } else if (matchedQueryParamId.length && matchedQueryParamValue.length) {
                      activeQueryId = matchedQueryParamId;
                      var storage = klevu.getSetting(scope.kScope.settings, "settings.storage");
                      if (storage.tabs) {
                          storage.tabs.setStorage("local");
                          storage.tabs.mergeFromGlobal();
                          storage.tabs.addElement("active", activeQueryId);
                          storage.tabs.mergeToGlobal();
                      }
                  }
                  var paginationQueryParam = activeQueryId + "PgNo";
                  var paginationFromURL = klevu.dom.helpers.getQueryStringValue(paginationQueryParam);
                  paginationFromURL = Number(paginationFromURL);
                  if (paginationFromURL && paginationFromURL > 1) {
                      var recordQueries = klevu.getObjectPath(data, "request.current.recordQueries");
                      if (recordQueries.length) {
                          klevu.each(recordQueries, function(key, recordQuery) {
                              if (recordQuery.id === activeQueryId) {
                                  var limit = klevu.getObjectPath(recordQuery, "settings.limit");
                                  limit = Number(limit);
                                  if (limit > 0) {
                                      var expectedOffset = (paginationFromURL - 1) * limit;
                                      klevu.setObjectPath(data, "localOverrides.query." + activeQueryId + ".settings.offset", expectedOffset);
                                  }
                              }
                          });
                      }
                  }
              }
          },
          build: true
      }
  });
}
)(klevu);

</script>
```
:::

