URL as SPA Seed State

Don’t break the web

Gerard Rodes Vidal
Mar 13 · 2 min read
Medium wants me to add a feature image

Before starting, I would like to set the following quote as an axiom to be taken into account for a while

“Any website should always display the same content for a given URL, regardless any previous state”

― Someone with common sense

I can think of some exceptions, like session or browser preferences, that can make differ the content between users, but It should be true for each single user experience.

This is something important to have in mind when building Single Page Applications.

A common mistake I’ve encountered many times during development is when a page displaying a results view, offers filters to adjust the search. Once the users starts tweaking with those filters the results update but the URL keeps the same inducing a URL-State desynchronization, so if the user tries to reload the page or shares the URL, the web page will not display the filtered results.
This is because the developer has directly updated the app state instead of use a router to keep the URL in sync with it.


Next I’m going to show some examples written using Vue and Vue Router

Warning: all this gists has been written directly from medium, I cannot assure they run without errors but I think that they capture the idea

Bad implementation

Here we can see how the inputs Checkbox and Pagination are updating the data properties directly and then the watchers of them trigger the fetch of new results without updating the URL.

It’s wrong.

Good implementation

On this example we use the navigation guards provided by Vue Router to hook into the cycle of the router so we can get the query params and sync our data with them

Even we could go further with it and get rid of the data properties to only use the params provided by the route so we don’t need to sync anything, like is shown in this last gist

This way the browser will keep track of any changes on the state of the page and the user will have full functionality on Back/Forward actions and a fully shareable URL

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade