Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.5 — The History API and Client-Side Routing
JavaScript · Example 2 of 2

A hash router with a route parameter

The route /users/:id is a regular expression with a capture group; the captured text is passed to the view. Each hash change adds a history entry, so Back steps through them.

A single-page app changes the view without loading a new page: history.pushState changes the address and adds a Back-button entry, the popstate event tells you when the user goes Back or Forward, and a router maps each URL to what should be shown; hash routing is the simpler, older variant.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write matchRoute(path) that returns { name: "user", id: "42" } for /users/42, { name: "home" } for /, and null otherwise.

02

Write a navigate(path) that skips pushing when path equals the current route and otherwise pushes and renders.

Explain it without notes

01

What problems does client-side routing solve in a single-page app?

02

What do pushState, replaceState and popstate each do? Which of them fire events?

03

Compare hash routing and path (History API) routing.

04

What does a good router do besides swapping content?

A hash router with a route parameter

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

/ -> Home
/users -> Users: Asha, Ravi
/users/2 -> Profile of Ravi
/users/9 -> No such user
/nowhere -> 404