How to build your first Electron app

By

Published · Updated

Tagged: DevTools

Create your first Electron desktop app with a main process, isolated renderer, preload bridge, two-way IPC, userData storage, native dialogs, and Electron Forge.

Let’s build a small Electron desktop app that opens a window with an HTML page. We’ll install Electron with npm, create main.js and index.html, then run the app.

This tutorial gives you a first Electron app to run and change.

Electron is free and open source, and lets you build cross-platform desktop apps with JavaScript, HTML and CSS. It was created at GitHub and powers apps including VS Code, Slack and Discord.

A quick look into the Electron internals

Electron is basically bundling the Chromium rendering library and Node.js (Chromium the open source project made by Google, on which they build the Chrome browser).

You have both access to a canvas powered by Chromium, which runs the V8 JavaScript engine, and use any Node.js package, and run your own Node.js code.

It’s a sort of Node.js for the desktop, if you wish. It does not provide any kind of GUI elements, but rather lets you create UIs using HTML, CSS and JavaScript.

Electron aims to be fast, small in size, and as slim as possible, yet providing the core features that all apps can rely upon.

Which kind of apps you can create using Electron

You can create lots of different kind of apps, including:

A good collection of Electron apps is available on the official site: https://www.electronjs.org/apps. With Electron you can create apps and publish them on the Windows and Mac App Store. One of mine is Note Repo, a daily notes app I built with Electron.

Learning Electron by example

The old Electron API Demos app is legacy now. For a current starter, use Electron Forge (npx create-electron-app@latest my-app), follow the Electron docs, or start from Create an app with Electron and React if you want a React renderer. The old quick-start repo is now electron/minimal-repro, a repro template, not a bootstrap.

Electron app demo

Those screenshots still show the shape of a simple Electron window. The docs walk through the same ideas with up-to-date APIs.

Electron app demo

How to create your first Electron app

First, create a new folder on your filesystem and into it run:

npm init -y

to create a package.json file:

{
  "name": "testelectron",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Add this line in the scripts section:

"scripts": {
  "start": "electron ."
}

Now install Electron:

npm install -D electron

Electron can now be started with

npm start

However if you do you will see an error telling you there’s no main.js file, which is what we wrote in the package.json file to be the main starting point of our app:

Error dialog showing Cannot find module index.js and unable to find Electron app

An Hello World Electron GUI app!

Let’s create an application that shows an Hello World in a window.

Create 2 files, main.js:

const { app, BrowserWindow } = require('electron')

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
  })

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  console.log(
    `Node ${process.versions.node}, Chrome ${process.versions.chrome}, Electron ${process.versions.electron}`
  )
  createWindow()
})

and index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>Check the terminal for the Node, Chrome, and Electron versions.</p>
  </body>
</html>

The renderer stays isolated from Node. Leave contextIsolation on (it is the default) and do not enable nodeIntegration in the renderer. Version strings come from the main process (process.versions), printed in the terminal when the app starts.

If you want Node in the same JavaScript context as the page, that’s the NW.js model instead.

Now run again npm start, and this window should show up:

Activity monitor

This is a very simple one-window app, and when you close this window, the application exits.

Expose a narrow API with a preload script

An Electron app splits work across two kinds of processes: the main process (which has Node.js and OS access) and the renderer process (which draws your HTML, CSS, and browser JavaScript). Keep the renderer isolated and connect the two through a preload script using contextBridge.

Attach preload.js when creating the window in main.js:

const path = require('node:path')

const win = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
  },
})

In preload.js, expose one focused method per action instead of passing ipcRenderer straight to the page:

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('notesAPI', {
  loadNotes: () => ipcRenderer.invoke('notes:load'),
  saveNotes: (notes) => ipcRenderer.invoke('notes:save', notes),
  exportNotes: () => ipcRenderer.invoke('notes:export'),
  onNewNote: (callback) => ipcRenderer.on('notes:new', () => callback()),
})

Notice two habits here. First, onNewNote wraps callback so the renderer never receives Electron’s internal event object. Second, only plain, serializable data (strings, numbers, arrays, plain objects) can cross the bridge.

Handle two-way IPC in the main process

Pair ipcRenderer.invoke() in the preload script with ipcMain.handle() in main.js:

const { app, BrowserWindow, ipcMain } = require('electron')

ipcMain.handle('notes:load', async () => {
  return readNotesFromDisk()
})

Register IPC handlers once at the top level of main.js, not inside createWindow(). On macOS, closing a window and clicking the Dock icon runs createWindow() a second time, which throws if the channel already has a handler.

In the renderer, call the exposed bridge with async/await:

const notes = await window.notesAPI.loadNotes()

Avoid ipcRenderer.sendSync(). It blocks the renderer until the main process answers and can freeze the interface.

Store app data in userData

Never save user data next to your source files or inside the application bundle. On macOS (/Applications) and Windows (Program Files), the app directory is often read-only.

Use app.getPath('userData') after app.whenReady() resolves so Electron picks the standard per-user folder for each operating system:

const path = require('node:path')

function notesPath() {
  return path.join(app.getPath('userData'), 'notes-data', 'notes.json')
}

Keep durable files in userData, not in sessionData (which holds Chromium caches and cookies that the OS or user may clear). Also pick a stable productName early, because Electron names the userData folder after it.

Use native dialogs for file exports

When a user exports a file, let the main process open the operating system’s save dialog and write the file. Never let the renderer send an arbitrary filesystem path to the main process.

const { dialog, ipcMain } = require('electron')

ipcMain.handle('notes:export', async () => {
  const result = await dialog.showSaveDialog(mainWindow, {
    defaultPath: 'notes.json',
    filters: [{ name: 'JSON', extensions: ['json'] }],
  })

  if (result.canceled || !result.filePath) {
    return { canceled: true }
  }

  await writeExportFile(result.filePath)
  return { canceled: false }
})

Passing mainWindow attaches the dialog as a modal sheet on macOS. Treat result.canceled as a normal outcome, not an error.

Package and ship with Electron Forge

When you move past a minimal prototype, scaffold your app with Electron Forge (npx create-electron-app@latest my-app). Forge splits shipping into two commands:

npm run package
npm run make

npm run package produces an unpacked app bundle under out/ so you can launch and test it without the dev server running. npm run make wraps that bundle into platform distributables (such as ZIP/DMG on macOS, Squirrel installers on Windows, and DEB/RPM on Linux). Build each platform’s artifact on that operating system, and test installing the final distributable on a clean user account before releasing.

Making app developer’s life easier

Electron aims to make the developer’s life easier. Applications have lots of problems in common. They need to perform things that the native APIs sometimes make a little bit more complicated that one might imagine.

Electron provides an easy way to manage In-App Purchases, Notifications, Drag and Drop, managing key shortcuts and much more.

It also provides a hosted service for app updates, to make updating your apps much simpler than if you had to build such as service yourself.

Want me to talk about your product? You can sponsor this site.

Related posts about devtool: