Query Parameters in Routes
You'll learn how to capture, modify, and preserve query parameters (like ?sort=name&filter=active) when navigating between routes, so users don't lose their view preferences.
What Are Query Parameters in Routes?
Query parameters are the key-value pairs that appear after the ? in a URL, like example.com/products?category=shoes&color=red. When building client-side routers, you need to read these parameters to configure your view (show filtered results) and preserve them during navigation so users maintain their context.
Think of query parameters like sticky notes on a filing cabinet drawer — they remind you which subset of files you were looking at, and you want them to stay in place as you move between sections.
Handling Query Parameters in Routes
When a route changes, you typically:
- Parse the current parameters using
URLSearchParamsfromwindow.location.search - Apply them to your view logic (filter data, set sort order, etc.)
- Preserve them when navigating to related routes
- Update them when users change filters, using
history.pushState()orreplaceState()
For example, when navigating from /products?sort=price to /products/123, you might want to preserve the sort parameter: /products/123?sort=price. This way, when users go back, their sorting preference remains intact.
Preserving State During Navigation
Use history.pushState() to navigate while keeping useful query parameters, and replaceState() when you want to update filters without adding a new history entry (like real-time search filtering).
Key Takeaway: Query parameters in routes let you encode view state directly in the URL, making your app's state shareable, bookmarkable, and history-friendly — but you must actively read, preserve, and update them as users navigate.