Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 36 ยท Main and Renderer Processes

The Electron Main Process and Node.js

Learn what the Electron main process does, which Node.js and Electron modules it can use, why it must never block, and how to keep it small, responsive and safe.

The main process is the heart of an Electron app. It is the Node.js process that your package.json main field points to. There is exactly one, it starts first, and it lives until the app quits. It owns everything that is not drawn inside a web page: creating windows, showing menus and dialogs, talking to the operating system, managing files and processes, and deciding when the app exits.

Think of it as the back end of your desktop app, running on the user's machine. Understanding what belongs here (and what does not) is the single most useful architectural skill in Electron.

What the main process can do

Because it is plain Node.js with Electron's native modules added, the main process has full access to the computer:

  • All Node.js built-in modules: fs, path, os, child_process, net, http, crypto, worker_threads and more.
  • Any npm package you install.
  • Electron modules that only exist here or are most useful here: app, BrowserWindow, Menu, Tray, dialog, ipcMain, Notification, globalShortcut, screen, shell, session, protocol, autoUpdater and others.

It has no DOM. There is no document or window in the main process; those belong to renderers. Trying to use them throws a ReferenceError.

JavaScript
// main.js
const { app, BrowserWindow, dialog } = require('electron')
const fs = require('node:fs/promises')
const os = require('node:os')

app.whenReady().then(async () => {
  console.log('Running on', os.platform(), os.release())        // Node.js API
  const userData = app.getPath('userData')                       // Electron API
  await fs.mkdir(userData, { recursive: true })

  const win = new BrowserWindow({ width: 800, height: 600 })
  win.loadFile('index.html')

  const { response } = await dialog.showMessageBox(win, {        // native dialog
    message: 'Welcome!',
    buttons: ['OK'],
  })
  console.log('button index', response)
})

Where does console.log go? In the terminal you used to launch the app, not in DevTools. That is how you know you are looking at main-process output.

What does NOT belong here

The flip side of "full power" is that the main process is shared by every window. Two rules follow:

  1. Never block it. The main process handles window events, menu clicks, IPC and the native UI. A long synchronous loop or a big fs.readFileSync freezes every window of your app at once, because they all wait for the same event loop.
  2. Do not put UI logic here. Anything about layout, forms or rendering belongs in the renderer.

Use the asynchronous APIs (fs.promises, fetch, streams), push CPU-heavy work into a worker_threads Worker or an Electron utility process, and keep handlers short.

Seeing a blocked event loop

You can feel the difference between blocking and non-blocking code. The stand-in below runs a timer every 20 ms, representing "the app staying responsive". Watch how a synchronous loop starves it and a chunked loop does not.

Node.js Blocking versus yielding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a real app the "ticks" are mouse clicks, menu events and IPC messages. A frozen main process means a window that stops responding.

Organizing main-process code

A main.js that does everything becomes unmanageable quickly. Split it into modules with one job each:

TEXT
src/main/
  main.js          # entry: lifecycle only
  windows.js       # createMainWindow(), createSettingsWindow()
  menu.js          # builds the application menu
  ipc-handlers.js  # registers ipcMain.handle(...) functions
  store.js         # reads and writes settings on disk
JavaScript
// main.js
const { app } = require('electron')
const { createMainWindow } = require('./windows')
const { registerIpcHandlers } = require('./ipc-handlers')
const { buildMenu } = require('./menu')

app.whenReady().then(() => {
  registerIpcHandlers()
  buildMenu()
  createMainWindow()
})

Keep each module testable by passing dependencies in (for example give registerIpcHandlers the object that holds settings) instead of reaching for global state.

Handling errors in the main process

An uncaught exception in the main process shows a native error dialog and can crash the app. Add logging and a controlled response:

JavaScript
process.on('uncaughtException', (error) => {
  console.error('Unhandled error in main:', error)
  // log to a file, then decide whether to continue or quit
})

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled promise rejection:', reason)
})

Wrap IPC handlers in try/catch so a failing request returns a useful error to the renderer instead of leaving it waiting.

A model of the main process as a service

A neat way to think about it: the main process exposes a small set of capabilities (read this file, show that dialog) to the renderers, which ask for them. The stand-in below models a tiny capability registry. Only registered names can be called, and each call is async and validated, the same shape you will meet with real IPC handlers.

Node.js Stand-in: a capability registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Unknown capabilities are refused, and input is checked before use. This "allow-list" thinking is the foundation of the IPC chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does console.log output from main.js appear?

    The main process is a Node.js process, so its console output goes to the launching terminal, not to DevTools.
  2. 2. Why is a long synchronous loop in the main process harmful?

    The main process handles events for all windows; blocking it makes the entire app unresponsive.
  3. 3. Which of these does the main process NOT have?

    The DOM belongs to renderer processes; the main process is plain Node.js with Electron modules.
  4. 4. How should you handle CPU-heavy work started from the main process?

    Worker threads or utility processes keep the main event loop free to serve windows and IPC.

Summary

  • The main process is a single Node.js process with full OS access and Electron's native modules.
  • It has no DOM; its console output appears in the launching terminal.
  • Never block it: use async APIs, workers or utility processes.
  • Split it into small modules (windows, menu, IPC handlers, storage).
  • Treat it as a service that exposes a small, validated set of capabilities.

Next: The Renderer Process and Web APIs