Validate the response shape
Never trust the shape of data. Check it before you use it.
AJAX · Validate the response shapeAdvanced
function isUser(x) {
return x && typeof x === 'object'
&& Number.isInteger(x.id)
&& typeof x.name === 'string'
&& (x.email === undefined || typeof x.email === 'string');
}
async function getUser(id) {
const data = await (await fetch('/api/users/' + id)).json();
if (!isUser(data)) throw new Error('Unexpected response from server');
return data;
}validationschemadefensivejson