We want our Next.js components to degrade cleanly when API fields are missing instead of crashing. Normally, if an API call fails and returns an empty object or missing keys, components break unless you litter your code with question marks (data?.feature?.isHidden).
What if API results were just safe objects to begin with? You can wrap normalized API responses in a small JavaScript Proxy with explicit defaults:
const defaultValues = {
isHidden: false,
};
function createSafeObject(obj = {}, defaults = {}) {
return new Proxy(obj, {
get: (target, prop) =>
prop in target
? target[prop]
: prop in defaults
? defaults[prop]
: null,
});
}
Then components read properties normally without cluttering JSX with fallbacks:
const safeData = createSafeObject(apiResult, defaultValues);
const isHidden = safeData.isHidden; // returns false when omitted
const missing = safeData.unknownKey; // returns null instead of undefined
One tradeoff before using this everywhere: Proxy wrappers can surprise deep-equality checks or serialization if nested objects are not wrapped too, and TypeScript with DTO mappers makes missing fields explicit at the boundary. Still, in plain JS components it cuts out a lot of crashes in ten lines.