Mental model
Generative UI (GenUI) shifts AI products from rendering static prose and brittle Markdown tables toward composing live interactive React widgets directly inside conversation streams. Rather than letting models generate executable JavaScript strings cleanly, secure architectures bind structured model tool calls (tool_name + typed arguments) strictly against an application-owned widget registry validated at runtime (Zod), mounting isolated interactive UI cards asynchronously.
Learning outcomes
- Architect safe declarative component-map registries rather than evaluating arbitrary model-generated JSX or HTML strings (
XSS/RCE). - Validate partial and complete streaming tool payloads through strict Zod runtime schemas with graceful skeleton states and fallback error cards.
- Keep main bundle sizes fast (
LCP) while mounting rich charts, payment previews, and forms asynchronously via code-splitting (next/dynamic).
Theory
Asking models to output raw React JSX code or custom HTML string tags inline inside text responses breaks on the first omitted closing bracket and opens catastrophic Cross-Site Scripting (XSS) vulnerabilities whenever untrusted RAG documents inject malicious onClick payloads cleanly into generations! Declarative registry-driven GenUI restricts the model purely to picking pre-authored React widget keys and filling validated JSON props:
| GenUI Implementation Strategy | Runtime Safety (XSS/RCE) | Interactive Richness | Streaming Partial Support | Bundle & Maintenance Profile |
|---|---|---|---|---|
Markdown Inline Tags (<card />) | Low–Medium unless custom XSS AST sanitized | Low (static markdown cards mostly) | Breaks while half-streamed tags arrive | Lightweight; brittle parser maintenance |
Allowlisted Component Map (Tool -> Zod -> React) | Highest (strict fixed React code + sanitized JSON) | Highest (forms, charts, confirmations, state loops) | Native skeleton loading + progressive validation | Clean bundle split via next/dynamic lazy chunks |
Dynamic Server-Compiled / eval() JSX | Unacceptable in multi-tenant apps (RCE/XSS) | Arbitrary layouts | Requires runtime sandboxed iframes | Massive complexity & latency overhead |
Notice two production UX subtleties cleanly handled by deterministic client boundaries: partial argument tolerance during SSE token streaming (rendering crisp skeleton cards cleanly while args.amount arrives token-by-token before Zod finalizes) and stateful round-trip interactions (user picks seat 14A inside <SeatPickerCard /> -> triggers typed client action appending verified selection cleanly to agent state).
tsximport React, { Suspense } from "react";import { z } from "zod";const PaymentPreviewPropsSchema = z.object({invoiceId: z.string().regex(/^INV-\d{4,10}$/),amountCents: z.number().int().positive().max(10_000_000),currency: z.enum(["USD", "EUR", "GBP"]),recipientLabel: z.string().min(1).max(80),});const FlightStatusPropsSchema = z.object({flightCode: z.string().regex(/^[A-Z0-9]{2,3}\d{1,4}$/),gate: z.string().max(8),delayedMinutes: z.number().int().min(0),});type WidgetEntry = {schema: z.ZodTypeAny;Component: React.LazyExoticComponent<React.ComponentType<never>>;};const WIDGET_REGISTRY: Record<string, WidgetEntry> = {render_payment_preview: {schema: PaymentPreviewPropsSchema,Component: React.lazy(() => import("@/components/widgets/PaymentPreviewCard")),},render_flight_tracker: {schema: FlightStatusPropsSchema,Component: React.lazy(() => import("@/components/widgets/FlightTrackerCard")),},};export function SafeGenerativeWidget({ toolName, rawArgs }: { toolName: string; rawArgs: unknown }) {const entry = WIDGET_REGISTRY[toolName];if (!entry) return null; // Ignore unknown or disallowed widget names cleanlyconst parsed = entry.schema.safeParse(rawArgs);if (!parsed.success) {return (<div className="rounded-lg border p-3 text-sm text-amber-700">Validating structured preview details...</div>);}const TargetWidget = entry.Component as React.ComponentType<Record<string, unknown>>;return (<Suspense fallback={<div className="h-24 animate-pulse rounded-lg bg-muted" />}><TargetWidget {...(parsed.data as Record<string, unknown>)} /></Suspense>);}
Trade-offs
Declarative Zod-validated React widget registries deliver silky-smooth multi-modal experiences (date pickers, cost estimators, approval confirmations) while maintaining strict Content Security Policy compliance and small initial JavaScript payloads via React.lazy / next/dynamic. However, designers must build and maintain curated widget schemas deliberately up front rather than relying on improvised layout formatting per query, and widget state callbacks must enforce clear recursion limits so interactive user clicks cannot accidentally bounce infinite tool loops cleanly between client and server.
Failure modes and misconceptions
- Passing Unvalidated Tool JSON Straight to Props (
<Widget {...args} />): Models regularly hallucinate unexpected types (amount: "$500"strings instead of integers) or malformed URLs (javascript:...) triggering runtime React crashes or security bugs unless Zod parses every prop boundary. - Bundling All Rich Widgets Synchronously: Eagerly importing 30 charting, map, and PDF viewer widgets onto the chat page bundle degrades mobile First Input Delay and LCP across simple text sessions.
- Allowing Interactive Widgets to Bypass Backend Authorization: Trusting form submission payloads straight from a client GenUI confirmation card without server-side digest binding enables client manipulation of prices or tenant IDs.
Decision scenario
A fintech payments copilot renders live transfer confirmation widgets (recipient, FX rate, fee, Approve Transfer action) inside SSE chat streams. Design a registry allowlist, strict Zod currency/regex checks (amountCents > 0), lazy chunk loading, and server-side bound approval verification cleanly preventing broken props or client-tampered transfer submissions.
Why is runtime schema validation (e.g. Zod) plus an explicit widget allowlist mandatory before mounting dynamic Generative UI components from model tool calls?