Projects
Client-Side Routing
Build a SPA router from scratch. Learn hash-based routing, the History API, dynamic route parameters, navigation guards, query strings, and how to intercept anchor clicks without a framework.
What You Will Build
1
Route Matching
Pattern-to-regex, named :params, wildcard 404 fallback
2
Hash vs History
hashchange vs pushState/popState — pros and cons
3
Navigation Guards
Run async guards before each navigation (auth checks)
4
Active Links
Highlight current link, intercept <a> clicks globally
Hash vs History API
| Feature | Hash (#) | History API |
|---|---|---|
| URL looks like | example.com/#/users/1 | example.com/users/1 |
| Browser event | hashchange | popstate |
| Server needed? | No — hash never sent to server | Yes — server must return index.html for all paths |
| SEO | Poor — hash not crawled by default | Good — real URLs are crawled |
| pushState needed? | No | Yes — for programmatic navigation |
| Best for | Simple demos, static hosts | Production apps with a real server |
Common Pitfalls
Deploying a History API SPA to a static host without a server fallback — all routes except / return 404 on refresh
Configure server to return index.html for all paths (nginx try_files, Vercel vercel.json rewrites, etc.)
Rebuilding the entire DOM on every route change — losing scroll position, animation state, form input
Use a virtual DOM diff or just replace a #view container. Persist shared UI (nav, sidebar) outside the view outlet.
Forgetting to call e.preventDefault() when intercepting link clicks — page reloads anyway
Always call e.preventDefault() before history.pushState(). Guard with closest('[data-router-link]') to avoid blocking external links.
No navigation guards — authenticated pages accessible by directly typing the URL
Run guards synchronously before rendering. Redirect to /login and return false to cancel navigation if token is missing.
Build It Live
Code Editor
<nav>
<a href="#/">Home</a> <a href="#/about">About</a> <a href="#/users/42">User 42</a> <a href="#/nope">Broken</a>
</nav>
<main id="view"></main>Preview
Client-Side Routing — step by step
1
History API Fundamentals
history.pushState adds a new entry to the browser history stack and updates the URL without a page reload. The state object is serialised with the entry so you can restore it when the user navigates back.
1 of 4
🔍Always Handle the Initial Load
A client-side router must handle the URL on first page load, not just on link clicks. If a user lands directly on /dashboard/profile, your router must parse that URL and render the correct view immediately, before any navigation events have fired.
🎯 Quick Check
Which event fires when the user clicks the browser's Back or Forward button in a single-page app?
Next project