🎄Add state to your static website - save state in the url🌟

Dec 16 2023

Back to 2023 Advent Calendar

As we mentioned before in Advent Calendar, we are big fans of static websites. They are fast, secure, and cheap to host. However, they have one big disadvantage - they are static. You can't have any state in them.

But what if you want to share some state with your users? For example, one user might create MermaidJS diagram and share with others.

With static websites you have two options:

  • use backends as a service like firebase/supabase etc to store state
  • use URL to store state

What are the requirements?

  1. It should be as short as possible
  2. it should be fast to encode and decode, so it doesn't slow down the website.
  3. (optional) some users might want to make sure our servers don't receive this state.

What are the options?

  1. Query parameters (part of URL after ? sign)
  2. Hash (part of URL after # sign)

While both are valid options and will look almost the same in the browser, the Hash is better because it is not sent to the server.

How to encode state into the URL?

There are many ways to encode state into the URL. One would be just JSON encode it and put it into the URL. But that would be too long. There are fast compression libraries like lz-string which is what we use on this website.

The code could look like this

import lz from 'lz-string'
const state = { a: 1, b: 2 }
const encoded = lz.compressToEncodedURIComponent(JSON.stringify(state))
window.location.hash = encoded;
// or history.pushState({}, '', `#${encoded}`)