This error occurs when your code attempts to access the whenReady property on an object that is currently undefined. In Electron applications, this typically happens because the app module has not been properly imported or initialized before calling app.whenReady(), causing the runtime to throw a TypeError during the startup sequence.
Understanding the Root Cause
The specific messageTypeError: Cannot read properties of undefined (reading 'whenReady') indicates a fundamental issue with object references in your JavaScript execution context. When you write code like app.whenReady().then(...), you are assuming that the variable app holds a valid reference to the Electron application instance. If app is undefined, JavaScript cannot find the method whenReady attached to it, resulting in the crash.
This scenario is most prevalent in Electron projects where the main process entry point fails to correctly bind the electron module. It can also occur if there are naming conflicts, such as defining a local variable named app that shadows the global Electron instance, or if the module resolution fails due to incorrect import syntax. Understanding the lifecycle of the Electron app is crucial here, as whenReady is a promise that resolves only after the application's initialization phase is complete.
Common Scenarios in Electron Development
One frequent cause is using CommonJS require statements incorrectly or mixing them with ES6 imports without proper handling. Another common pitfall is attempting to use theapp object in renderer processes where it is not available by default. The main process must handle all interactions with the system tray, window creation, and lifecycle events. If you are building a complex project involving multiple modules, ensure that the dependency chain does not break the reference to the core electron package. For related configuration issues, you might want to check out our guide on [Electron Builder: Please specify author 'email' in the application package.json](/news/1076268/electron-builder-specify-author-email-in-package-json) to ensure your build environment is stable.
Step-by-Step Resolution
To resolve this issue, you need to verify the import structure of your main process file, usually namedmain.js or index.js. Follow these steps to correct the reference:
- Check Your Import Statement: Ensure that you are importing the
appobject from theelectronmodule correctly. The standard way to do this in modern JavaScript is using destructuring. - Verify Variable Naming: Look for any local variables or functions named
appwithin the same scope that might be overriding the imported value. Rename your custom variables to avoid shadowing. - Confirm Execution Context: Make sure the code calling
whenReady()is running in the main process. Renderer processes do not have access to theappmodule directly.
const { app, BrowserWindow } = require('electron');
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
}
app.whenReady().then(() => {
createWindow();
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
In this example, require('electron') returns the entire electron namespace. We then destructure app from that object. This guarantees that app is defined before we call app.whenReady(). If you are using ES modules, the syntax would be import { app } from 'electron';. Both methods work, but consistency is key.
Debugging Module Resolution Issues
If the import looks correct but the error persists, the issue may lie in how Node.js resolves theelectron module. This often happens in monorepos or when node_modules are not installed correctly. Run npm install or yarn to ensure all dependencies are present. Check your package.json to confirm that electron is listed under dependencies or devDependencies.
Sometimes, the error arises from caching issues or corrupted installation artifacts. Deleting the node_modules folder and the lock file (package-lock.json or yarn.lock) followed by a fresh install can resolve hidden path resolution errors. Additionally, verify that your project directory does not contain a file named electron.js that might interfere with the module lookup, although this is rare in modern setups.
For developers working on macOS who encounter similar module access issues, reviewing [Accessing Node.js Package in Visual Studio Code (Electron App) on MacOS without Installing Node.js](/news/1449221/access-node-js-in-vs-code-without-installing-node-js) might provide insights into environment-specific configurations.
Preventing Future Occurrences
To prevent this error in larger codebases, adopt strict linting rules. Tools like ESLint can catch references to undefined variables before they reach runtime. Configure your linter to treat unused or undefined variables as errors. Furthermore, use TypeScript if possible, as its static type checking will flag any attempt to access properties on an undefined variable during the development phase, long before the application runs. Ensure that your entry point scripts are executed in the correct order. If you are dynamically loading modules, wrap those calls in try-catch blocks or check for existence before accessing deep properties. This defensive programming approach makes your application more resilient to structural changes in your dependency tree.Frequently Asked Questions
Why does this error happen in the renderer process?
The app module is only available in the main process of an Electron application. Renderer processes run in browser contexts and do not have direct access to Electron's core APIs. You must use IPC (Inter-Process Communication) to request actions from the main process instead.
Can I use import instead of require?
Yes, you can use ES6 import syntax provided your project supports it via Babel or native ES module support in Node.js. The key is ensuring that the destructured app variable is correctly assigned from the imported module before use.
What if my package.json is missing the electron dependency?
If electron is not listed in your package.json, Node.js will fail to resolve the module, potentially leading to undefined references. Always run npm install electron --save-dev to add it to your project dependencies.
How do I know if my variable is being shadowed?
You can use your IDE's debugger or console.log to print the value of app right before the error occurs. If it prints undefined or a different object, check the surrounding scope for other declarations with the same name.
Is this error related to the version of Node.js?
No, this is a JavaScript runtime error related to object references, not a Node.js version incompatibility. However, older versions of Electron may have different API structures, so ensure your code matches the documentation for your specific Electron version.