How to embed a database in your electron app

If your electron app state is beyond what localStorage can manage, you need to bundle a database. NEDB is a mongo API compatible, file-based database. It’s a great fit for electron apps.

Shivek Khurana
3 min readOct 30, 2018

In this post, I’ll walk through my NEDB setup. It’s fairly simple and is being used in production at HTTPSLocalhost app.

Install nedb-promises

nedb-promises is a wrapper around NEDB. I suggest using this over Nedb directly. Sooner or later, you’d need to wait for your data to arrive.

$ yarn add nedb-promises

Create a database factory

You can choose to have just one database file for your entire app, or you can choose to have one file per domain entity. But the location of those files can cause a problem after you have packaged the app.

Electron provides a getAppPath helper. We use userData to store the database files in a packaged app, and ./data/ in development.

If you are using my Glutten free react electron structure, create a file named db.js in main/src folder. If not, place this file where you see fit. It will be used to load data entities.

// main/src/db.js
const {app} = require('electron');
const Datastore = require('nedb-promises');
const dbFactory = (fileName) => Datastore.create({
filename: `${process.env.NODE_ENV === 'dev' ? '.' : app.getAppPath('userData')}/data/${fileName}`,
timestampData: true,
autoload: true
});

I also pass some nifty defaults like autoload and auto timestamping.

Setup environment

Now we need to inform electron about our environment. We can do so by modifying package.json.

"scripts": {
"start": "NODE_ENV=dev electron src",
"build": "NODE_ENV=prod electron-builder",
},

I usestart command in my development env and build to create the package. If you use different commands, adjust accordingly.

Setup domains objects

Suppose you need to persist two domain objects: posts and tags. In this example, I’m gonna persist posts in posts.db file and tags in tags.db file. (You can use a single file.)

We do so by extending the db.js module we created earlier.

// db.js
// requires
// const dbFactory = ...
const db = {
tags: dbFactory('tags.db'),
posts: dbFactory('posts.db')
};
module.exports = db;

Query records

Now your domain objects are accessible as db.tags and db.posts. Follow the NEDB API as usual.

const db = require('db')const createTag = async (label) => {      
const tag = await db.tags.insert({label})
return tag
}
const getTags = async () => {
const proxies = await db.tags.find({})
return {proxies}
}

The above concept was used to create HTTPSLocalhost — The fastest way to get https working locally. Thanks for reading :)

Hi, if you liked this article and want to stay updated, follow me on: Medium, Github or Twitter

You might also like:

--

--

Shivek Khurana

🏋🏻‍♂️ Founder — Building Meta Blocks — The NFT evolution protocol | 🔫 Talks about 📜 code, 🏛 crypto, 🕸 web3 and 🪖 ed-tech | 👼🏼 Angel Investor | W