Lesson 3 of 9 · 24m
Designing IPC Contracts That Scale
ipcMain/ipcRenderer are transport primitives, not an API; versioned, typed, least-privilege channels keep Electron apps maintainable and auditable.
Most Electron codebases begin with ipcRenderer.send("save", data) and end with eighty untyped channels, half of them undocumented and several accidentally exposing admin powers. IPC is your application's internal RPC boundary. Treat it like an API contract, because architecturally that is exactly what it is.
Prefer invoke/handle for request-response
// main
ipcMain.handle("workspace:read-settings", async (event) => {
requireTrustedSender(event);
return settingsStore.read();
});
// preload
contextBridge.exposeInMainWorld("workspace", {
readSettings: () => ipcRenderer.invoke("workspace:read-settings"),
});invoke returns a promise and preserves errors across the boundary. It is almost always better than manually pairing send with response event names. Use event streams (webContents.send) for pushes such as download progress, updater status, or output from a long-running helper.
Channel names are capabilities
A good channel name tells you who owns it and what authority it grants:
workspace:read-settings
report:save-pdf
updater:install-downloaded
window:minimizeA bad channel name is invoke, message, or ipc. Generic channels destroy least privilege because every renderer can suddenly reach every operation. If one window shows untrusted help content and another edits billing settings, they must not receive the same bridge object or channel surface.
Validate every argument in main
Renderer validation is UX. Main-process validation is security.
const SaveReportSchema = z.object({
title: z.string().min(1).max(120),
findings: z.array(z.object({ id: z.string().uuid(), severity: z.enum(["low", "medium", "high", "critical"]) })).max(5000),
});
ipcMain.handle("report:save", async (event, payload) => {
requireTrustedSender(event);
return reportService.save(SaveReportSchema.parse(payload));
});Never trust paths, URLs, IDs, sizes, or object shapes merely because your own UI created them. XSS does not care how pretty your React form was.
Think in errors, versioning, and cancellation
Desktop IPC crosses process boundaries; failures are normal. Return structured results such as { ok: false, code: "QUOTA_EXCEEDED" } or throw errors with stable codes. Include schema versions when persisted messages or long-lived preload contracts can outlive a release. For long work, expose a cancellation channel rather than forcing users to quit the application.
Field notes
event.senderFrame.urlandevent.senderare part of authorization; check them before acting.- Objects crossing IPC are structured-cloned, not passed by reference — functions and class identity vanish.
- Don't broadcast events to all windows when one window is the intended recipient.
- Log channel names and error codes, not payloads; IPC payloads often contain user data.
Was this lesson helpful?