Inter-Process Communication (IPC) Mastery
8 min read
Before we start wiring up buttons and reading local files, we need to understand the fundamental architecture of Electron. Electron applications are split into two completely separate worlds:
- The Main Process: This is the backend of your desktop app. It runs in a Node.js environment, controls the application lifecycle, manages windows, and has full access to the operating system (file system, databases, native menus).
- The Renderer Process: This is the frontend. It runs in a Chromium browser environment. It is responsible for drawing your UI using HTML, CSS, and JavaScript (or React/Vue/Angular).
The Problem: Because these two processes run in entirely different environments, they are isolated. Your frontend UI cannot simply use fs.readFileSync() to read a file from the user's computer—it lacks the permissions. Conversely, the Main process cannot directly manipulate the DOM to show a popup on the screen.
The Solution: Inter-Process Communication (IPC). IPC is the bridge that allows these two isolated environments to securely pass messages and data back and forth.
Let's master how to build and secure these bridges.
1. ipcMain and ipcRenderer: The Communication Channels 📡
Definition
ipcMain: An Event Emitter module utilized strictly in the Main process to handle and reply to messages.ipcRenderer: An Event Emitter module utilized strictly in the Renderer process (specifically inside preload scripts) to dispatch messages.
The Problem
Without a standardized way to talk, the Chromium browser engine and the Node.js backend are like two people speaking different languages in soundproof rooms. If a user clicks a "Minimize Window" button in the UI, the UI has absolutely no way to tell the operating system to minimize the window.
The Solution
Electron provides ipcMain and ipcRenderer to act as dedicated communication lines. Under the hood, they use a Unix-like message-passing system and the HTML Standard Structured Clone Algorithm to serialize and deserialize JavaScript objects.
Imagine you are working in a highly secure bank. The bank teller (Renderer Process) sits behind bulletproof glass and talks to the vault manager (Main Process) via a secure telephone line. ipcRenderer is the teller's microphone, and ipcMain is the vault manager's receiver. They can only pass words (serialized data), not physical objects.
How it Works
Both modules operate using channels. A channel is simply a developer-defined string (e.g., 'update-user-settings' or 'window-minimize') that both sides agree upon to listen to and broadcast on.
2. One-Way Messaging: Sending Fire-and-Forget Data ✉️
Definition
One-way messaging is a communication pattern where a sender transmits data to a receiver through a specific channel and immediately moves on, expecting no response or confirmation.
The Problem
Sometimes the UI just needs to notify the backend that an event occurred without caring about the result. For example, logging a frontend error to the terminal, triggering a native window resize, or updating the native window title. Waiting for a response would unnecessarily block resources.
The Solution
We use the ipcRenderer.send() method to dispatch the message, and the ipcMain.on() method to listen for it.
Code Example: Changing the Window Title
Here is how you handle a fire-and-forget message from the UI to the Main process:
Main Process (main.js):
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('node:path');
app.whenReady().then(() => {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});
// Listen on the 'set-title' channel
ipcMain.on('set-title', (event, newTitle) => {
// We can find out exactly which window sent this message
const webContents = event.sender;
const win = BrowserWindow.fromWebContents(webContents);
// Perform the native action
win.setTitle(newTitle);
console.log(`Window title changed to: ${newTitle}`);
});
mainWindow.loadFile('index.html');
});Preload Script (preload.js):
(Note: We will explain exactly why we use a preload script in Subtopic 4, but for now, know that this is the safe middle-ground where ipcRenderer lives).
const { ipcRenderer } = require('electron');
// Dispatch the message with data
ipcRenderer.send('set-title', 'My Awesome Electron App');Industry Insight: You will frequently use one-way messaging for tracking analytics, updating system tray icons based on UI state, or logging.
3. Two-Way Communication: The invoke and handle Pattern 🔄
Definition
Two-way communication is an asynchronous request-response pattern. The sender dispatches a message requesting an action, and then waits asynchronously for a computed reply from the receiver.
The Problem
If your UI needs to query a local SQLite database or open a native file dialog to select an image, it must get the result back to display it.
Historically, developers had to use ipcRenderer.send() to ask for data, and then set up a separate ipcRenderer.on() listener to catch the reply. This caused spaghetti code, race conditions, and massive headaches if multiple requests were sent at the same time. (There was also ipcRenderer.sendSync(), which completely froze the entire application UI until it finished—a terrible user experience).
The Solution
Electron 7 introduced the modern, industry-standard approach: ipcRenderer.invoke() and ipcMain.handle().
When the Renderer calls invoke(), it returns a Promise. The Main process catches this with handle(), does the heavy lifting, and whatever it returns is passed right back to resolve the Renderer's Promise.
Imagine you ask a chef for a pizza (invoke). You stand at the counter waiting (awaiting the Promise). The chef bakes it (handle), and hands it directly back to you. No extra steps, no confusion.
Code Example: Opening a Native File Dialog
Main Process (main.js):
const { ipcMain, dialog } = require('electron');
// Handle the 'dialog:openFile' channel
ipcMain.handle('dialog:openFile', async () => {
// Use Electron's native dialog module
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ['openFile']
});
// Return the data back to the invoker
if (!canceled) {
return filePaths[0]; // Returns the string path of the file
}
return null;
});Renderer Process / Preload:
const { ipcRenderer } = require('electron');
async function getSelectedFilePath() {
// We wait for the Main process to finish and give us the result
const path = await ipcRenderer.invoke('dialog:openFile');
console.log('User selected:', path);
}Fun Fact: invoke/handle is so vastly superior to older IPC methods that if you try to use the old sendSync method in a modern code review, your senior engineers might actually start weeping. Always use invoke/handle for returning data!
4. Exposing Safe APIs via contextBridge 🌉
Definition
contextBridge is a utility module that safely exposes specific, isolated APIs from a preload script to the main web environment.
The Problem
If ipcRenderer is so powerful, why don't we just import it directly into our React components or our HTML's <script> tags?
Because of Security. If you attach ipcRenderer directly to the global window object in your Renderer process, any third-party script running on your page (like a hacked NPM analytics package, or a malicious ad) can access it. That script could execute a command like ipcRenderer.invoke('delete-system-files') and your Main process would blindly execute it.
The Solution
Modern Electron enables Context Isolation by default. This forces your UI code and your Node.js/Electron API code to run in completely separate JavaScript contexts. They cannot touch each other's global variables.
To connect them safely, we use a Preload script and contextBridge.exposeInMainWorld(). This allows us to define a strict, immutable dictionary of functions. We don't hand the UI the entire ipcRenderer module; we only give it specific functions it is allowed to call.
Imagine the difference between handing a stranger the keys to your entire house (nodeIntegration: true), versus installing a specific mail slot where they can only drop off letters (contextBridge).
Tying It All Together: The Ultimate Modern Boilerplate
Here is the exact setup used in industry to wire up IPC safely.
1. The Preload Script (preload.js):
const { contextBridge, ipcRenderer } = require('electron');
// We are exposing an object named "electronAPI" to the global window
contextBridge.exposeInMainWorld('electronAPI', {
// One-way API
setTitle: (title) => ipcRenderer.send('set-title', title),
// Two-way API
openFile: () => ipcRenderer.invoke('dialog:openFile')
});2. The Renderer Process (renderer.js):
(This is your standard frontend code, linked in your HTML)
const btnChangeTitle = document.getElementById('btn-title');
const btnOpenFile = document.getElementById('btn-file');
const filePathDisplay = document.getElementById('file-path');
btnChangeTitle.addEventListener('click', () => {
// Safely using the specific function we exposed
window.electronAPI.setTitle('New Secure Title!');
});
btnOpenFile.addEventListener('click', async () => {
// Safely requesting data
const filePath = await window.electronAPI.openFile();
if (filePath) {
filePathDisplay.innerText = filePath;
}
});Notice what we achieved here: The frontend (renderer.js) has absolutely no idea what ipcRenderer is. It only knows that window.electronAPI exists. Even if a malicious script tries to modify window.electronAPI.openFile, contextBridge freezes the object so its definitions cannot be tampered with.
Summary
- Use
ipcMainin the backend andipcRendererin the frontend's preload script. - Use
sendandonfor fire-and-forget one-way data. - Use
invokeandhandlefor reliable two-way data requests. - Always use
contextBridgein your preload scripts to maintain context isolation and protect your users' machines.
References & Further Reading
Challenge
You are building an Electron application and need to securely fetch data from the Main process to display in the Renderer process. Your task is to implement a complete, two-way Inter-Process Communication (IPC) channel from scratch within the provided code structure.
Your Task:
In the Main Process (
main.jssection):- Create a handler for a channel named
"get-system-info". - This handler must be asynchronous and should return a simple object:
{ platform: 'exampleOS', version: '10.0' }. - Use the appropriate
ipcMainmethod designed for handling invocations that expect a response.
- Create a handler for a channel named
In the Preload Script (
preload.jssection):- Securely expose an API to the Renderer process using
contextBridge. - The exposed global object on
windowshould be namedbridge. - This
bridgeobject must contain a single asynchronous method namedgetSystemInfo. - The
getSystemInfomethod should use the correctipcRenderermethod to call the"get-system-info"channel and return the result.
- Securely expose an API to the Renderer process using
In the Renderer Process (
renderer.jssection):- Write the line of code that would call the exposed
getSystemInfofunction and assign its returned promise to a constant namedsystemInfoPromise. Do not useawaitor.then(); just demonstrate the function call.
- Write the line of code that would call the exposed
Expected result
Your code should correctly establish a secure IPC channel for request-response communication.
// Assume the necessary Electron modules are available.
const { ipcMain, contextBridge, ipcRenderer } = require('electron');
// --- main.js ---
ipcMain.handle('get-system-info', async (event) => {
const info = { platform: 'exampleOS', version: '10.0' };
return info;
});
// --- preload.js ---
contextBridge.exposeInMainWorld('bridge', {
getSystemInfo: () => ipcRenderer.invoke('get-system-info')
});
// --- renderer.js ---
const systemInfoPromise = window.bridge.getSystemInfo();Explanation:
- Main Process:
ipcMain.handle()is the correct method for two-way, asynchronous communication. It listens for aninvokecall and its return value is automatically sent back to the renderer as a resolved Promise. - Preload Script:
contextBridge.exposeInMainWorld()is used to securely expose thegetSystemInfofunction to the renderer. This function wrapsipcRenderer.invoke('get-system-info'), which sends the request to the main process and returns the promise that resolves with the data from thehandlecallback. - Renderer Process: The exposed function is accessed via
window.bridge.getSystemInfo(). Calling it initiates the IPC request and returns a Promise that will resolve with the system info object.