Electron require() is not defined
Resolve require() is not defined in Electron by setting nodeIntegration: true and contextIsolation: false in webPreferences during the BrowserWindow creation:
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:
In the preload.js script, employ the contextBridge to safely expose only the required functionalities or APIs to the renderer process:
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
Was this article helpful?