Local data and native APIs

Choose the data location

Store application data under Electron’s per-user userData directory instead of beside source files or the executable.

Where do the notes go on disk? Not next to the source files, and not next to the executable.

A packaged application often lives in a read-only folder. On macOS it sits inside /Applications. On Windows it’s usually under Program Files. Writing there fails, or needs admin rights. The current working directory is no help either. It changes depending on how the app was launched.

Electron solves this with app.getPath(). You pass the name of a well-known location and get back the right folder for the current operating system. For small configuration and application data, the one we want is userData.

I like to create a dedicated subdirectory inside it, so the notes file never mixes with anything else Electron puts there. Add this helper to src/index.js:

const path = require('node:path')

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

path.join() builds the path with the right separator for each platform. The actual folder is different on macOS, Windows, and Linux. Let Electron pick it. Don’t assemble a home-directory path by hand, because you’ll get at least one of the three platforms wrong.

Two things to keep in mind.

First, call app.getPath() only after Electron is ready. Calling it at the top of the module, before app.whenReady() resolves, is a common mistake.

Second, the default userData folder is named after the application. Change the productName later and your users’ notes appear to vanish, because the app looks in a new folder. Pick a stable name before you ship.

Keep caches somewhere else

Chromium also writes to disk: cookies, local storage, network state, the disk cache. Electron exposes a separate location for those, sessionData. Those files can grow large, and the operating system or the user can clear them without warning. Never store durable notes next to them.

Check the path

Log the path while developing:

console.log(notesPath())

On macOS it prints something like /Users/flavio/Library/Application Support/desktop-notes/desktop-notes-data/notes.json. Open that folder, create a note, and confirm that only your data file appears in the subdirectory. Remove the log before release if paths count as sensitive in your support model.

One last decision: what happens on uninstall? Most operating systems leave userData behind. That preserves notes across a reinstall, which is nice, but it can surprise a user who expected a clean removal. Decide, and document it.

Lesson completed