Programming · free software · the open webSubscribe via RSS

Why Should a Web Client Validate Server Responses?

From the earlier reference collection. Read the current software blog.

A successful network response can still contain missing, mistyped, or unexpected data. Validate its shape before using it in application logic.

A response is external input

A web client should treat server data as input, even when the server belongs to the same organization. Deployments can be out of sync, an endpoint can change, and a response can contain an error payload instead of the expected object. A successful transport status only says something about the request exchange; it does not prove that every field is usable.

If the client assumes response.temperature is always a number, a missing field may become an undefined value and cause a confusing display or calculation. Explicit checks let the application handle the problem at the boundary.

Check shape and types

Before reading fields, confirm that the top-level value has the expected structure. For a list endpoint, verify that the response contains an array; for each item, check required fields and their runtime types. Also validate allowed values, ranges, and formats where the application relies on them.

For example, a transit display might require each arrival item to have a stop identifier, route label, and time string. If the identifier is absent, the client can skip or flag that item rather than rendering a broken link. If the time is malformed, it should not be quietly interpreted as a valid arrival.

Handle incompatibility intentionally

Validation should lead to a deliberate outcome. The client might show an unavailable state, preserve cached information with a freshness label, or report a structured error for diagnostics. Avoid converting every invalid value to a plausible default: displaying zero for an unknown reading can mislead users into thinking a real measurement was observed.

Error messages should help developers locate the failing endpoint or field without exposing private data. If a response contains optional fields, distinguish them from required ones and specify what the client does when they are absent.

Keep checks aligned with the contract

A schema or validation function can centralize the expected response shape, making it easier to update when the server contract changes. Tests should include valid examples and representative failures: wrong types, missing required keys, empty collections, and unfamiliar enum values. These examples clarify what the interface promises and how the UI responds when it is violated.

Validation does not replace server-side checks, and it cannot establish that a well-formed value is factually correct. It does keep unexpected data from flowing unchecked into rendering and application logic. Validate once at the boundary, then let the rest of the client work with a representation whose assumptions are explicit.

Suggest a correction · All posts