How do you add or update a URL query parameter without reloading in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you add or update a URL query parameter without reloading in JavaScript?

message-square
0

To add or update a URL query parameter without reloading the page in JavaScript, read the current location with new URL(window.location.href), modify query parameters cleanly using url.searchParams.set("key", "value") (or .append() when multiple values for the same key are needed), and update the browser address bar without triggering a navigation or reload via window.history.replaceState(...) (to replace the current history entry) or window.history.pushState(...) (to create a new back/forward history entry). Using the URL and URLSearchParams APIs handles percent-encoding automatically and avoids fragile string concatenation bugs.


1. Updating or Adding a Query Parameter with URL, URLSearchParams, and history.replaceState()

Parse window.location.href into a URL instance, set the parameter on url.searchParams, and update the address bar without reloading:

// Add or update a single query parameter without reloading the page
function setQueryParamWithoutReload(key, value, { push = false } = {}) {
  if (typeof key !== "string" || key.trim().length === 0) {
    throw new TypeError("Expected key to be a non-empty string.");
  }

  if (typeof window === "undefined" || !window.history) {
    throw new Error("Browser history API is unavailable in this environment.");
  }

  const url = new URL(window.location.href);

  if (value === null || value === undefined || String(value) === "") {
    url.searchParams.delete(key);
  } else {
    url.searchParams.set(key, String(value));
  }

  const nextUrl = `${url.pathname}${url.search}${url.hash}`;
  const state = window.history.state ?? null;

  if (push) {
    window.history.pushState(state, "", nextUrl);
  } else {
    window.history.replaceState(state, "", nextUrl);
  }

  return url.toString();
}

// Example usage:
// Current URL: https://example.com/search?q=react
// setQueryParamWithoutReload("page", 2);
// Address bar becomes: https://example.com/search?q=react&page=2 (no reload)
  • .set() vs. .append(): searchParams.set(k, v) replaces existing values for k (or adds it if absent), whereas .append(k, v) adds another entry with the same key.
  • Deleting empty/nullish values: Removing null, undefined, or "" params keeps URLs clean instead of leaving ?page= behind.

2. Batch-Updating Multiple Query Parameters Non-Mutatingly

When updating several filter or pagination keys at once, apply all changes to a single URL object before calling history.replaceState() or history.pushState() once so the address bar updates atomically:

// Update multiple query parameters in a single history operation
function updateQueryParams(updates, { push = false } = {}) {
  if (updates === null || typeof updates !== "object" || Array.isArray(updates)) {
    throw new TypeError("Expected updates to be a plain object.");
  }

  const url = new URL(window.location.href);

  for (const [key, value] of Object.entries(updates)) {
    if (value === null || value === undefined || value === "") {
      url.searchParams.delete(key);
    } else {
      url.searchParams.set(key, String(value));
    }
  }

  const nextUrl = `${url.pathname}${url.search}${url.hash}`;
  const method = push ? "pushState" : "replaceState";
  window.history[method](window.history.state ?? null, "", nextUrl);

  return url.searchParams.toString();
}

// Example usage:
// updateQueryParams({ sort: "newest", page: 1, draft: null });
  • Single history call per batch: Updating multiple keys before calling replaceState avoids redundant URL mutations and extra state churn.
  • Preserves pathname and hash: Constructing nextUrl from url.pathname, url.search, and url.hash keeps path and fragment anchors intact.

3. pushState vs. replaceState, SPA State Sync, and Origin Gotchas

Choose pushState when users should be able to click Back to undo the query change (such as search queries, tabs, or pagination), and replaceState when the query reflects ephemeral or continuous UI state (such as live typing or scroll position) that should not pollute back-button history:

// Listen to browser Back/Forward navigation when pushState is used
function onUrlChange(callback) {
  if (typeof callback !== "function") {
    throw new TypeError("Expected callback to be a function.");
  }

  const handlePopState = () => {
    const currentUrl = new URL(window.location.href);
    callback(currentUrl.searchParams, currentUrl);
  };

  window.addEventListener("popstate", handlePopState);
  return () => window.removeEventListener("popstate", handlePopState);
}

// Example usage:
// const unsubscribe = onUrlChange((params) => {
//   console.log("Active page param:", params.get("page"));
// });
  • pushState / replaceState do not fire popstate: popstate fires when the user navigates history (Back/Forward) or calls history.back()/go(), so update your app state directly when calling pushState/replaceState.
  • Same-origin rule: pushState and replaceState throw a SecurityError if you pass a URL with a different origin (scheme, host, or port) than window.location.origin.