The State of pushState and REST
Posted by Dion Almaer 11 months ago on javascript
We have a feature on m.walmart.com that is good ‘ole fashion breadcrumbs. We show you where you have been in context. In the old days the server would have the session history and would be spewing out the needed markup. Today though, often the client is local, talking to backend services that response with JSON with data models. There may not be a session up there.
If your “session” state is living in the client, you can be tempted to use the state object in pushState to store some information related to the view change. We have done this in the breadcrumb solution as we need to know if you are going forward or backwards in the stack. This is harder than you think, and our solution ended up being holding an index to where the client was in the stack.
But wait, this means that if the user copies the given URL and opens it in a new session (new browser window say) then you may be in a different state. The RESTafarians do not rejoice, including Jeremy Ashkenas:
It’s very important that the first two arguments to pushState are never used — they’re a flaw in the API design.
Tying invisible “state” to a URL is exactly the opposite of what a URL is supposed to be. Now, navigating back from a pushState version of the URL, vs copying and pasting it into a new browser window, both behave differently.
Instead, store the “extra state” in a session.
If you start to store state in localStorage for example, then you are in the same situation where the same URL loaded in difference situations could have different results. The advantage of storing state with the history APIs themselves is that they are scoped to that world.
You also wouldn’t want to have a URL that has state in the URL itself, as that doesn’t make any sense.
Should pushState be pushUrl instead?