How to Resolve the "ReferenceError: alert is not defined / prompt is not defined / window is not defined" Error in JavaScript
The ReferenceError: alert is not defined, prompt is not defined, or window is not defined are classic errors that occur when you try to use a browser-specific API in a non-browser environment, most commonly Node.js.
These APIs are global variables provided by the web browser's runtime environment to interact with the user and the browser window. They simply do not exist in a server-side environment like Node.js.
This guide will explain why this error happens and show you the correct way to handle these different environments.
The Core Problem: Browser-Specific Global Variables
JavaScript can run in many different environments. The two most common are:
- The Browser: Provides a rich set of APIs for user interaction, DOM manipulation, and browser control. These are often exposed as global variables on the
windowobject (e.g.,window.alert,window.document). - Node.js: A server-side runtime that provides APIs for file system access (
fs), networking (http), and other server-related tasks. It does not have a "window" or a user interface.
For example, when you write code that uses a browser-only global and try to run it in Node.js, the Node.js runtime has no idea what that variable is, and it throws a ReferenceError.
// my-script.js
// This function is part of the browser's `window` object.
alert('Hello, World!');
// ⛔️ When run with `node my-script.js`, this throws:
// ReferenceError: alert is not defined
The Solution: Detecting the Environment
If you are writing code that needs to run in both the browser and Node.js (this is known as "isomorphic" or "universal" JavaScript), you must first check which environment your code is currently in before calling a specific API.
The most reliable way to check for a browser environment is to see if the window object exists.
Solution:
function showMessage(message) {
// Check if `window` exists and `window.document` exists.
if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
// We are in a browser environment.
alert(message);
} else {
// We are in a server-side environment (e.g., Node.js).
console.log(message);
}
}
// Example Usage:
showMessage('Hello, World!');
This function will safely use alert() in the browser and fall back to console.log() in Node.js, preventing the ReferenceError.
Alternatives for Common Browser APIs in Node.js
alert() -> console.log()
- Browser:
alert()creates a pop-up dialog to show a message to the user. - Node.js: The equivalent is to log a message to the terminal using
console.log().
prompt() -> readline or prompt-sync
- Browser:
prompt()creates a dialog that asks the user for text input. - Node.js: The equivalent is to read input from the command line. Node.js's built-in
readlinemodule can do this, but for a simpler, synchronous experience similar to the browser'sprompt(), theprompt-synclibrary is an excellent choice.
The prompt-sync Solution:
- Install the package:
npm install prompt-sync - Use it in your script:
const createPrompt = require('prompt-sync')({ sigint: true });
const name = createPrompt('What is your name? ');
console.log(`Hello, ${name}!`);
window -> global or globalThis
- Browser:
windowis the global object. - Node.js: The global object is named
global. - Universal: The modern standard is
globalThis, which refers to the global object in any environment (browser, Node.js, or Web Worker). When possible, preferglobalThisfor universal code.
A Special Case: Server-Side Rendering (e.g., Next.js)
In frameworks like Next.js, your components often render first on the server and then again on the client ("hydration"). This means the same code runs in both environments. If you try to access window or alert at the top level of your component, it will crash on the server.
Solution: Only access browser-specific APIs inside a useEffect hook (for React) or after the component has mounted.
import { useEffect } from 'react';
export default function MyComponent() {
useEffect(() => {
// This code only runs on the client, after the component has mounted.
// It is safe to use `window`, `alert`, etc. here.
alert('Component has mounted in the browser!');
}, []); // The empty dependency array ensures this runs only once.
return <div>My Component</div>;
}
Conclusion
The "alert is not defined" error is a fundamental indicator that your code is running in a non-browser environment like Node.js.
- The root cause is that
alert,prompt, andwindoware browser-specific APIs and do not exist on the server. - The solution is to detect the environment (
typeof window !== 'undefined') and use the appropriate API for each case (e.g.,console.logforalert). - In server-side rendering frameworks, ensure you only access browser globals inside a lifecycle method that runs exclusively on the client, like React's
useEffect.