GUN — Decentralized database. Five things I wish I had known

Gustav Corpas
4 min readNov 6, 2023

I have been getting into developing applications with gun. It is a really cool decentralized, streaming database. It’s super fun to play around with. For a big project it does require a lot of extra work to get working properly. But all in all, I would recommend trying it out!

If you do start out fiddling with gun beyond the small example code, this article contains what I wish someone would have told me before I got started! So here you go : )

Watch values. Dont read too much.

Gun is a streaming database. It streams in data. You will want to work with this, not against it. Don’t rely too much on reading off values from gun, then doing a bunch of stuff without gun, and trying to put the values back into it…. Maybe better with an example:

// Dont do this
let info = {name: "loading..."};
gun.get("info").get("name").once(name => info.name = name);

// And then later...
info.name = "updated name";

// And then even later...
gun.get("info").get("name").put(info.name);

This might work fine when name is just a single value being read. But weird things will start to happen once you begin building up objects from these values, or passing info around thinking it has some value that you’ve read at a particular point in time, setting values of name in the client code, but also having gun potentially update the value suddenly. This is not the streaming mindset.

Instead subscribe to the name value. If you want to change the value, put the value into gun, and let the value get back to you through your subscription. I am using writable here, which is a svelte.js thing. But it is just something that allow for setting a value, and letting subscribers know about the changes.

const name_store = writable("loading...");
gun.get("info").get("name").once(name => name.store.set(name));

// And then later
name_store.subscribe(name => {
// will be called with "loading..."
// and then again with "updated name".
});

gun.get("info").get("name").put("updated name");

This will be annoying at times, but it will force you into the streaming mindset which will safe you a lot of time in the long run!

// if you really want to…

--

--

Gustav Corpas

I write about technology and society. Or anything that is interesting to me.