ReferenceError 🟨 JavaScript

ReferenceError: x is not defined

Code refers to a variable or function name that doesn’t exist in the current scope.

Seen on: JavaScript Node.js React

Meaning

Unlike undefined (declared but no value), “not defined” means the identifier was never declared where the code runs. Classic sources: typos, missing imports, scripts loading in the wrong order, and Node-only globals used in the browser (or vice versa).

Common causes

  • Typo or wrong case (myVar vs myvar)
  • Missing import / script tag
  • Using a variable outside its block scope (let/const)
  • Script order: library (e.g. jQuery $) loaded after the code using it
  • require, module, __dirname used in browser or ES modules
  • window/document used during server-side rendering (Next.js)
  • Accessing let/const before declaration (temporal dead zone)

⚡ Quick fix

  1. Check spelling and scope at the line in the stack trace
  2. Add the missing import or <script> before your code
  3. In ES modules, replace __dirname with path.dirname(fileURLToPath(import.meta.url))
  4. Guard browser globals in SSR: if (typeof window !== 'undefined')

Detailed fix by platform

Node.js

  1. __dirname in ES modules:
    javascript
    import { fileURLToPath } from 'node:url';
    import path from 'node:path';
    const __dirname = path.dirname(fileURLToPath(import.meta.url));

React

  1. Next.js: move window/localStorage access into useEffect, which only runs in the browser.

How to diagnose

  1. Name — Spelled and cased correctly?
  2. Scope — Declared in an enclosing scope?
  3. Load order — Is the defining script/import loaded first?
  4. Environment — Browser vs Node vs SSR?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.