How to Fix TypeError: Cannot read properties of undefined (reading 'whenReady')

Abstract: Resolve the TypeError when accessing app.whenReady in Electron by correctly importing and destructuring the app module from electron.

Created: 2026-09-21 by

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 message TypeError: 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 the app 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 named main.js or index.js. Follow these steps to correct the reference:
  1. Check Your Import Statement: Ensure that you are importing the app object from the electron module correctly. The standard way to do this in modern JavaScript is using destructuring.
  2. Verify Variable Naming: Look for any local variables or functions named app within the same scope that might be overriding the imported value. Rename your custom variables to avoid shadowing.
  3. Confirm Execution Context: Make sure the code calling whenReady() is running in the main process. Renderer processes do not have access to the app module directly.
Here is the correct pattern for initializing the Electron app:
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 the electron 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More