Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Testing and Performance

Memory, Debugging and Profiling

Debug the main and renderer processes, find memory leaks with heap snapshots, log to files with rotation, capture crash reports and profile CPU use in Electron apps.

Debugging an Electron app means debugging several programs at once: the main process, one renderer per window, maybe a preload script and utility processes. Each has its own tools, and a bug can hide in the gap between them. Once the app is in users' hands you also need logs and crash reports, because you cannot attach a debugger to their computer.

This lesson gives you the toolbox: DevTools for renderers, an inspector for the main process, memory tools for leaks, structured logging, crash reporting and the sanity checks that catch the usual suspects.

Debugging the renderer

Each window is a Chromium page, so it has the Chrome DevTools you know. Open them from code or a shortcut:

JavaScript
if (!app.isPackaged) win.webContents.openDevTools({ mode: 'detach' });

mode: 'detach' puts DevTools in its own window so it does not squash your layout. In production, remove the shortcut or gate it (a hidden menu item behind a setting), because DevTools in a shipped app is a way to poke around inside it. The fuse EnableNodeCliInspectArguments (Safe Storage and Fuses) also blocks remote inspection of release builds.

Useful panels: Console (errors and your console.log), Network (for loaded remote content), Sources (breakpoints, with source maps for TypeScript or bundled code), Performance (flame charts) and Memory.

Debugging the main process

The main process is Node, so use the Node inspector.

TEXT
electron --inspect=5858 .

Then attach Chrome (chrome://inspect) or VS Code. With VS Code, a launch configuration does it all:

JSON
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Main Process",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceFolder}",
      "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
      "windows": { "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd" },
      "args": ["."],
      "outputCapture": "std"
    }
  ]
}

Breakpoints in main.js and in IPC handlers now pause the app. Remember that pausing the main process freezes every window, which is a good way to see what runs on that thread.

Logging that helps in the field

console.log disappears when no terminal is attached. For real apps, write log files to app.getPath('logs'), with levels, timestamps and rotation so they do not grow forever. electron-log does it with one import; here is the idea in a small module you can run.

Node.js A logger with levels and rotation

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.

Two professional touches are visible: the log rotates so disk use is bounded, and secrets are redacted before they reach the file. Ask users to send you the log from "Help, Open Logs Folder" when something goes wrong.

Catching errors nobody expected

Install global handlers in the main process so that a bug is logged rather than silently dying or showing Electron's default dialog:

JavaScript
process.on('uncaughtException', (err) => { logger.error('uncaught', { stack: err.stack }); });
process.on('unhandledRejection', (reason) => { logger.error('unhandled rejection', { reason: String(reason) }); });

win.webContents.on('render-process-gone', (_e, details) => {
  logger.error('renderer gone', details);              // reason: crashed, oom, killed...
  if (details.reason !== 'clean-exit') win.reload();
});
win.webContents.on('unresponsive', () => logger.warn('window unresponsive'));

For native crashes (a segmentation fault in Chromium or a native module) use the built-in crash reporter:

JavaScript
import { crashReporter } from 'electron';

crashReporter.start({
  productName: 'Notes Studio',
  submitURL: 'https://crashes.example.com/submit',
  uploadToServer: true,
});

It writes minidumps and uploads them to your own crash server (Sentry, Backtrace and similar services provide one). Tell users what you collect and ask consent where law or good manners require it.

Memory: how leaks happen

Electron memory shows up in Task Manager as one process per window plus GPU and utility processes. A window that grows steadily without doing more work has a leak: objects stay reachable when they should be garbage. The usual suspects:

  • Event listeners never removed. ipcRenderer.on(...), window.addEventListener, emitter.on inside code that runs repeatedly.
  • Timers and intervals never cleared when a view is closed.
  • Caches without a limit: a Map that only grows.
  • Detached DOM nodes referenced from JavaScript after being removed from the page.
  • Windows kept in arrays after they are closed.

Finding them: open DevTools, Memory tab, take a heap snapshot, perform the action you suspect 20 times, take another snapshot, and compare; or use the "Allocation instrumentation on timeline". In the comparison view, look for counts that grow by exactly the number of repetitions.

Leaks you can reproduce

The most common pattern is a listener added per use and never removed. This example simulates a view that subscribes to an event bus each time it opens. The leaky version keeps stale listeners alive; the fixed version cleans up.

Node.js Finding a listener leak

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 Node itself you get a warning when more than ten listeners accumulate on one event name. Treat MaxListenersExceededWarning as a leak report, not noise.

Watching memory over time

Both processes can report their own numbers. process.memoryUsage() works in the main process, and app.getAppMetrics() lists memory and CPU for every process, which is great for a diagnostics page or an automated test that fails if memory grows too much.

JavaScript
setInterval(() => {
  const metrics = app.getAppMetrics().map((m) => ({
    type: m.type,
    mb: Math.round(m.memory.workingSetSize / 1024),
  }));
  logger.debug('memory', metrics);
}, 30_000);

This sampler detects steady growth: it records readings and flags a trend when most steps go up and the total growth is large.

Node.js Detecting steady memory growth

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.

CPU profiling

For slowness rather than memory, use the Performance panel in a renderer (record, perform the slow action, stop, read the flame chart: wide bars are expensive functions) and, for the main process, --inspect plus the Profiler tab, or node --cpu-prof. Look first for long tasks over 50 ms; those are what users feel as jank. Compare before and after every change.

A debugging checklist

  1. Reproduce it in a packaged build: some bugs only appear there.
  2. Check both consoles: the terminal (main process) and DevTools (renderer).
  3. Read the log file and any render-process-gone reason.
  4. Bisect: disable features and plugins until it stops.
  5. For memory, snapshot, repeat, snapshot, compare.
  6. Add a regression test (Testing Electron Apps) before fixing, so it cannot come back.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you attach a debugger to the main process?

    The main process is Node.js. The Node inspector protocol lets Chrome DevTools or VS Code set breakpoints in it.
  2. 2. Which of these is the classic source of a renderer memory leak?

    A listener keeps its closure and the data it captured alive. Repeating the action keeps adding more.
  3. 3. What does the render-process-gone event tell you?

    details.reason distinguishes a crash, out-of-memory kill and a clean exit, which makes support much easier.
  4. 4. Why redact values like tokens before writing log lines?

    Logs travel: they are shared in bug reports and may be uploaded. Secrets must never appear in them.

Summary

  • Debug renderers with DevTools and the main process with --inspect or a VS Code launch config.
  • Write rotating, level-based, redacted logs to app.getPath('logs').
  • Handle uncaught errors, render-process-gone and unresponsive, and enable the crash reporter for native crashes.
  • Hunt leaks with heap snapshots; the usual causes are listeners, timers, unbounded caches and retained windows.
  • Sample memory with app.getAppMetrics() and profile CPU with flame charts before optimising.

Next: Project: A Markdown Notes App