Explain Codes LogoExplain Codes Logo

Electron require() is not defined

javascript
electron
nodejs
security
Alex KataevbyAlex KataevยทJan 5, 2025
โšกTLDR

Resolve require() is not defined in Electron by setting nodeIntegration: true and contextIsolation: false in webPreferences during the BrowserWindow creation:

new BrowserWindow({ webPreferences: { nodeIntegration: true, // like enabling GPS for a lost tourist contextIsolation: false // breaking down the wall ๐Ÿ˜Ž } });

This configuration activates Node.js features, permitting the usage of require() in Electron's renderer process.

Deep dive: nodeIntegration and security

Swiftly fixing the require() problem is one thing, but understanding the consequences of enabling nodeIntegration is a piece of eight. Starting from version 5, Electron defaults nodeIntegration to false for heightened security, particularly when loading external content.

To access Node.js features safely, use a preload script. Running prior to the renderer process, this script has full access to Node.js APIs, regardless of the nodeIntegration setting. An example:

new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') // secure load-up in progress...๐Ÿ”๐Ÿ‘ } });

In the preload.js script, employ the contextBridge to safely expose only the required functionalities or APIs to the renderer process:

const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld( 'api', { doSomething: () => ipcRenderer.send('do-something') // do-something: "Hey, I'm doing the thing! ๐ŸŽ‰" } );

Here, despite the contextIsolation being enabled, the renderer communicates securely with the main process using IPC.

How to manage nodeIntegration securely

Enabling nodeIntegration certainly comes with its risks. Any renderer-loaded content gains the same privileges as your app, potentially leading to security vulnerabilities.

Enable only when necessary

If your application exclusively loads local HTML files or trusted content, turning on nodeIntegration is relatively safe. However, if pulling in external content, disabling it will hedge against potential security vulnerabilities.

Adaptation to change

The Electron environment is evolving, and as of version 10, the nodeIntegration flag is deprecated. Adapting to these changes means sticking to the updated security recommendations, chiefly using preload scripts effectively.

Maximum security: go sandbox!

If you're striving for maximal security, set sandbox: true in webPreferences. This virtually seals off the environment, leaving IPC as the sole communication medium between your processes.

References