Solve - Alert is not Defined Error in JavaScript


Borislav Hadzhiev

Tue Oct 19 20212 min read


Photo by Sereja Ris

Solve - Alert is not Defined Error in JavaScript #

The "ReferenceError: alert is not defined" occurs when the alert() method is used outside of the browser environment, most commonly in Node.js. The alert method is a method on the window object, which is only available in the browser.

referenceerror alert is not defined

To solve the "alert is not defined" error, use the console.log or console.error methods instead of alert when outside the browser. The console.log and console.error methods allow us to output a message to the web console or standard output and error if you're on the server side.

console.log('hello'); console.error('an error occurred');

If you're getting the error in a browser, you might be using server side rendering (e.g. with Next.js), or you might have misspelled alert (all lowercase).


If you're getting the error when using server side rendering, you can conditionally check if you're on the browser (can use alert) or you are on the server (can't use alert).

if (typeof window !== 'undefined') { console.log('You are on the browser') // 👉️ can use alert() } else { console.log('You are on the server') // 👉️ can't use alert() }

In our if statement, we check if the window global variable is not undefined. If it is defined, we can use the alert method.

The alert method is defined on the window object in the browser.
console.log(alert === window.alert); // 👉️ true

If you check whether alert is equal to window.alert in a browser environment, we get a true value back.

The window global variable represents the window that contains the DOM document (browser side only).

An easy way to think about it is - in a browser, each tab is represented by its own Window object.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.