# TypeError: Cannot read properties of undefined (reading 'x') (Node.js)

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.

```ts
// 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);
```

## 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`

## Sources

- [MDN: TypeError: "x" is (not) "y"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_type)
- [MDN: Optional chaining (?.)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)

---

To see this error the next time it happens in production, with the stack trace and the steps before it: Runheed records it and serves it to your coding agent over MCP. Setup instructions an agent can follow: https://runheed.com/SETUP.txt

Human-readable version: https://runheed.com/errors/cannot-read-properties-of-undefined
