Use history.pushState() when a same-document router needs to add a session-history entry without loading a new document. It can attach state and update the URL. Use history.replaceState() instead when the current entry should be updated rather than adding another. section 10.3.6 section 11.2
Changing the URL is not the same as rendering a route. pushState() does not fire popstate, so render from location immediately after calling it. Listen for popstate separately to render after Back or Forward traversal. section 10.3.6 section 11.2
Keep the fallback narrow and preserve normal browser navigation:
- Start with real links. Intercept only same-origin application links; leave external links, downloads, other targets, modifier-key clicks, and hash jumps to the browser. section 10.3.6 section 15.4
- For navigation initiated by code, put pushState() and the subsequent render in one helper rather than scattering calls throughout the application. section 11.2
Navigate after a save
After a form saves, a routing helper can add the destination with pushState() and then render from location. If the destination should replace the current entry, use replaceState(). When the Navigation API is available, the same helper can delegate to navigation.navigate() instead. section 11.2
Table 11.1 Deciding on storing state data in URL or in history entry
State |
Belongs in the URL |
Belongs in history entry state |
Selected product |
Yes, as |
No, because the route should be shareable. |
Search filters |
Usually, as query parameters. |
Only if the filters are private or temporary. |
Scroll position inside a panel |
No. |
Yes, because it belongs to the current browsing session. |
Open disclosure panel |
Maybe, if it should be shareable. |
Yes, if it is only UI convenience. |
Choose the URL for shareable route data, and history-entry state for temporary browsing-session details such as a panel’s scroll position. section 11.2
