Electron Node Integration Error Fix
In this tutorial, you'll learn about Electron Node Integration Error Fix. We cover key concepts, practical examples, and best practices.
The Problem
Your Electron app's renderer process cannot access Node.js APIs like require(), process, or fs. Errors include require is not defined or process is not defined. Since Electron 12, contextIsolation is enabled by default.
Quick Fix
Step 1: Use a preload script
// preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
openFile: () => ipcRenderer.invoke('dialog:openFile'),
platform: process.platform
});
Step 2: Configure preload in main process
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
win.loadFile('index.html');
}
Step 3: Access exposed APIs in renderer
// renderer.js
document.getElementById('open-btn').addEventListener('click', async () => {
const file = await window.electronAPI.openFile();
console.log('Selected file:', file);
});
console.log('Platform:', window.electronAPI.platform);
Step 4: Disable contextIsolation (not recommended)
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
Expected: Only for legacy apps. This is a security risk.
Step 5: Use IPC for file system access
// main.js
ipcMain.handle('dialog:openFile', async () => {
const result = await dialog.showOpenDialog();
return result.filePaths[0];
});
Prevention
- Always use preload scripts with contextBridge.
- Keep contextIsolation enabled for security.
- Use IPC for main/renderer communication.
Common Mistakes with node integration
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world ELECTRON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro