# How to Implement IPC Communication Between Main and Renderer Processes Using `ipcMain.handle` in Electron

> Learn to implement IPC communication between Electron main and renderer processes using ipcMain.handle and ipcRenderer.invoke. Build secure Promise-based request-response channels.

- Repository: [Electron/electron](https://github.com/electron/electron)
- Tags: how-to-guide
- Published: 2026-02-25

---

**Use `ipcMain.handle()` in the main process to register async handlers and `ipcRenderer.invoke()` in the renderer process to call them, enabling secure Promise-based request-response communication across Electron's process boundary.**

Electron's architecture isolates the Node.js-powered **main process** from sandboxed **renderer processes** running Chromium. To bridge this gap securely, the `electron/electron` repository provides an **invoke-style IPC** API centered on `ipcMain.handle()` and `ipcRenderer.invoke()`. This pattern lets renderer processes request data or trigger actions in the main process while maintaining strict context isolation and avoiding direct Node.js exposure.

## Architecture of `ipcMain.handle` in the Electron Source

Under the hood, Electron implements this pattern through the `IpcMainImpl` class defined in [`lib/browser/ipc-main-impl.ts`](https://github.com/electron/electron/blob/main/lib/browser/ipc-main-impl.ts). When you call `ipcMain.handle(channel, listener)`, the framework:

1. Validates that the channel is not already registered in the internal `_invokeHandlers` Map.
2. Stores the listener function in the map keyed by the channel name.
3. Returns `undefined` upon successful registration.

When a renderer subsequently calls `ipcRenderer.invoke(channel, ...args)`, the IPC dispatcher looks up the channel in `_invokeHandlers`. According to the implementation in [`lib/browser/ipc-main-impl.ts`](https://github.com/electron/electron/blob/main/lib/browser/ipc-main-impl.ts):

- If the listener returns a **Promise**, the dispatcher awaits it and serializes the resolved value back to the renderer.
- If it returns a plain value, that value is sent immediately.
- Errors thrown inside the listener are caught, and their `message` property is serialized to reject the renderer's Promise.

This implementation is exposed to applications through the singleton `ipcMain` instance exported from [`lib/browser/api/ipc-main.ts`](https://github.com/electron/electron/blob/main/lib/browser/api/ipc-main.ts).

## Implementing Secure IPC with `ipcMain.handle`

Production-ready Electron applications use **context isolation** and a **preload script** to safely expose IPC capabilities. Below is the complete implementation pattern.

### Main Process: Registering Handlers

In your main process entry point (typically [`main.ts`](https://github.com/electron/electron/blob/main/main.ts)), import `ipcMain` from `electron` and register channels using `handle()`:

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

async function openFileDialog() {
  const { canceled, filePaths } = await dialog.showOpenDialog({});
  if (!canceled) return filePaths[0];
}

function createWindow() {
  const win = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
    },
  });
  win.loadFile('index.html');
}

app.whenReady().then(() => {
  // Register the invokable channel as implemented in ipc-main-impl.ts
  ipcMain.handle('dialog:openFile', openFileDialog);
  createWindow();
});

```

The `ipcMain.handle()` method corresponds directly to the handler registration logic in [`lib/browser/ipc-main-impl.ts`](https://github.com/electron/electron/blob/main/lib/browser/ipc-main-impl.ts), where your `openFileDialog` function is stored in the private `_invokeHandlers` map.

### Preload Script: Exposing the API via `contextBridge`

Create a preload script to safely expose only the necessary IPC methods to the renderer:

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

contextBridge.exposeInMainWorld('electronAPI', {
  openFile: () => ipcRenderer.invoke('dialog:openFile'),
});

```

This pattern ensures the renderer cannot directly access `ipcRenderer` or Node.js modules, adhering to the security recommendations documented in [`docs/tutorial/ipc.md`](https://github.com/electron/electron/blob/main/docs/tutorial/ipc.md).

### Renderer Process: Invoking the Handler

In your frontend code, call the exposed API using `await`:

```javascript
const btn = document.getElementById('btn');
const output = document.getElementById('filePath');

btn.addEventListener('click', async () => {
  try {
    const filePath = await window.electronAPI.openFile();
    output.textContent = filePath ?? 'No file selected';
  } catch (err) {
    console.error('IPC error:', err.message);
  }
});

```

The `window.electronAPI.openFile()` call triggers `ipcRenderer.invoke()`, which sends a message to the main process. The Promise resolves with the return value from your `ipcMain.handle()` listener, or rejects if the main process throws an error.

## Advanced Handler Patterns

### One-Time Handlers with `handleOnce()`

For scenarios requiring single-use handlers (such as initialization or license validation), use `ipcMain.handleOnce()`. This method registers a handler that is automatically removed from `_invokeHandlers` after the first invocation:

```javascript
ipcMain.handleOnce('license:validate', async (event, key) => {
  const result = await validateLicenseKey(key);
  return result;
});

```

After the first renderer calls `ipcRenderer.invoke('license:validate')`, the handler is deleted from the internal map and subsequent calls will reject with a "No handler registered" error.

### Removing Handlers Dynamically

To unregister a channel manually (for example, when cleaning up resources), use `ipcMain.removeHandler()`:

```javascript
ipcMain.removeHandler('dialog:openFile');

```

This deletes the channel entry from the `_invokeHandlers` map in `IpcMainImpl`, preventing further invocations until a new handler is registered.

## Key Source Files in `electron/electron`

Understanding these implementation files helps debug complex IPC issues:

- **[`lib/browser/api/ipc-main.ts`](https://github.com/electron/electron/blob/main/lib/browser/api/ipc-main.ts)** – Exports the singleton `ipcMain` object used by applications.
- **[`lib/browser/ipc-main-impl.ts`](https://github.com/electron/electron/blob/main/lib/browser/ipc-main-impl.ts)** – Contains the `IpcMainImpl` class with the `_invokeHandlers` map and the logic for `handle()`, `handleOnce()`, and `removeHandler()`.
- **[`docs/api/ipc-main.md`](https://github.com/electron/electron/blob/main/docs/api/ipc-main.md)** – Formal API documentation detailing error propagation and method signatures.
- **[`docs/tutorial/ipc.md`](https://github.com/electron/electron/blob/main/docs/tutorial/ipc.md)** – Step-by-step tutorial covering secure IPC patterns.

## Summary

- **`ipcMain.handle()`** registers async request handlers in the main process, storing them in an internal `_invokeHandlers` map.
- **`ipcRenderer.invoke()`** calls these handlers from the renderer, returning a Promise that resolves with the handler's return value.
- **Error propagation** automatically serializes thrown error messages to reject the renderer's Promise.
- **Security requires** using `contextBridge` in a preload script to expose only specific IPC methods, preventing direct Node.js access.
- **`handleOnce()`** provides single-use handlers that auto-remove after first invocation, while **`removeHandler()`** allows manual cleanup.

## Frequently Asked Questions

### How does `ipcMain.handle()` differ from `ipcMain.on()`?

**`ipcMain.handle()`** is designed for request-response patterns using Promises, while **`ipcMain.on()`** is for one-way event listening. When you use `handle()`, the renderer calls `ipcRenderer.invoke()` and receives a Promise that resolves with your handler's return value. With `on()`, the renderer uses `ipcRenderer.send()` and must listen for a separate response via `ipcRenderer.on()`, requiring manual correlation of request-response pairs.

### Can I pass complex objects or binary data through `ipcMain.handle()`?

Yes, Electron uses the **Structured Clone Algorithm** to serialize arguments and return values. This supports most JavaScript types including objects, arrays, Maps, Sets, and ArrayBuffers, but excludes functions and DOM nodes. For very large binary data, consider using Node.js streams or the `contextBridge` `postMessage` API instead of IPC invoke.

### What happens if I register two handlers for the same channel?

The `IpcMainImpl` validation in [`lib/browser/ipc-main-impl.ts`](https://github.com/electron/electron/blob/main/lib/browser/ipc-main-impl.ts) throws an error when you attempt to register a handler for a channel that already exists in `_invokeHandlers`. You must call `ipcMain.removeHandler(channel)` before re-registering, or use `ipcMain.handleOnce()` for temporary handlers.

### How do I handle errors thrown in the main process handler?

Errors thrown inside an `ipcMain.handle()` listener are automatically caught by the dispatcher. The error's `message` property is serialized and sent to the renderer, causing the Promise returned by `ipcRenderer.invoke()` to reject with an Error object containing that message. Always wrap renderer-side calls in `try/catch` blocks to handle main-process failures gracefully.