Ad Space — Top Banner

window is not defined

JavaScript Programming Language

Severity: Moderate

What Does This Error Mean?

This error means code that relies on browser globals (window, document, localStorage) is running in Node.js. Node.js has no browser — it has no window object. This is extremely common in server-side rendering frameworks like Next.js, Nuxt, and Gatsby.

Affected Models

  • Chrome DevTools
  • Firefox DevTools
  • Node.js
  • React
  • Vue.js

Common Causes

  • A React or Vue component accesses window or document at the top level (outside useEffect)
  • A third-party library uses browser globals and is imported in a server-side rendered page
  • Code runs during static site generation (SSG) where there is no browser context
  • A test runs in Node.js (Jest) without a DOM simulation configured
  • localStorage, navigator, or screen is accessed before the component mounts

How to Fix It

  1. In React, move all window/document access inside a useEffect hook.

    useEffect only runs in the browser, after the component mounts. Code there is safe from SSR errors.

  2. Guard browser code with a typeof check before using it.

    if (typeof window !== 'undefined') { // safe to use window here }. This check works in both Node and the browser.

  3. In Next.js, use dynamic import with ssr: false for libraries that use browser globals.

    const MyMap = dynamic(() => import('./Map'), { ssr: false }). This tells Next.js to only load the component in the browser.

  4. In Jest, configure the test environment to jsdom in your jest.config.js.

    Set testEnvironment: 'jsdom'. This gives your tests a simulated browser DOM so window and document exist.

  5. Check the library's documentation for an SSR-compatible version or configuration option.

    Many popular libraries (charts, maps, animations) have known SSR issues and document a specific workaround.

When to Call a Professional

This is a standard SSR (server-side rendering) compatibility issue. If you are using a framework like Next.js for the first time, a frontend developer familiar with SSR patterns can solve this quickly.

Frequently Asked Questions

Why does my React app work in development but crash in production?

Many Next.js and Gatsby projects use server-side rendering only in production builds. Development mode may skip SSR, hiding the bug. Always test with a production build (npm run build) before deploying.

What browser globals commonly cause this error?

The most common ones are: window, document, localStorage, sessionStorage, navigator, screen, and location. Any of these will throw ReferenceError in a pure Node.js environment.

Does this error mean my code is wrong?

Not necessarily — it means browser code ran in a non-browser context. SSR frameworks intentionally run your components in Node.js to generate HTML. The fix is to defer browser-specific code to the client side, not to remove the functionality.