Scott Antipa scottantipa.com

How to store your app's entire state in the URL  ↦

Scott Antipa:

I’m working on a flowchart editor that runs in the browser, and I wanted a way for people to use it without having to sign in, or store any data on our server. I wanted to give them control over their data and to be able to store it locally to open and edit later. And also easily share it with other people. It’s easy to do this by supporting file upload/download, but I wanted something simpler, like the ability to share by sending a url. I also didn’t want to store anything on the backend (at least for the free tier).

What he decided on was to base64 encode the entire application state and store it in the fragment section of the URL. I love all the upsides of this approach and it’s pretty trivial to accomplish. Here’s the pseudocode that Scott provides in his post:

const stateString = JSON.stringify(appState); // appState is a json object
const compressed = compress(stateString);
const encoded = Base64.encode(compressed);
// Push that `encoded` string to the url
// ... Later, on page load or on undo/redo we read the url and
// do the following
const decoded = Base64.decode(encoded); // same encoded as above, but read from url
const uncompressed = uncompress(decoded);
const newState = JSON.parse(uncompressed);
// Now load your application with the newState

Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00