ReferenceError: x is not defined
Code refers to a variable or function name that doesn’t exist in the current scope.
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 (
myVarvsmyvar) - 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,__dirnameused in browser or ES moduleswindow/documentused during server-side rendering (Next.js)- Accessing
let/constbefore declaration (temporal dead zone)
⚡ Quick fix
- Check spelling and scope at the line in the stack trace
- Add the missing import or
<script>before your code - In ES modules, replace
__dirnamewithpath.dirname(fileURLToPath(import.meta.url)) - Guard browser globals in SSR:
if (typeof window !== 'undefined')
Detailed fix by platform
Node.js
- __dirname in ES modules:javascript
import { fileURLToPath } from 'node:url'; import path from 'node:path'; const __dirname = path.dirname(fileURLToPath(import.meta.url));
React
- Next.js: move
window/localStorageaccess intouseEffect, which only runs in the browser.
How to diagnose
- Name — Spelled and cased correctly?
- Scope — Declared in an enclosing scope?
- Load order — Is the defining script/import loaded first?
- 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.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026