A catalog that worked yesterday now crashes on items.map(). The request succeeded, and the JSON was parsed. But the service sent{"items":null}, and the page was expecting {"items":[]}. Both are valid JSON. Only one fits this page.
Check the shape just after parsing and before you hand the data to the page. In the JavaScript example below, invalid JSON stops at the parser. A well-formed response with the wrong stock value makes it as far as the validator, which names items[0].stock.quantity so you know what to inspect. A zero quantity and an empty result both get through. You can run all of those cases in Node.js without installing a package.
Decide what the catalog promises
Start with what the page does. This catalog loops throughitems, uses each item’s string id to identify a row, and displays stock.quantity. The service might also send a price, a category, or an image. You can leave those fields out of the checks because this view never uses them. Write down the parts of the response that need to work every time.
The top-level value must be an object, with an own items property containing an array.
Each element must be an object with an own id property containing a string with at least one non-whitespace character.
Each element must have its own stock object, with its own quantity field.
Quantity must be a nonnegative safe integer. Zero represents an item that is in the catalog and currently out of stock.
An empty items array passes. Additional properties pass too, including a top-level cursor or a field added to a product later.
Here is the smallest example with one item. A catalog can return a richer object and still satisfy this contract.
Imagine using this catalog to search for a pencil. Withitems: [], you can tell the shopper the search matched nothing. With no items field at all, you still need to investigate. The client might have reached the wrong endpoint or the service might have shipped a new response format. A fallback such as value.items ?? [] makes those two situations look identical at the point where you most need to tell them apart.
New optional fields deserve a different decision. If the service adds a pagination cursor tomorrow, the catalog view can keep working with the same checks. Reject an unfamiliar field when the agreed contract calls for that strictness. If you plan to forward or store the data, decide which fields belong in that next step. You can construct a smaller object with only those fields before passing it on.
Write the JavaScript validator
Save this as catalog.mjs. Give raw text to readCatalog so it can distinguish a syntax failure from a shape failure. If you already have a parsed value, call validateCatalog directly. That function returns the path and reason for the first problem it finds, or null when the value can go on to the catalog.
A path such as `items[0].stock.quantity` points directly to the nested value that failed.
export function validateCatalog(value) {
if (!isRecord(value)) return "$ must be an object";
if (!Object.hasOwn(value, "items") || !Array.isArray(value.items)) {
return "items must be an array";
}
for (const [index, item] of value.items.entries()) {
const path = `items[${index}]`;
if (!isRecord(item)) return `${path} must be an object`;
if (!Object.hasOwn(item, "id") || !isNonBlankString(item.id)) {
return `${path}.id must be a nonblank string`;
}
if (!Object.hasOwn(item, "stock") || !isRecord(item.stock)) {
return `${path}.stock must be an object`;
}
if (
!Object.hasOwn(item.stock, "quantity") ||
!Number.isSafeInteger(item.stock.quantity) ||
item.stock.quantity < 0
) {
return `${path}.stock.quantity must be a nonnegative safe integer`;
}
}
return null;
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isNonBlankString(value) {
return typeof value === "string" && value.trim().length > 0;
}
export function readCatalog(source) {
let value;
try {
value = JSON.parse(source);
} catch (error) {
if (!(error instanceof SyntaxError)) throw error;
return { ok: false, stage: "syntax", message: "Invalid JSON text" };
}
const issue = validateCatalog(value);
return issue
? { ok: false, stage: "shape", message: issue }
: { ok: true, data: value };
}
Read the checks in the same order you would follow the field in DevTools. First find the root object and its list. Then check each row before touching its identifier or stock. Only read quantity after confirming that stock is an object. If stock is missing in the third row, the error has enough context to send you straight to items[2].stock. The validator never needs to read quantity from an undefined value to discover the problem.
A check using only typeof leaves a hole here. Both typeof null and typeof [] produce"object", so isRecord rules out null and arrays separately. That is sufficient for the object check in this example because the values came from JSON. Arbitrary JavaScript inputs can also contain dates or accessors. Decide what to accept before sharing this helper with a caller that can supply those values.
Object.hasOwn makes required properties explicit. If a caller later passes a JavaScript object from outside the parser, an inherited property alone won’t satisfy the check. The same reasoning applies at each nested level. This function validates the parsed value as it exists. It does not normalize the identifier or copy the object.
The quantity check also has a deliberate second condition. Number.isSafeInteger Returns false for a numeric string, a fraction, and numbers outside the safe integer interval. A negative integer can still pass that method, so the next condition rejects it. The signed value -0 passes this check as zero. If inventory identifiers or counts genuinely require integers above the safe range, ask the producer for a string representation and validate that contract directly. JavaScript numbers can already lose precision during ordinary parsing. MDN’s safe integer reference explains the representable range.
Run the same checks against eleven inputs
Save the following as check.mjs beside the validator. Run node check.mjs from that folder. There are no packages to install. The test uses strict assertions for the outcome and checks that accepted values match what the JSON parser returned.
Node.js v22.23.5 test results show that numeric zero passed and a string in the same field failed the shape check.
import { deepStrictEqual, strictEqual } from "node:assert";
import { readCatalog } from "./catalog.mjs";
const cases = [
["valid", '{"items":[{"id":"pen","stock":{"quantity":0}}]}', "ok"],
["empty list", '{"items":[]}', "ok"],
["extra field", '{"items":[],"cursor":"next"}', "ok"],
["broken JSON", '{"items":', "syntax: Invalid JSON text"],
["null root", "null", "shape: $ must be an object"],
["missing items", "{}", "shape: items must be an array"],
[
"missing stock",
'{"items":[{"id":"pen"}]}',
"shape: items[0].stock must be an object",
],
[
"wrong nested type",
'{"items":[{"id":"pen","stock":{"quantity":"0"}}]}',
"shape: items[0].stock.quantity must be a nonnegative safe integer",
],
[
"later item",
'{"items":[{"id":"pen","stock":{"quantity":0}},{"id":" " }]}',
"shape: items[1].id must be a nonblank string",
],
[
"negative quantity",
'{"items":[{"id":"pen","stock":{"quantity":-1}}]}',
"shape: items[0].stock.quantity must be a nonnegative safe integer",
],
[
"unsafe integer",
'{"items":[{"id":"pen","stock":{"quantity":9007199254740993}}]}',
"shape: items[0].stock.quantity must be a nonnegative safe integer",
],
];
console.log(`Node ${process.version}`);
for (const [label, source, expected] of cases) {
const result = readCatalog(source);
const actual = result.ok ? "ok" : `${result.stage}: ${result.message}`;
strictEqual(actual, expected, label);
if (result.ok) deepStrictEqual(result.data, JSON.parse(source));
console.log(`${label} -> ${actual}`);
}
console.log(`PASS ${cases.length}/${cases.length}`);
The cases passed on Node.js v22.23.5. In particular, a valid row with zero quantity passed, and the otherwise identical row with quantity "0" failed at items[0].stock.quantity. A two-row fixture passes its first row and flags the identifier on the second one. That catches a mistake you can miss when you only test a single object or validate items[0].
If one service release sends quantity as a string in every row, the first failure gives you enough to start debugging. That is why the guard stops early. You might make a different choice for a form or a migration report, where someone can fix several problems in one pass. Return a list of issues for those tasks and set a limit on the amount of input or the number of errors you report. Otherwise, a single format change can produce hundreds of near-identical diagnostics.
Put the check after Fetch has parsed the body
With Fetch, you usually start by checking whether the HTTP response was successful. Then call await response.json(), pass the resulting value to validateCatalog and release it to the view only if there is no issue. Calling readCatalog after response.json() would try to parse an already parsed JavaScript value. Use readCatalog when you intentionally have a string, such as file contents or await response.text().
There are three useful places to stop. If response.ok is false, the endpoint gave an HTTP failure, and you can preserve the status code separately. If reading or parsing the response body fails, there is no parsed catalog to check. If JSON parsing succeeds but the validator returns a field path, fix the mismatch between the data producer and the consumer. The Response.json() reference describes body-read and parsing exceptions. If you are already seeing an end-of-input error, start with how to fix Unexpected End of JSON Input in Fetch and come back to shape validation after the parser succeeds.
The shopper can see a short explanation and a way to try again. Put the endpoint, stage, and field path in your internal log, where someone can use them to debug. A request ID can help you match that entry to the corresponding service call when different client and server versions are in play. You generally need only a few invented values to reproduce the problem in a ticket. Leave the raw response out.
Keeping the guard beside the request also gives every rendering path the same guarantee. After a successful result, the view can loop through items without repeating the array check. If a second route hands you a different structure, adapt it separately. Once a guard accepts two unrelated shapes as if they meant the same thing, a field path becomes harder to interpret when something fails.
Leave a regression fixture beside that decision. If you later upgrade the server runtime, keep shape tests separate from tests of the transport itself. A runtime test can show that Fetch follows a redirect or returns the expected HTTP status. The shape test still needs to exercise a completed response with a broken field. The CyboGeek Node Fetch migration fixture is a starting point for transport checks.
Pick the strictness that matches this endpoint
Required, nullable, and optional are different
A required field must be present. A nullable field can explicitly be null. An optional field can be absent. A field can be both nullable and optional if the service intends that, but each version needs a meaning. Decide all three from the endpoint contract and its consumer. For the example, stock is required and must be an object. You could define a different API where stock: null means the supplier has not reported inventory. The view would then need an explicit “stock unknown” display separate from any numeric quantity.
Do the same for strings. An empty string may be valid for a description. Here it cannot identify a row. The identifier test uses trim() to check that there is meaningful content, but it returns the original string. If you want to normalize identifiers, do it as an explicit transform, then test whether values that were previously distinct become equal.
Choose when to coerce a field
The number 0 and the string "0" are different inputs. This example rejects the string because accepting it would hide a format change. If the API explicitly promises numeric strings, handle those strings deliberately and keep a fixture for blank text, signs, unwanted fractional values, and out-of-range quantities. Letting generic number conversion make the decision can accept values you did not intend to accept, such as blank strings converting to zero.
Validate key rules separately when they matter
Passing this validator tells you that every item contains the values the view expects. The check does not enforce that identifiers are unique across the list. If your interface depends on unique keys, add a test with two rows using the same identifier, track seen keys, and return an issue that identifies the second occurrence. Part of keeping this validator readable is choosing rules you can explain and demonstrate with an input.
Use a schema when you start repeating the rules
A short handwritten guard is easy to read when one view needs a few fields. The trade-off changes if you handle several nested response types, maintain identical rules in different services, or need a consistent format for every issue. Libraries make it practical to keep those rules in a definition. Zod’s basic usage guide covers schema parsing and issue paths. Ajv’s getting-started guide covers compiling reusable validation functions when the team already shares JSON Schema.
When you make that move, keep the original failure fixtures. Change only the implementation behind them and verify that the new library handles extra keys, empty results, and number types according to your contract. A type declaration alone cannot make such runtime decisions. In TypeScript, marking parsed data as unknown can help enforce a check before use, but the check still has to run.
When you wire this into your own project, save a shareable sample from the endpoint and keep the fields the view actually reads. Break one field, run it through the same path as a successful response, and check that the failure names the value you changed. Repeat that with a valid empty response. It should still reach the view, ready to show that the catalog has no rows to display.