How to fix JavaScript errors

Find the error in the console, read the stack trace, fix the usual causes, and handle errors with try/catch, async/await and window.onerror. Code included.

javascript errorserror handlingdevtools

Open the console, read the message and the first stack frame that is your file, reproduce that line, fix the cause, and then catch the same class of error so the next one is reported instead of failing silently. In Chrome the console is F12, or Command-Option-J on a Mac, or Control-Shift-J on Windows and Linux.

Opening Safari's console is a different set of steps: how to open the Safari console. Which panel to use for a layout bug or a failed request is website debugging tools.

Find the error

Open the page that failed and open the console before you repeat the click. The console does not keep messages from before it was opened, and a navigation clears it.

  • Chrome. Command-Option-J (Mac) or Control-Shift-J (Windows and Linux) opens the Console panel. F12 or Command-Option-I opens the last DevTools panel you used, which is not always the console.
  • Firefox. Command-Option-K (Mac) or Control-Shift-K (Windows and Linux) opens the console. F12 opens the toolbox.
  • Safari. Developer features are off until you enable them. The path is how to open the Safari console.

Turn on Preserve log in the console settings (the gear in Chrome's console) before a reload or a redirect. Firefox calls the same control Persist Logs. Safari's console has Preserve Log. Without it, a submit that navigates away deletes the error you needed.

Open the Network panel when the console error is a consequence of a request. A 404 on a script URL means that file never ran. A 500 from the API the page needs will show up as a red row, and the JavaScript often throws afterward because it read undefined from a body that was an error page. Turn on the Network panel's own Preserve log so the row survives the redirect. Filter by status if the list is long.

Read the stack trace

A console error has a message, then a stack. Each frame is a function, a file, a line, and a column.

Read the message first. Cannot read properties of undefined (reading 'email') tells you the value before .email is undefined. The stack tells you which call did that read.

The first frame in your code is the one to open. Frames above it are often the framework or a library that called you. Frames inside node_modules or a bundled chunk are the library, unless the bug is that you called the library wrong.

Source maps. A production build minifies your files into a bundle. The stack then shows that bundle and a line in the minified output, which you cannot usefully read. A source map connects those positions back to the original file and line. DevTools loads it from the sourceMappingURL in the script or from a SourceMap response header. When the map is missing, you are looking at the bundle. Generate the map for the build you shipped, and give it to the people who debug that build. Do not publish a map of private source on a public URL if the source itself is not public.

The common errors and their usual fixes

The strings below are what current V8 prints. Chrome's console puts Uncaught in front of an error that nothing caught. Run the snippets. They throw on purpose, except where the comment says they do not.

Cannot read properties of undefined

const user = undefined;
user.email;
// TypeError: Cannot read properties of undefined (reading 'email')

The usual cause is data that has not arrived, or a shape that is not the one you destructured. A loading flag is still true, the API returned { error: "..." } and the code read .user.email, or a typo asked for user.emial on an object that has email. Optional chaining and a guard stop the throw. They do not create the user.

const body = { user: undefined };
const email = body.user?.email;

if (!body.user) {
  // Still loading, or the response was an error. Do not read fields yet.
} else {
  body.user.email;
}

email is undefined when body.user is missing. The else branch runs only when user is an object. Fix the fetch or the field name if the user should have been there.

x is not defined

function total(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

total(cart);
// ReferenceError: cart is not defined

cart was never declared in this scope. Usual causes: a typo (cart versus cartItems), a variable declared inside another function, or a script that defines it and has not loaded yet. A 404 on the script URL in the Network panel is that last case. Declare the variable, fix the typo, or fix the script URL. Do not add an implicit global to silence it.

x is not a function

const formatPrice = undefined;
formatPrice(10);
// TypeError: formatPrice is not a function

The name exists, or resolved to undefined, and the code called it. Usual causes: a default export imported as a named export, a named export that the module does not have, or a local variable that shadows the function. Log typeof formatPrice at the call. "undefined" means the binding is empty. "object" or another type means you imported or assigned the wrong value. Fix the import. Calling it inside try does not make it a function.

Unexpected token '<'

JSON.parse of an HTML document throws because < is not JSON. Current V8 prints:

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

const html = "<!DOCTYPE html><title>Not found</title>";
JSON.parse(html);

The usual cause is response.json() on a 404 or a 500 whose body is an HTML error page. Check response.ok, or the status, before you parse. Read text only when you need to show the parser error.

async function readJson(response) {
  if (!response.ok) {
    throw new Error(`request failed: ${response.status}`);
  }
  return response.json();
}

The Network row has the status and the response body. The SyntaxError is what happens when that body is fed to the JSON parser.

Uncaught (in promise)

A promise that rejects, and that nobody awaits or passes to .catch(), is an unhandled rejection. Chrome prints Uncaught (in promise) and then the error.

async function loadSession(response) {
  if (!response.ok) throw new Error(`session ${response.status}`);
  return response.json();
}

// loadSession(failedResponse) with no await and no .catch()
// Console: Uncaught (in promise) Error: session 500

The fix is to await it inside try, or to attach .catch().

async function loadSession(response) {
  if (!response.ok) throw new Error(`session ${response.status}`);
  return response.json();
}

async function showSession(response) {
  try {
    return await loadSession(response);
  } catch (error) {
    console.error(error);
    return null;
  }
}

return null is a stand-in. Show the failure in the UI if a person is waiting on the request. Swallowing the error and rendering a blank success state is how the bug becomes invisible.

CORS

A cross-origin response the browser will not expose produces a console message like this:

Access to fetch at 'https://api.example/session' from origin 'https://app.example' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The browser is refusing to hand the response to the page. The header is missing on the server that answered, or it does not list this origin. Changing the client fetch call does not add that header. The fix is on the server: a response that includes Access-Control-Allow-Origin for the page's origin, and Access-Control-Allow-Credentials as well if the request sends cookies. The Network row often shows the status as a CORS error rather than the status the server returned. The console sentence names the header that was missing.

Loading chunk failed

After a deploy, a tab that was opened on the previous build can request a JavaScript file the new build deleted. Webpack reports that as ChunkLoadError: Loading chunk … failed. Other bundlers print Failed to fetch dynamically imported module or a similar load error for the missing URL. Reloading the tab fetches the new HTML, which points at the new files. Catching the rejection and prompting a reload is the in-app fix. Retrying the old URL will keep failing until the tab loads the new document.

window.addEventListener("unhandledrejection", (event) => {
  const reason = event.reason;
  const message = reason instanceof Error ? reason.message : String(reason);
  if (message.includes("Loading chunk") && message.includes("failed")) {
    // This tab is asking for a file the current deploy removed.
  }
});

Handling errors on purpose

try/catch handles a throw in the synchronous code inside the try, and a rejection of a promise you await there.

try {
  const data = JSON.parse(text);
  render(data);
} catch (error) {
  console.error(error);
}

An error thrown later, from a timer, an event handler, or a promise you did not await, is outside that try. Await it, or use .catch():

loadSession(response).catch((error) => {
  console.error(error);
});

window.onerror and unhandledrejection are the global net. They run when something else did not catch the error. They are how you learn about it. They are not a fix for the throw.

window.onerror = (message, source, lineno, colno, error) => {
  console.error(message, source, lineno, colno, error);
};

window.addEventListener("unhandledrejection", (event) => {
  console.error(event.reason);
});

window.onerror receives the message, the script URL, the line, the column, and the Error object when the browser has one. unhandledrejection receives an event whose reason is the rejection value. Calling event.preventDefault() marks the rejection handled. Do that only when you have actually recorded it.

React. An error boundary is a class component that implements static getDerivedStateFromError or componentDidCatch. It catches a render error in its child tree and can render a fallback. It does not catch errors in event handlers, async code, or the server. Those still need try/catch or .catch(). Put the boundary around a route or a widget you can replace with a message, not around a single expression you could have checked.

Log without leaking

Log the error message, the route, and a request id if you have one. Do not log access tokens, passwords, session cookies, or the body of a request that contains them. A console you attach to a bug report is copied into a tracker. A console.log(user) that includes an email or a token will be pasted with the stack. The same rule applies to window.onerror: report error.message and the source location, not the surrounding form state.

Catch the next one on a flow you can describe

Handling and logging tell you about an error in a session you instrumented. They do not click through sign-up after a deploy. A Monito check runs a scenario you write in plain English in desktop Chromium, usually at 1440×900, and records the console messages, the failed requests as method, URL, and status, and the screenshots from that run. A JavaScript error on the path you described shows up on the run report with that evidence.

You can start it from the check command, from MCP so a coding agent can run it after a change, or from CI. The run ends Passed, Failed, or Error. Error means the check could not verify the scenario. What cannot verify means.

The browser in that run is Chromium. It is not Safari or Firefox, and it is not a matrix of browsers. It is also not error monitoring of your visitors' sessions. There is no real-user feed and no session replay of production traffic. The console you get is the console of the check.

FAQ

How do I fix Cannot read properties of undefined?

The value before the property is undefined. It has not loaded yet, or the object does not have the shape the code expects. Stop reading the property until the value exists, and fix the code that should have set it. Optional chaining hides the throw. It does not supply the missing data.

What is the difference between window.onerror and try/catch?

try/catch handles an error in the block you wrap, including a promise you await inside that try. window.onerror runs later, for an error on the page that nothing caught. It reports the error. It does not undo it. Use try/catch where you can show a message or retry. Use window.onerror as the net for the rest.

How do I catch errors in async code?

Await the promise inside try/catch, or call .catch() on the promise. A promise you neither await nor attach .catch() to becomes an unhandled rejection. Chrome prints Uncaught (in promise) in front of that error. window.addEventListener('unhandledrejection', ...) reports the ones that still get through.

Run a check

Run your first test. The command is monito check. An agent can call the same check through MCP.

Related posts

Compare Monito with other tools
All Posts