TypeError: Cannot read properties of undefined (reading 'x')

Node.js · updated 2026-11-05

Thrown at the exact expression that reads a property from undefined; the first stack frame in your own code points at it. The name in parentheses is the property being read ('x' here), not the variable that was undefined.

TypeError: Cannot read properties of undefined (reading 'reduce')
    at getOrderTotal (/app/src/orders/total.js:27:29)
    at buildInvoice (/app/src/orders/invoice.js:41:19)
    at async handleInvoice (/app/src/routes/invoices.js:18:21)

Quick fix

Look at the property named in parentheses: the object just to its left is undefined. Trace where that object comes from, fix the missing data or missing await at its source, and guard values that are legitimately optional with ?. or an early return so one gap in the data cannot crash the request.

  1. Open the first stack frame inside your code and find the exact expression.
  2. Identify the object left of the named property; that is the undefined value.
  3. Trace where that object is assigned, returned or destructured.
  4. Add the missing await, default value or not-found check at the source.
  5. Use optional chaining (a?.b?.c) only for fields that are truly optional.
typescript
// Before: crashes when a user has no profile yet
// const city = user.profile.address.city;

// Optional data: guard it
const city = user.profile?.address?.city ?? 'unknown';

// Required data: fail early with a message that says what was missing
const order = await db.order.findUnique({ where: { id: orderId } });
if (!order) {
  throw new Error(`Order ${orderId} not found`);
}
const total = order.items.reduce((sum, item) => sum + item.price, 0);
Fix it with your coding agent

Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.

prompttext
Read https://runheed.com/errors/cannot-read-properties-of-undefined.md and fix this error in this project.

Why it happens

Missing await

const user = getUser(id) without await gives you a Promise. A Promise has no profile field, so user.profile is undefined and user.profile.name throws. Look for async functions called from code that treats the result as plain data.

A lookup found nothing

Array.prototype.find, Map.get, object key lookups and many ORM single-row queries return undefined (or null) when nothing matches. The code after them assumes a match and reads a field from the empty result.

The data has a different shape than expected

An API wraps its payload ({ data: { items } } instead of { items }), a field was renamed, or destructuring pulls a key that does not exist. Destructuring never throws on a missing key; the crash happens one line later.

Array index past the end

rows[0].id on an empty result set, or a loop written with i <= arr.length that reads one element too far. Both produce undefined and then fail on the property read.

Class method passed as a callback

items.map(this.format) or promise.then(this.flush) detaches the method from its object. In class bodies (strict mode) this becomes undefined inside the call, so this.queue fails with exactly this TypeError.

Other fixes

  • Validate request bodies and API responses with a schema at the boundary so bad shapes fail with a clear message.
  • Enable strict and noUncheckedIndexedAccess in tsconfig so the compiler flags possibly undefined reads.
  • Bind methods in the constructor, or define them as arrow-function class fields, before passing them as callbacks.
  • Load configuration at startup and validate it, so missing config sections fail at boot instead of mid-request.

Same error, other wording

  • TypeError: Cannot read property 'x' of undefined
  • TypeError: Cannot read properties of null (reading 'x')
  • TypeError: undefined is not an object (evaluating 'a.x')
  • TypeError: can't access property "x", a is undefined

Let your coding agent catch the next one

Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:

> Find the most frequent "Cannot read properties of undefined" error in production, show which variable was undefined and the request that triggered the latest occurrence, and fix the data at its source or add the right guard.

Setup for Supabase Edge Functions, Vercel Functions or AWS Lambda (Node.js and Python), then have your agent fix and resolve it.

Related errors

More in Undefined, None and type errors

Other error topics

Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.

References: MDN: TypeError: "x" is (not) "y", MDN: Optional chaining (?.)

Spotted a mistake? Email hello@greatwork.company. About Runheed.