Learn Electron · 2/12

The Two-Process Architecture Explained

8 min read

Welcome to the core of Electron! Before writing any serious code, you must understand how an Electron application actually runs. Unlike a standard Node.js script or a traditional React website, Electron performs a continuous juggling act between two very different environments.

Understanding this architecture is the single most important step in mastering Electron. Let's break it down progressively.


1. The Main Process: The Backend of Your Frontend

Definition: The Main Process is a single, continuous Node.js environment that serves as the entry point and core controller of your Electron application.

Problem: Standard web browsers (like Google Chrome) intentionally block websites from interacting with your local operating system. A website cannot read your local files, change your system settings, or create a tray icon. If you want to build a powerful desktop app, a standard web page simply does not have the permissions to do desktop-level tasks.

Solution: Electron provides the Main Process. Because it runs in Node.js rather than a browser sandbox, it has full, unrestricted access to the operating system. It bypasses browser restrictions, allowing you to manage files, interact with the OS, and control the application's lifecycle.

Imagine you are running a pizza shop (the server). The Main Process is the manager sitting in the back office. The manager handles the money, pays the rent, and negotiates with the ingredient suppliers (the Operating System). The manager does not cook the pizzas or talk to the customers directly—they just ensure the building stays open and resources are available.

Industry Standard Practice

You will only ever have one Main Process per application. It is strictly used for backend operations: creating windows (BrowserWindow), managing native application menus, handling file dialogs, and processing auto-updates.

javascript
// main.js - The Main Process
const { app, BrowserWindow } = require('electron');
const path = require('node:path');

// Problem: We need a visual window to show our UI to the user.
// Solution: The Main Process creates it using the BrowserWindow module.
const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // We will attach a bridge here later!
      preload: path.join(__dirname, 'preload.js') 
    }
  });

  // The manager tells the window what HTML file to display
  win.loadFile('index.html');
};

// Lifecycle: We wait for the app to be fully ready before opening the doors
app.whenReady().then(() => {
  createWindow();
});

(Interesting Fact: The Main Process runs a special, hidden V8 JavaScript engine instance. If a fatal error occurs in the Main Process, your entire application closes instantly. No error screen, no warnings—just poof! Gone.)


2. The Renderer Process: Your App's User Interface

Definition: The Renderer Process is a Chromium-based web environment responsible exclusively for rendering the User Interface (UI) of your application.

Problem: Node.js (our Main Process) is fantastic at talking to the operating system, but it has absolutely no idea how to draw buttons, text, or CSS animations on a computer screen.

Solution: Electron spins up a Renderer Process for every window you create. It behaves exactly like a Google Chrome tab, parsing HTML, CSS, and JavaScript to display your user interface.

If the Main Process is the manager in the back office, the Renderer Process is the dining area and the waiters. It is where the customers (users) interact. The waiters take orders (button clicks) and present the menu (HTML/CSS).

Industry Standard Practice

Unlike the Main Process, you can have multiple Renderer Processes (one for your main app window, one for a hidden background task window, one for a settings popup). You treat this environment exactly like a standard React, Vue, or Vanilla JS web application.

Crucial Limitation: By default in modern Electron, the Renderer Process is entirely sandboxed. It cannot use require('fs') or talk to Node.js directly. This is an industry-standard security measure to prevent malicious third-party scripts (like a rogue NPM package on your frontend) from deleting a user's hard drive.

html
<!-- index.html - The Renderer Process -->
<!DOCTYPE html>
<html>
  <head>
    <title>My Electron App</title>
  </head>
  <body>
    <h1>Hello Renderer! 👋</h1>
    <button id="save-btn">Save Document</button>
    
    <!-- This is standard web JavaScript, no Node.js allowed here -->
    <script src="./renderer.js"></script>
  </body>
</html>

3. The Bridge: Introduction to Preload Scripts

Definition: A Preload Script is a special JavaScript file that runs in the Renderer Process before the web page starts loading. It uniquely has access to a limited subset of Node.js APIs as well as the HTML DOM.

Problem: The Main Process has the system access, and the Renderer Process has the UI. But they are completely isolated from each other. How does a button click in the UI (Renderer) tell the system to save a file (Main)? If we give the Renderer full Node.js access to do it directly, it becomes a massive security vulnerability.

Solution: The Preload Script acts as a strictly controlled bridge. It uses Electron's contextBridge to expose only specific, safe functions from the Main Process to the Renderer Process.

Going back to the pizza shop: The waiters (Renderer) are not allowed in the manager's office (Main), and the manager does not walk into the dining area. The Preload Script is the small order-passing window between the kitchen and the dining area. Waiters can slide tickets (messages) through this specific window, but they cannot climb through it to access the safe.

Industry Standard Practice

We use contextBridge.exposeInMainWorld to attach strictly defined API methods to the browser's global window object.

(Funny Exaggeration: Exposing the raw ipcRenderer module in your Preload script is like giving a toddler a loaded bazooka. Technically, they can defend the house, but they are far more likely to blow up the television. Always wrap your communications in helper functions!)

javascript
// preload.js - The Bridge
const { contextBridge, ipcRenderer } = require('electron');

// Problem: We need the UI to trigger a save function safely.
// Solution: We expose a specific, limited API to the 'window' object.
contextBridge.exposeInMainWorld('mySecureAPI', {
  // We strictly only allow this specific channel 'save-document'
  saveFile: (fileData) => ipcRenderer.invoke('save-document', fileData)
});

Now, in your standard Frontend code (Renderer), you can safely use the bridge:

javascript
// renderer.js - Frontend Logic
document.getElementById('save-btn').addEventListener('click', async () => {
  // We use the bridge we created! No Node.js required in the UI.
  const response = await window.mySecureAPI.saveFile("Hello World!");
  console.log(response);
});

And the Main process waits in the back office to handle the request:

javascript
// main.js - Backend Logic
const { ipcMain } = require('electron');

// We listen on the 'save-document' channel
ipcMain.handle('save-document', async (event, data) => {
  console.log("Renderer sent:", data);
  // Safely do native OS stuff here, like writing a file to the hard drive
  return "File saved successfully!";
});

4. Understanding Process Lifecycles and App Events

Definition: Process Lifecycles are a series of built-in events emitted by the Electron app module that indicate what state your application is currently in (e.g., starting up, all windows closed, or quitting).

Problem: You need to know exactly when it is safe to interact with the system. If you try to create a graphical window before Electron's internal graphical engine is fully booted, the application will crash instantly. Similarly, you need a way to know when the user is trying to close the app so you can save their settings before the process dies.

Solution: Electron provides specific event listeners (ready, window-all-closed, activate) that let you execute your code at the exact right moment.

Industry Standard Practice

The most frequently used lifecycle events are whenReady(), window-all-closed, and activate (which is essential for macOS behavior).

Here is the standard boilerplate handling lifecycles that you will see in almost every production Electron application:

javascript
// main.js
const { app, BrowserWindow } = require('electron');

// 1. 'ready' - The most important event. 
// Electron has finished initializing and can safely create browser windows.
app.whenReady().then(() => {
  createWindow();

  // 2. 'activate' - macOS specific standard.
  // On macOS, it's common to re-create a window in the app when the 
  // dock icon is clicked and there are no other windows currently open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// 3. 'window-all-closed' - User closed all windows.
// Problem: On Windows and Linux, closing all windows should quit the app.
// Solution: Listen for this event and manually call app.quit().
app.on('window-all-closed', () => {
  // 'darwin' is the underlying OS kernel name for macOS.
  // On macOS, apps usually stay active until the user quits explicitly with Cmd + Q.
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

(Under the hood: When app.quit() is called, Electron doesn't just pull the power plug. It emits a before-quit event, cleanly closes all active renderer windows, emits a will-quit event, and finally terminates the Node.js process. This gives your code ample time to save user preferences before the lights go out.)


Further Reading & References

Challenge

Challenge: Secure Inter-Process Communication Setup

Your task is to correctly implement the foundational code for an Electron application, demonstrating a secure communication channel between the Main and Renderer processes using a Preload script. You will need to write the code for three separate logical components (main.js, preload.js, and renderer.js) within the single editor window provided.

Requirements:

  1. In the main.js section:

    • Import all necessary modules: app, BrowserWindow, ipcMain, and path from electron.
    • In the createWindow function, instantiate a new BrowserWindow.
    • Configure the webPreferences for this window to securely load the preload.js script. Remember to use path.join(__dirname, 'preload.js') for the path and ensure contextIsolation is enabled.
    • Set up a handler using ipcMain to listen for the channel 'get-app-version'. This handler should be an async function that returns the application's version via app.getVersion().
    • Use the app.whenReady() promise to call your createWindow function.
  2. In the preload.js section:

    • Import contextBridge and ipcRenderer from electron.
    • Use the contextBridge to expose a new API object on window.electronAPI.
    • This API object must contain a single method: getVersion(). This method should use ipcRenderer.invoke() to call the 'get-app-version' channel you defined in the main process.
  3. In the renderer.js section:

    • Implement the displayAppVersion asynchronous function.
    • Inside this function, call the getVersion() method you exposed from the preload script.
    • Take the returned version string and set it as the innerText of a hypothetical HTML element with the ID version-display.

Expected result

Your final code should correctly implement all three sections. The solution will be evaluated based on the following criteria:

main.js

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

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

app.whenReady().then(createWindow);

ipcMain.handle('get-app-version', async () => {
  return app.getVersion();
});
  • Imports: app, BrowserWindow, ipcMain, and path are correctly imported.
  • webPreferences: The preload key is set to path.join(__dirname, 'preload.js') and contextIsolation is true.
  • Lifecycle: app.whenReady().then() is used to call createWindow.
  • IPC Handler: ipcMain.handle is used for the 'get-app-version' channel, and its callback returns app.getVersion().

preload.js

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

contextBridge.exposeInMainWorld('electronAPI', {
  getVersion: () => ipcRenderer.invoke('get-app-version')
});
  • Imports: contextBridge and ipcRenderer are correctly imported.
  • contextBridge: exposeInMainWorld is called with the key 'electronAPI'.
  • Exposed Method: The exposed object contains a getVersion method which correctly calls ipcRenderer.invoke('get-app-version').

renderer.js

javascript
const displayAppVersion = async () => {
  const version = await window.electronAPI.getVersion();
  const versionElement = document.getElementById('version-display');
  if (versionElement) {
      versionElement.innerText = version;
  }
};

displayAppVersion();
  • Asynchronous Call: The function correctly uses async and await.
  • API Usage: It calls window.electronAPI.getVersion() to retrieve the version string.
  • DOM Manipulation: It correctly attempts to find an element by its ID and set its innerText to the retrieved version.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.