Quick answer: The browser reached a name that does not exist in any scope it can see at that moment. In a web game this is usually one of four things: a script ran before the script that defines the name, the library file never loaded (a 404 or a blocked CDN), the name lives inside a module or a block and is not global, or the code expects Node.js globals such as require. Open the Network tab first to rule out a failed download, then check the order of your script tags.

The canvas is blank and the console shows one red line naming something you are sure exists: Phaser, PIXI, THREE, your own startGame function. The message is the same for a typo, for a library that failed to download and for a function that is defined in the wrong scope, so the text alone does not tell you which one you have. This guide lists the wording in each browser, the causes that produce it in HTML5 games, how to tell them apart in about a minute, and the fix for each with code.

The exact error

Chrome and Edge print this in the console, followed by the file and position:

Uncaught ReferenceError: Phaser is not defined
    at game.js:3:14

Firefox and Safari word the same error differently, and there are two close relatives that are also a ReferenceError. These are the messages from current builds of the three engines:

SituationChrome, EdgeFirefoxSafari
The name does not existUncaught ReferenceError: Phaser is not definedReferenceError: Phaser is not definedReferenceError: Can't find variable: Phaser
A let, const or class is used before its line has runUncaught ReferenceError: Cannot access 'score' before initializationReferenceError: can't access lexical declaration 'score' before initializationReferenceError: Cannot access 'score' before initialization.
Assignment to an undeclared name in strict mode or in a moduleUncaught ReferenceError: lives is not definedReferenceError: assignment to undeclared variable livesReferenceError: Can't find variable: lives

The word Uncaught is Chrome’s prefix for an exception nobody caught. It is part of event.message in an error handler, and it is not part of error.message on the object itself. If the reference is inside a promise chain or an async function, Chrome prints Uncaught (in promise) ReferenceError: ... instead.

What the error means

When JavaScript meets a bare name, it looks for it in the current block, then each enclosing function, then the module, then the global object. If the name is in none of them, the engine throws a ReferenceError. The check happens when the line runs, not when the file loads, which is why a game can start, play for a minute and only then fail inside a rarely used function.

Three consequences matter when you debug it:

The common causes in a web game

CauseHow to recognize it
Scripts in the wrong orderThe name is a library global or lives in another of your files, and that file’s tag comes later in the HTML
The library failed to loadA red row in the Network tab, and a failed-load line in the console just above the error
async, defer or module timingThe order in the HTML looks right, and the error comes and goes between reloads or only appears on a slow connection
The function is inside a moduleThe stack ends in HTMLButtonElement.onclick, or the name is defined in a file loaded with type="module"
Typo or wrong casePlayr, phaser instead of Phaser, Pixi instead of PIXI
Block or function scopeThe name is declared with let or const inside an if, a loop or another function
Node.js globals in the browserThe missing name is require, process, module, exports or __dirname
DOM globals in a Web WorkerThe missing name is window or document and the file in the stack is your worker script
Used before its declarationThe “before initialization” wording from the table above

Find which cause you have

  1. Click the file and line link at the end of the console message. You need to know which name is missing and which file asked for it.
  2. Open the Network tab, tick Disable cache, reload and filter by JS. Any row that is red, has status 404, or shows a blocked or failed status is a script that never ran. Chrome also logs Failed to load resource: the server responded with a status of 404 (Not Found) for it, and Firefox logs Loading failed for the <script> with source “...”.
  3. When the page has finished loading, type typeof Phaser (with your missing name) in the console. If it prints "undefined", the name was never defined globally: a failed load, a typo, or a module or block scope. If it prints "function" or "object", the name exists now and did not exist when your code ran. That is an ordering or timing problem.
  4. Read the script tags in the page source from top to bottom and note which have async, defer or type="module".
  5. If the file in the stack is a worker script, skip to the Web Worker part of the environment section.

Fix: script order, failed loads and timing

Order and failed downloads

Plain script tags run in the order they appear, each one finishing before the next starts. The game file is first here, so it runs before the engine exists:

<script src="js/game.js"></script>
<script src="js/vendor/phaser.min.js"></script>

Put dependencies first:

<script src="js/vendor/phaser.min.js"></script>
<script src="js/game.js"></script>

If the order is right and the Network tab shows the library request failing, the order was never the problem. A 404 means the path is wrong on that host. The usual reasons are a file name that differs in case and a path that starts with / on a site served from a subfolder, both covered in the guide to 404s on GitHub Pages and itch.io. A library on a public CDN can also be stopped by an ad blocker, a school or office filter, or an http:// URL on an HTTPS page (see the mixed content guide). Hosting the engine file next to your game removes all three.

Whichever way the engine is loaded, make its absence say what happened. This goes at the top of the first file that uses it:

if (typeof Phaser === "undefined") {
  throw new Error("phaser.min.js did not load. Check the Network tab for the request.");
}

async, defer and module timing

The attributes on a script tag change when it runs, and inline scripts ignore most of them.

TagWhen it runs
<script src>Immediately, in document order, pausing the HTML parser
<script defer src>After the document is parsed, in document order
<script async src>As soon as its download finishes, in no fixed order
<script type="module">, inline or with srcDeferred, like defer
Inline classic <script>Immediately. async and defer have no effect on it
A script element created from JavaScriptLike async, unless you set script.async = false

This page fails on most loads, because the inline script runs while the engine is still downloading:

<script async src="js/vendor/phaser.min.js"></script>
<script>
  const game = new Phaser.Game({ width: 800, height: 600 });
</script>

Move the inline code into a file and give both tags the same treatment. Two defer scripts keep their order:

<script defer src="js/vendor/phaser.min.js"></script>
<script defer src="js/game.js"></script>

The same race happens in the other direction when a classic script calls something that a module puts on window: the module is deferred, so the classic script runs first. If you must keep inline code, wait for DOMContentLoaded, which fires after deferred scripts and modules have run:

document.addEventListener("DOMContentLoaded", () => {
  const game = new Phaser.Game({ width: 800, height: 600 });
});

When you add a script from code, wait for its load event before using what it defines:

function loadScript(src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = src;
    script.onload = resolve;
    script.onerror = () => reject(new Error("Failed to load " + src));
    document.head.appendChild(script);
  });
}

loadScript("js/vendor/phaser.min.js").then(startGame);

Fix: module scope, block scope and inline handlers

Everything declared at the top of a classic script becomes global. Nothing declared in a module does. An inline onclick attribute looks its names up in the global scope, so this button throws startGame is not defined when clicked, with HTMLButtonElement.onclick in the stack:

<button onclick="startGame()">Play</button>

<script type="module">
  function startGame() {
    // ...
  }
</script>

Attach the handler from inside the module, where the function is visible:

<button id="play">Play</button>

<script type="module">
  function startGame() {
    // ...
  }
  document.getElementById("play").addEventListener("click", startGame);
</script>

If something outside your code has to call the function by name (a portal SDK, an engine export, the console while you debug), publish it deliberately with window.startGame = startGame;.

With a bundler such as Vite or webpack, every file is a module. A class defined in player.js is unknown in enemy.js until that file imports it, and a library installed from npm has no global at all:

// enemy.js
import * as THREE from "three";
import { Player } from "./player.js";

Block scope produces the same message on a smaller scale. A let or const exists only inside the braces that contain it:

if (level === 1) {
  const boss = spawnBoss();
}
boss.update(dt);   // ReferenceError: boss is not defined

Declare it where every user can see it:

let boss = null;
if (level === 1) {
  boss = spawnBoss();
}
if (boss) boss.update(dt);

In a minified production build the missing name may be a single letter that appears nowhere in your source. Reproduce the error in the development build, or load the source map, before you try to read it.

Fix: names that belong to another environment

require, process, module and exports in the browser

These names are provided by Node.js. No browser defines them, so code written or compiled for Node fails on its first line.

A package that needs the file system or other Node modules cannot run in a browser whatever you do to these names. Check whether it ships a browser build.

window and document inside a Web Worker

A worker has no page, so window and document do not exist there. A worker file that starts like this throws window is not defined on its first line:

// pathfinding-worker.js
const width = window.innerWidth;

Inside a worker the global object is self, and globalThis works in both places. Anything that comes from the page has to be sent in a message:

// main thread
worker.postMessage({ type: "init", width: window.innerWidth, height: window.innerHeight });

// pathfinding-worker.js
self.onmessage = (event) => {
  if (event.data.type === "init") {
    const { width, height } = event.data;
    // ...
  }
};

For drawing in a worker, pass a canvas across with canvas.transferControlToOffscreen() instead of touching document. A library that reads window while it loads cannot be imported into a worker at all. The page hears about worker failures through worker.onerror, which receives the message, the worker file name and the line.

You get the same message when browser code is run by Node, for example in a build script or a unit test. There the guard is typeof window !== "undefined".

The sibling error: “Cannot access before initialization”

Here the name exists, and its let, const or class line has not run yet. Function declarations are hoisted and can be called from anywhere in their scope. Classes cannot:

const player = new Player();   // ReferenceError: Cannot access 'Player' before initialization
class Player {}

Move the class above its first use, or put it in its own module and import it. In a project split into modules, the usual source is a circular import. game.js is the entry point:

// game.js
import { Player } from "./player.js";
export const TILE = 16;
const player = new Player();

// player.js
import { TILE } from "./game.js";
const HALF_TILE = TILE / 2;   // runs before game.js has reached its TILE line
export class Player {}

player.js runs first because game.js imports it, and at that point TILE has not been initialized. Break the cycle by moving shared constants into a third file that imports nothing from the other two:

// constants.js
export const TILE = 16;

Confirm the fix

  1. Reload with Disable cache ticked in the Network tab. The console should be clean and every script row should have status 200.
  2. Set the Network tab’s throttling menu to a slow preset and reload a few times. A timing race that hides on a fast machine shows up here.
  3. Right-click the library request in the Network tab, choose Block request URL and reload. You should now see your own “did not load” message, which is what a player behind a filter will send you.
  4. Repeat in Firefox and Safari. The wording changes, and so do some timings.

Seeing this error from players’ browsers

The Bugnet Web SDK adds error and unhandledrejection listeners when you call Bugnet.init(). An uncaught ReferenceError is filed once per session with the message, the file and line, the stack, the last 50 console lines, a screenshot of the canvas, the user agent and the game version. Reports with the same title stack into one entry with an occurrence count.

Two limits apply to this error in particular. The SDK is subject to load order like everything else: it reports errors thrown after its own script has loaded and Bugnet.init() has run, so load it with a plain script tag ahead of the engine and the game. And the report title is the browser’s message, which differs between engines, so one missing library can appear as separate entries for Phaser is not defined and Can't find variable: Phaser. The failed download itself produces no report, because a failed <script> request does not raise an error the SDK listens for. The ReferenceError that follows it does. Setup is in the SDK docs.

Frequently asked questions

What does Uncaught ReferenceError: X is not defined mean?

JavaScript looked for the name X in the current block, the enclosing functions, the module and the global object and did not find it. The error is thrown when the line runs, so it can appear long after the page has loaded. Firefox prints the same text without Uncaught, and Safari prints Can't find variable: X.

Why is Phaser (or PIXI, or THREE) not defined when the script tag is there?

Either the library file did not load, or your code ran before it. Check the Network tab for a 404 or a blocked request, then check that the library tag comes before your game tag and that neither is async. If you installed the library from npm and use a bundler, there is no global and each file has to import it.

Why does my onclick handler say the function is not defined?

An inline onclick attribute looks for the function in the global scope, and functions declared inside a script with type=module are not global. Attach the handler with addEventListener from inside the module, or assign the function to window on purpose.

How do I fix require is not defined or process is not defined in the browser?

Those are Node.js globals and browsers do not provide them. Use import and export with a module script or run the code through a bundler, and read build settings from the bundler's own mechanism such as import.meta.env in Vite. A package that needs Node's file system cannot run in a browser.

What is the difference between is not defined and Cannot access before initialization?

Is not defined means the name does not exist in any visible scope. Cannot access before initialization means the name is declared with let, const or class and the code used it before that declaration ran, which often comes from a circular import between two modules.

Check the Network tab before you read your code: a library that never downloaded and a script that ran too early produce the same message. typeof is the one test that tells you which without throwing.