Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Validate & Render Dynamic UI Components Safely

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Dynamically generated UI components—whether from a CMS, an API response, or user configuration—are powerful but risky. Rendering them without validation can expose your app to XSS attacks, broken layouts, and runtime crashes. This guide walks you through a practical, defense-in-depth approach: validating the data structure, sanitizing content, and using safe rendering techniques. You’ll need a basic understanding of JavaScript, React (or a similar framework), and a willingness to treat all external input as untrusted.

What You'll Need

  • A frontend project (React, Vue, Svelte, or vanilla JS) where components are rendered dynamically.
  • Access to your package manager (npm, yarn, pnpm) to install validation and sanitization libraries.
  • Basic knowledge of JSON schema validation (or willingness to learn quickly).
  • Optional: a testing framework (Jest, Vitest) to write unit tests for your validation logic.

Step-by-Step

  1. Define a strict schema for your component data. Before you render anything, decide exactly what fields a component can have. Use a schema validator like Zod, Yup, or JSON Schema. For example, a "button" component might require a label (string, max 50 chars), variant (enum: 'primary' | 'secondary'), and an optional onClick action (string ID referencing a known handler). Write this schema in a shared module so both client and server can use it.
  2. Validate the incoming data at the boundary. When data arrives from an API, CMS, or user input, run it through your schema. Do this as early as possible—ideally in an API route or a data-fetching layer. If validation fails, reject the data (throw an error, return a fallback) rather than trying to render it. Never skip this step, even for data you think is "trusted" (e.g., from your own backend).
  3. Sanitize all string content. Even after schema validation, strings can contain malicious HTML or JavaScript. Use a sanitization library like DOMPurify (for HTML) or sanitize-html. Apply this to any field that will be rendered as HTML (e.g., description , htmlContent ). For plain text fields, escape them automatically by using React's default text rendering or Vue's interpolation—never use v-html or dangerouslySetInnerHTML on unsanitized content.
  4. Map validated data to a whitelist of components. Create a registry object that maps component type strings (e.g., 'button', 'card', 'chart') to actual React/Vue components. After validation, look up the component by its type. If the type isn't in the registry, render a fallback or ignore it. This prevents attackers from injecting arbitrary component names that might trigger unexpected behavior.
  5. Pass only validated props. When rendering, construct the props object from the validated data. Do not spread the entire raw data object into the component—this could pass extra fields that the component doesn't expect, leading to unexpected behavior or security issues. Instead, explicitly pick the fields your schema allows.
  6. Handle actions and events safely. If your components can trigger actions (e.g., button clicks), don't accept raw JavaScript function strings. Instead, define a set of allowed action IDs (like 'submitForm', 'openModal') and map them to actual functions in your code. When rendering, pass the action ID as a prop, and have the component call a dispatcher that looks up the function. Never use eval() or new Function() on any string from the data.
  7. Add error boundaries and fallbacks. Even with validation, a component might throw at runtime (e.g., a chart library fails to load). Wrap each dynamic component in an error boundary (React) or use a similar mechanism (Vue's errorCaptured). If an error occurs, show a generic placeholder instead of crashing the whole page.
  8. Test your validation and rendering. Write unit tests for your schema: valid data passes, invalid data is rejected, malicious strings are sanitized. Also test the rendering layer: unknown component types are ignored, and actions are correctly mapped. Run these tests in your CI pipeline to catch regressions.
  9. Log and monitor failures. When validation fails or an error boundary catches an exception, log it (with appropriate context, but no sensitive data). This helps you spot patterns—maybe a third-party API changed its response shape, or a user is trying to inject bad data.

Common Mistakes

  • Trusting data because it came from your own backend. Your backend can be compromised, or a developer might accidentally store unsanitized data. Always validate at the client boundary.
  • Using dangerouslySetInnerHTML or v-html without sanitizing. This is the most common XSS vector. If you must render HTML, sanitize it first with DOMPurify.
  • Only validating the component type, not the props. An attacker might send a valid type like 'button' but with a label containing script tags. Validate every field.
  • Spreading raw data into components. This can pass unexpected props that a component might use in unsafe ways (e.g., a prop that sets innerHTML).
  • Ignoring validation errors. If you just skip invalid components silently, you might miss legitimate issues. At minimum, log them.

Tips

  • Use a schema library that can infer TypeScript types. Zod, for example, gives you both runtime validation and compile-time types, reducing drift.
  • Keep your component registry in one file. This makes it easy to audit what components are allowed and ensures consistency.
  • Sanitize on the server too. If you control the backend, sanitize before storing data. This adds a second layer of defense.
  • Consider using a UI framework that enforces safe rendering by default. React escapes text by default, but you still need to avoid dangerouslySetInnerHTML.
  • Use a Content Security Policy (CSP). Even with sanitization, a CSP that blocks inline scripts and eval can stop many attacks.

Troubleshooting

  • My component renders but looks broken. Check if the data has extra fields that your component doesn't expect. Use your schema to strip unknown fields, or log the raw data to see what's coming in.
  • I'm getting a validation error for data that used to work. Your API likely changed its response shape. Check the API docs and update your schema accordingly. Add a fallback to a default component if you want to be resilient.
  • XSS still possible? Double-check that you're sanitizing every string that goes into HTML. Also ensure you're not using eval() or new Function() anywhere. Review your CSP headers.
  • Error boundary catches errors but the page goes blank. Make sure you're rendering a fallback UI, not just catching the error. Also, check that your error boundary itself doesn't throw.
  • Performance is slow with many dynamic components. Consider lazy-loading components (React.lazy) and memoizing the validation results if the same data is used repeatedly.

Frequently Asked Questions

  1. Do I need to validate if I'm using a typed language like TypeScript? TypeScript only checks at compile time; it doesn't validate runtime data from external sources. You still need runtime validation.
  2. Can I use v-html in Vue if I sanitize with DOMPurify? Yes, but it's safer to avoid it altogether. If you must, sanitize the string with DOMPurify before passing it to v-html.
  3. What's the difference between sanitization and validation? Validation checks that data conforms to a schema (types, required fields). Sanitization cleans the data to remove dangerous content (like script tags). You need both.
  4. Should I validate on the client or server? Both. Server-side validation is essential for security, but client-side validation improves UX and reduces unnecessary network requests.
  5. What if my component data includes nested components? Recursively validate and render each level using the same schema and registry approach. Ensure your schema handles nesting with a children array.
  6. Is it safe to render HTML from a WYSIWYG editor? No, not without sanitization. WYSIWYG editors often allow pasting arbitrary HTML. Always sanitize with DOMPurify and configure it to allow only safe tags and attributes.