How to Safely Parse Dynamic JSON Config in React
2025-04-03
CMS blocks and feature flags often arrive as JSON. Untrusted JSON is as risky as untrusted code if you eval or skip validation.
Threat model
__proto__ pollution; no dangerouslySetInnerHTML from JSON strings; never eval(config).
Safe pipeline
fetch → JSON.parse → zod/JSON Schema → map to props with defaults.
const ConfigSchema = z.object({ theme: z.enum(["light", "dark"]) });
const config = ConfigSchema.parse(JSON.parse(raw));Storage
Validate localStorage JSON too; version field for schema migrations.
TypeScript
Types help at compile time; runtime still needs zod.parse for remote data.