"self is not defined" means JavaScript cannot find a variable or object named self in the current scope. This error typically appears in browser environments where self should reference the global window object, but something has broken that reference.
What "self is not defined" Means
In plain language, your code tried to use self as if it existed, but the JavaScript engine couldn't find it in any accessible scope. The most common scenario is running browser-specific code in Node.js, where self doesn't exist as a global.
Why It Happens
The two most common causes are:
-
Running browser code in Node.js —
selfis a browser global that referenceswindow. Node.js doesn't have it, so any reference throwsReferenceError: self is not defined. -
Shadowing or scope issues — You declared
const self = somethinginside a block, then tried to access it outside that block. Or you're usingselfin a module scope where it wasn't defined.
Example Code That Triggers It
// This runs in Node.js but references a browser global
function getGlobalContext() {
return self; // ReferenceError: self is not defined
}
getGlobalContext();
If you run this with node example.js, you'll get the error immediately. The same code works in a browser because self exists there.
How to Fix It
// Node.js fix: use globalThis instead
function getGlobalContext() {
return globalThis; // Works in both Node.js and browsers
}
getGlobalContext();
The fix works because globalThis is a standardized global that exists in every JavaScript environment — Node.js, browsers, and workers. It always points to the root scope, making it the safe replacement for self, window, or global.
Common Mistakes That Cause This
Mistake 1: Mixing environments without checking. Developers often write code that runs in a browser first, then later execute it in Node.js for testing or server-side rendering. The fix is to use globalThis from the start, not self.
Mistake 2: Destructuring or aliasing incorrectly. Some devs do const { self } = window or assign self = this in a constructor, then expect it to persist. If window is undefined (Node.js) or the assignment happens in a nested scope, self becomes undefined or throws.
When Should You Worry About This?
You should worry when this error appears in a production browser environment, not just Node.js. If self is undefined in a browser, it means either:
- Your code is running in a Web Worker where
selfexists but has different properties - You're using a bundler (like Webpack or Vite) that's stripping or renaming globals
- You've accidentally declared
let selfsomewhere, shadowing the global
In those cases, check your bundler config and any variable declarations before blaming the environment.
First, check whether you're running in Node.js or a browser — if it's Node.js, replace self with globalThis and move on.