The error **“Cannot read properties of undefined (reading length)”** means the value before .length is missing at that moment. With API data, check the HTTP response, parse the body, and validate the expected array before rendering it.
Last updated: November 13, 2026.
async function loadProducts() {
const response = await fetch('/api/products', {
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`Products request failed: HTTP ${response.status}`);
}
const payload = await response.json();
const products = Array.isArray(payload) ? payload : payload?.products;
if (!Array.isArray(products)) {
throw new TypeError('Expected an array of products');
}
document.querySelector('#product-count').textContent = String(products.length);
return products;
}
loadProducts().catch((error) => {
console.error(error);
document.querySelector('#product-count').textContent = 'Unavailable';
});An empty array is a valid successful result with length zero. A missing or incorrectly typed products field is a response-contract error and should not be disguised as an empty list.
Validate each stage separately
The MDN Fetch guide notes that fetch() does not reject merely because the server returned an HTTP error such as 404 or 500. Check response.ok before reading the body. Parsing is also asynchronous, so await response.json() before accessing fields.
The Response.json documentation explains that parsed JSON can be an object, array, string, number, or another JSON value. Successful parsing therefore does not prove that the application received the shape it expects.
Avoid hiding contract failures
Optional chaining can prevent one immediate exception, but payload?.products?.length ?? 0 turns malformed data into a believable zero. Use Array.isArray() where an array is required, and validate important item fields before rendering them into the page.
Show separate user states for loading, a valid empty result, and a failed request. Log safe diagnostic details such as status and request ID, not authorization headers or sensitive response bodies. Add tests for HTTP errors, invalid JSON, a missing property, a non-array property, an empty array, and a normal populated response. This keeps the UI predictable when the API contract changes.