How to use your URL as a shareable JSON database.

Wish you had a way to share data with your friends in a frontend-only project?

Turns out you can! You can place your data inside your URIs and then copy/paste them to your friends. It's that simple.

This project is a quick proof of concept whipped up in 30 minutes to show you how to do it.

Instructions

  1. Type data in the text box below.
  2. Click "Save".
  3. Copy + paste the URL to your friends.
  4. Your friends receive the same data that you saved earlier.

This project was built in a single file (plus a CSS stylesheet). You can check it out in your debug console.

You can also view the source code on Github

How to build your own

The recipe is super simple.

Function to save the data to the URL

In order to save data, all you have to do is use the following data. Your data will be saved to your URL, and you can copy/paste it to your friends.

          function save(json={}) {
            // step 1, serialize the JSON to a string.
            const dataToSave = JSON.stringify(json); // stringify the json
            const base64 = btoa(dataToSave);         // base64 encode the data, for aesthetic purposes
            const hash = encodeURIComponent(base64); // encode the string as a URI component

            // step 2, add the string to a param called 'data-hash'
            const urlParams = new URLSearchParams(window.location.search);
            urlParams.set("data-hash", hash);
            window.location.search = urlParams;
          }
        

Function to load the data from the URL

Loading the data back is even easier. You just read the URL params and decode the data.

          function load() {
            // get the data from the hash
            const urlParams = new URLSearchParams(window.location.search);
            const hash = urlParams.get("data-hash");

            // if there is no data, return empty object.
            if (!hash) {
              return {};
            }
            
            // else decode and return the object
            const jsonString = atob(decodeURIComponent(hash));
            return JSON.parse(jsonString);
          }
        

About the author

Monarch Wadia is a senior developer, software "architect", and the CEO & CTO at Mintbean.io. There, he builds hackathons which help developers sharpen their skills. He enjoys coding immensely.

You can connect with Monarch on LinkedIn or Twitter