Skip to content

Instantly share code, notes, and snippets.

@scottcorgan
Last active July 9, 2018 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottcorgan/1ebaf94dd913cfad49af5aaa52814a3e to your computer and use it in GitHub Desktop.
Save scottcorgan/1ebaf94dd913cfad49af5aaa52814a3e to your computer and use it in GitHub Desktop.

Storing Your App's State in the URL

I'm not the first person to think of this, but I thought I'd explore this really quickly. Is this a good idea? Probably not, but it is interesting as far as local and remote debuggability are concerned.

Normally, an app would need some special code to get 2 things we get for free when you store our app's state in the URL

  1. Time travel debugging (state history)
  2. Remote debugging (recreating a bad state from another user's data)

Let's take the following code as a rudimentary example of how to do this (here's a link to the working code http://jsbin.com/wituha/4/edit?js,output):

const state = {
  name: "Scott",
  age: 35,
  friends: [
    { id: 1, createdAt: "some time" },
    { id: 2, createdAt: "some time" }
  ]
};

const encoded = btoa(JSON.stringify(state));
const decoded = atob(encoded);

document.getElementById("app").innerHTML = `
<strong>Encoded:</strong> ${encoded}<br><br>

<strong>Decoded:</strong>
<pre>
${decoded}</pre>
`;

Here's how this is a helpful:

You have a state tree that gets base64 encoded. You can then store that in the url (using pushState or hashed based routing). Your app can then decode that as a way to know what the current state should be.

Now you can:

  • You can then store this in local storage to restore state to your app at some time
  • The browser is now storing your state tree, so you don't have to.
  • Get the URL from a user that has encountered a bug and go immediately to that state
    • The url/state immediately transferrable between sessions and computers.

Pitfalls

  • This is performant. It can get really slow with large state trees
  • It's weird. It's not immediately apparent where in the app you are by looking at the url (Not a vanity url).
  • People don't like change, so they'll get mad.
@bennadel
Copy link

bennadel commented Jul 9, 2018

People don't like change, so they'll get mad.

Ha ha ha ha :D

@monty5811
Copy link

Data privacy is also an issue I think?
You wouldn't want someone to unwittingly share an URL with addresses, phone numbers, etc in it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment