Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 156 ยท Browser APIs

URLs, Location and History

Parse and build URLs safely with URL and URLSearchParams, read and change location, and update the address bar with history.pushState for client routing.

The address bar is part of your user interface. A good URL tells people where they are, can be bookmarked and shared, and should bring them back to the same view: the same search, the same filters, the same tab. JavaScript gives you three tools for working with it:

  • URL and URLSearchParams parse, build and edit URLs safely, without fiddly string handling.
  • location tells you the current page's address and can navigate to a new one.
  • history lets you change the address bar without loading a new page, which is how single-page apps do routing.

You'll use all three in this lesson and finish with a small client-side router.

Parsing a URL

Pass a string to new URL() and you get an object with every part of the address split out. Each part has a name worth learning, because the same names appear on location and on links (<a> elements) too:

JS The parts of a URL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

An invalid string makes new URL() throw a TypeError. To check without try/catch, use URL.canParse(text), which returns true or false, or URL.parse(text), which returns a URL or null. Both are recent additions (2023โ€“2024) but are now supported in all current browsers.

Relative URLs need a base

A path like "/about" or "../img/logo.png" isn't a complete URL on its own. Give new URL() a second argument, the base, and it resolves the path the same way a browser resolves a link:

JavaScript
new URL("/about", "https://example.com/blog/post-1").href;
// "https://example.com/about"

new URL("photo.jpg", "https://example.com/blog/post-1").href;
// "https://example.com/blog/photo.jpg"

new URL("../css/site.css", "https://example.com/blog/2024/post").href;
// "https://example.com/blog/css/site.css"

// On a real page, resolve against the current address:
new URL("/search", location.href);

Query strings with URLSearchParams

The part after ? holds query parameters: key=value pairs separated by &. Building that by hand breaks as soon as a value contains a space, &, = or a non-English character. URLSearchParams handles the encoding for you. Every URL has one at url.searchParams, and changes to it update the URL immediately:

JS Reading and changing query parameters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can also create one on its own from a string, an object or a list of pairs. This is handy for building request URLs for fetch():

JavaScript
const query = new URLSearchParams({ city: "Sรฃo Paulo", units: "metric" });
const endpoint = `https://api.example.com/weather?${query}`;
// "https://api.example.com/weather?city=S%C3%A3o+Paulo&units=metric"

Never glue user input into a URL by hand. Something like "?q=" + input.value breaks or misbehaves the moment someone types & or #. Let URLSearchParams (or encodeURIComponent() for single values) do the encoding. The HTML course explains how URL encoding works.

Building filter URLs: a worked example

Here's a common job: turn the state of a filter panel into a shareable URL, and read it back when the page loads. Values from the URL are always strings, so convert them back carefully and provide defaults:

JS Filters to URL and back

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The location object

window.location (or just location) describes the current page's URL. It has the same properties as a URL object (href, pathname, search, hash and so on), plus methods that navigate:

JavaScript
location.href;                    // the full current URL
new URLSearchParams(location.search).get("page"); // read a query parameter

location.assign("/checkout");     // go to a new page (adds a history entry)
location.href = "/checkout";      // same as assign()
location.replace("/login");       // go there, replacing the current entry
location.reload();                // reload the page

location.hash = "#comments";      // jump within the page, no reload

Use replace() for redirects the user shouldn't come "back" to, such as a login page that forwards to the dashboard. Otherwise pressing Back would bounce them straight to the redirect again.

The editors on this site run inside a sandboxed frame created from inline HTML, so their location is a special internal address rather than a normal web URL. The next example prints it; on your own pages, the same code shows the real address:

JS Where is this code running?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Changing the URL without reloading: the History API

Assigning to location loads a new page. Single-page apps want something different: change the address bar to /products/42 and draw the product view themselves, with no reload. The History API does exactly that:

JavaScript
// Add a new entry to the session history and change the URL
history.pushState({ productId: 42 }, "", "/products/42");

// Change the current entry instead of adding a new one
history.replaceState({ productId: 42, tab: "reviews" }, "", "/products/42?tab=reviews");

history.state;   // the state object of the current entry
history.back();  // same as the browser's Back button
history.forward();
history.go(-2);  // two steps back

The three arguments are a state object (any data that structuredClone can copy), an unused title argument (pass ""), and the new URL, which must be on the same origin as the page. pushState() doesn't load anything and doesn't fire any event. It's up to your code to update the page.

popstate: reacting to Back and Forward

When the user presses Back or Forward between entries your code created, the browser fires a popstate event on window. The page doesn't reload; you read location or event.state and render the right view:

JavaScript
window.addEventListener("popstate", (event) => {
  console.log("Now at", location.pathname, "with state", event.state);
  render(location.pathname);
});

pushState is blocked in these editors. The sandboxed preview has an opaque origin, so the browser refuses to set a URL for it and throws a SecurityError. On a normal page the same call works. The router below catches that error and keeps its own in-memory history instead, so you can still see how routing works.

A tiny client-side router

A router maps paths to views. The pattern has three parts: links call navigate() instead of loading a page, navigate() updates the URL with pushState() and renders, and a popstate listener renders again on Back/Forward.

A minimal router

The code uses event delegation: one listener on the <nav> handles every link. Real links (<a href>) are kept on purpose; they still work for middle-click, "open in new tab" and search engines.

The server's part

A history-based router has one more requirement. If someone bookmarks https://example.com/products/7 and opens it later, the browser asks the server for /products/7. The server must answer with the same app page for every route, and the router then renders the right view. Most hosting platforms and frameworks have a setting for this "fallback to index.html".

The older alternative is hash routing (https://example.com/#/products/7). Everything after # never reaches the server, so no server setup is needed. You listen for the hashchange event instead of popstate. It works everywhere but produces less tidy URLs.

Looking ahead: the newer Navigation API (navigation.navigate(), the navigate event) is designed to replace much of this boilerplate by intercepting every navigation in one place. It has been in Chromium-based browsers for several years and reached Firefox and Safari by early 2026 (Baseline newly available since January 2026), but older browser versions lack it, so check your audience before relying on it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For https://example.com/blog?page=2#top, what is url.search?

    The search property includes the leading question mark. Use searchParams to read individual values.
  2. 2. params.get("size") returns "42". Why a string?

    Everything in a URL is text. Convert values to the types your app needs.
  3. 3. What does history.pushState(state, "", "/cart") do?

    pushState() only updates the URL and session history. Your code must render the new view itself.
  4. 4. When does the popstate event fire?

    popstate fires on history traversal such as Back and Forward, not when your own code calls pushState().
  5. 5. Which is the safe way to add a search term typed by the user to a URL?

    searchParams encodes special characters like &, = and # so the URL stays valid.

Summary

  • new URL(text, base) parses a URL into parts like origin, pathname, search and hash; use URL.canParse() to validate.
  • url.searchParams reads and edits query parameters with automatic encoding; values are always strings.
  • location describes the current address; assign(), replace() and reload() navigate.
  • history.pushState() and replaceState() change the URL without a reload; popstate fires on Back and Forward.
  • A client-side router intercepts link clicks, pushes the new URL, renders the view and listens for popstate; the server must serve the app for every route.

Next: Intersection, Resize and Mutation Observers โ€” react when elements scroll into view, change size or change content.