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.
- Open the first stack frame inside your code and find the exact expression.
- Identify the object left of the named property; that is the undefined value.
- Trace where that object is assigned, returned or destructured.
- Add the missing await, default value or not-found check at the source.
- Use optional chaining (a?.b?.c) only for fields that are truly optional.
// 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);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.
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
- [UnhandledPromiseRejection: This error originated either by throwing inside of an async...
- TypeError: 'NoneType' object is not subscriptable
- SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
More in Undefined, None and type errors
- panic: assignment to entry in nil mapGo
- TypeError: slugify(): Argument #1 ($title) must be of type string, null givenPHP
- System.InvalidOperationException: Sequence contains no elements.NET
- panic: runtime error: invalid memory address or nil pointer dereferenceGo
- NoMethodError: undefined method 'email' for nilRuby
- java.lang.NullPointerException: Cannot invoke "String.toLowerCase()" because the return...Java
- System.NullReferenceException: Object reference not set to an instance of an object..NET
- TypeError: Cannot destructure property 'id' of 'undefined' as it is undefined.Node.js
- TypeError: Cannot convert undefined or null to objectNode.js
- TypeError: items is not iterableNode.js
- TypeError: x is not a functionNode.js
- TypeError: Client is not a constructorNode.js
- ReferenceError: x is not definedNode.js
- ERR_INVALID_ARG_TYPE: The "path" argument must be of type string. Received undefinedNode.js
- AttributeError: 'NoneType' object has no attribute 'x'Python
- TypeError: 'NoneType' object is not iterablePython
- KeyError: 'email'Python
- TypeError: unhashable type: 'list'Python
- AttributeError: 'dict' object has no attribute 'name'Python
- IndexError: list index out of rangePython
- TypeError: unsupported operand type(s) for +: 'int' and 'str'Python
- ValueError: invalid literal for int() with base 10: ''Python
- TypeError: __init__() got an unexpected keyword argument 'proxies'Python
- UnboundLocalError: cannot access local variable 'total' where it is not associated with a...Python
- RuntimeError: dictionary changed size during iterationPython
- ValueError: too many values to unpack (expected 2)Python
- TypeError: 'str' object is not callablePython
Other error topics
- Error: 429 You exceeded your current quota, please check your plan and billing details.Network and HTTP
- Error: write EPIPENetwork and HTTP
- BrokenPipeError: [Errno 32] Broken pipeNetwork and HTTP
- [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379Databases
- error: infinite recursion detected in policy for relation "members"Databases
- pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection...Databases
- Error: Could not load the "sharp" module using the linux-x64 runtimeImports and modules
- Module not found: Can't resolve 'fs'Imports and modules
- AttributeError: module 'requests' has no attribute 'get'Imports and modules
- Element type is invalid: expected a string (for built-in components) or a class/function...React and Next.js rendering
- ReferenceError: window is not definedReact and Next.js rendering
- TypeError: Failed to parse URL from /api/ordersReact and Next.js rendering
- TypeError: Converting circular structure to JSONJSON, parsing and validation
- json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)JSON, parsing and validation
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byteJSON, parsing and validation
- RangeError: Maximum call stack size exceededMemory, async and the process
- Error: error:0308010C:digital envelope routines::unsupportedMemory, async and the process
- CredentialsProviderError: Could not load credentials from any providersMemory, async and the process
- McpError: MCP error -32001: Request timed outMCP servers and clients
- Bad Request: No valid session ID providedMCP servers and clients
- Error executing tool get_orderMCP servers and clients
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.