How I Build Generative UI with LangGraph and React
A practical example of Generative UI using a shopping assistant: LangGraph understands the request, the backend searches real product data, and React renders safe, reusable components such as product cards and purchase confirmation.
On this page
Generative UI sounds more complicated than it needs to be.
The basic idea is simple: sometimes text is not the best answer.
If I ask an AI assistant:
Show me wireless headphones under $150 with good battery life.
I would rather see a small product grid with an image, price, rating, battery life, and an Add to Cart button than receive a long paragraph describing five products.
That is where Generative UI becomes useful.
The model can understand what the user wants, the backend can fetch real product data, and the frontend can choose a useful component to show it.
The important part is that I still want this to behave like a normal web application. I do not want the model generating arbitrary JSX and sending executable UI code to the browser.
I prefer a much simpler split:
The model understands the request. LangGraph manages the workflow. The backend calls trusted tools and prepares the data. React renders components that already exist in the application.
A shopping assistant is a good example because the frontend and backend responsibilities are easy to see.
Start with a normal frontend and backend boundary
Suppose the user asks:
Show me wireless headphones under $150 with good battery life.
There are a few steps behind that simple request.
The model needs to understand that the user wants a product search. The backend needs to search the real product catalog. The result needs to be converted into something the frontend understands. React then renders a product grid.
If the user clicks Add to Cart, that action goes back to the backend. The server checks the current product, price, stock, and user session before changing the cart.
I think about the responsibilities like this.
The model is good at understanding natural language and choosing what should happen next.
The backend owns real data, authentication, permissions, tools, business rules, LangGraph state, and side effects.
React owns rendering and browser interaction.
That separation is useful because the AI does not become the source of truth for the product catalog or the shopping cart.
Let the model return intent, not JSX
For the planning step, I prefer structured output.
The model can turn a natural-language request into a small object that the application understands.
import * as z from "zod";const ShoppingPlanSchema = z.object({ intent: z.enum([ "search_products", "add_to_cart", "compare_products", ]), category: z.string().optional(), maxPrice: z.number().optional(), feature: z.string().optional(),});const planner = model.withStructuredOutput(ShoppingPlanSchema);const plan = await planner.invoke( "Show me wireless headphones under $150 with good battery life",);A possible result could be:
{ "intent": "search_products", "category": "wireless headphones", "maxPrice": 150, "feature": "good battery life"}This is a good job for the model. It understands the request without needing to know anything about the implementation of the React application.
What I would avoid is asking the model to return something like:
<ProductGrid products={...} />Now the prompt knows about frontend component names and props. The model can invent product data, component changes become prompt changes, and generated output starts getting too close to executable application code.
I would rather keep the model focused on intent.
The backend fetches the real products
Once LangGraph has the plan, a backend node can call the product catalog.
The model might say the user wants wireless headphones under $150, but it should not invent the actual products or prices.
Those come from the server.
async function searchProducts( state: ShoppingState, config: GraphConfig,) { const context = requireExecutionContext(config); const products = await productService.search({ userId: context.userId, category: state.plan.category, maxPrice: state.plan.maxPrice, feature: state.plan.feature, }); const event = UiEventSchema.parse({ version: 1, id: `products:${state.runId}`, revision: state.uiRevision + 1, component: "product_grid", props: { title: "Wireless headphones under $150", products: products.map((product) => ({ id: product.id, name: product.name, price: product.price, rating: product.rating, batteryHours: product.batteryHours, imageUrl: product.imageUrl, inStock: product.stock > 0, })), }, }); config.writer?.(event); return { uiRevision: event.revision, };}This is where I want the final UI data to be created.
The backend can also decide which fields are safe and useful for the browser. The catalog service may return supplier IDs, internal margins, warehouse data, or other information that should never be included in the UI response.
The frontend only gets what it needs.
Keep the UI contract small
The browser needs a simple contract that says which component to render and which props it receives.
I prefer a small set of known components rather than a generic layout language.
const ProductGridEvent = z.object({ version: z.literal(1), id: z.string(), revision: z.number().int().nonnegative(), component: z.literal("product_grid"), props: z.object({ title: z.string(), products: z.array(ProductCardSchema), }),});const PurchaseConfirmationEvent = z.object({ version: z.literal(1), id: z.string(), revision: z.number().int().nonnegative(), component: z.literal("purchase_confirmation"), props: z.object({ productId: z.string(), productName: z.string(), total: z.number(), }),});export const UiEventSchema = z.discriminatedUnion("component", [ ProductGridEvent, PurchaseConfirmationEvent,]);The id and revision are useful when the UI is streamed.
If the same component is updated several times, the frontend can keep the newest revision and ignore older events that arrive late after a reconnect.
I also keep a version on the contract because the frontend and backend will change over time. Generative UI still has the same compatibility problems as any other API.
React renders components we already own
On the frontend, I keep a small component registry.
function GeneratedComponent({ event, onAction,}: { event: UiEvent; onAction: (action: UiAction) => void;}) { switch (event.component) { case "product_grid": return ( <ProductGrid title={event.props.title} products={event.props.products} onAddToCart={(productId) => onAction({ type: "add_to_cart", productId, }) } /> ); case "purchase_confirmation": return ( <PurchaseConfirmation {...event.props} onConfirm={() => onAction({ type: "confirm_purchase", productId: event.props.productId, }) } /> ); }}The interesting part is that the selection can be generative while the component itself stays completely normal.
The AI may decide that a product grid is more useful than a paragraph. But ProductGrid is still a React component written and tested by the product team.
It can use the normal design system, responsive styles, loading states, analytics, and accessibility behavior.
The model is not generating buttons, event handlers, or arbitrary JavaScript.
If the backend sends a component name that does not exist in the registry, the frontend simply does not render it.
That is much easier to reason about than rendering arbitrary model-generated UI code.
React state and LangGraph state are different
There are several kinds of state in this example.
LangGraph may keep the user's current request, the selected products, the current workflow step, and whether the flow is waiting for confirmation.
The product database owns the real price and stock.
The cart service owns the real cart.
React owns temporary browser state such as which product details are expanded or whether an Add to Cart button is showing a loading state.
I do not try to put all of this into LangGraph or all of it into React.
For example, the product card might say inStock: true. That is useful for the UI, but I would still check stock again when the user actually adds the product to the cart.
The browser may be looking at data from ten seconds ago. The backend should make the final decision using current data.
Add to Cart still goes through the backend
A generated button should behave like any other button in an e-commerce application.
When the user clicks Add to Cart, the browser sends the product ID to the backend.
The server loads the current product and validates the action.
async function addToCart( productId: string, session: AuthenticatedSession,) { const product = await productRepo.get(productId); if (!product || product.stock <= 0) { throw new Error("This product is no longer available"); } return cartService.addItem({ userId: session.userId, productId: product.id, price: product.price, quantity: 1, });}Notice that I do not trust the price from the card that was already rendered in the browser.
The backend uses the current product price.
This protects the application from stale UI and also keeps the browser from becoming a security boundary.
LangGraph becomes useful when the flow needs more than one step
A simple product search does not need a complicated agent workflow.
LangGraph becomes more useful when the user continues the conversation.
For example:
Compare the first two.
Then:
Add the second one to my cart.
Then:
Buy it.
Now the application needs to keep some conversational state and move through several steps.
For the final purchase, I would normally require a confirmation before charging anything.
LangGraph's interrupt() works well for that kind of pause.
import { interrupt } from "@langchain/langgraph";function confirmPurchase(state: ShoppingState) { const decision = interrupt({ type: "purchase_confirmation", productId: state.product.id, productName: state.product.name, total: state.checkoutTotal, }); return { purchaseDecision: decision, };}The frontend can turn this into a normal confirmation card:
Sony WH-1000XM6Total: $149[Confirm purchase] [Cancel]When the user confirms, the backend resumes the same LangGraph thread using Command and the same thread_id.
The important part is that the workflow does not depend on one browser connection staying open forever.
A user can refresh the page or lose the network connection and the backend can still know that the shopping workflow is waiting for confirmation.
That is one reason persistent graph state is useful.
I use the same idea for longer-running agent interfaces, which I covered in Streaming an Agent Is a State-Management Problem, Not a Typing Effect.
Streaming should be simple for the frontend
LangGraph can stream model messages, graph updates, and custom events.
I usually do not expose all of those internal events directly to React.
The frontend only needs product-level information such as:
- searching for products;
- product grid ready;
- comparison ready;
- waiting for confirmation;
- item added to cart;
- purchase completed;
- something failed.
The backend can translate graph activity into those simpler UI events.
I also keep text streaming separate from component updates.
Text tokens may arrive many times per second. A product grid only needs to update when the product data changes.
Mixing both into one giant React state object creates unnecessary rendering work.
Stable component IDs and revisions also make reconnects easier. If the same event is received twice, the frontend can safely ignore the duplicate or older revision.
Security does not become special because AI is involved
Most of the security rules here are normal web application rules.
The backend still owns the authenticated user. It still checks product availability. It still uses the real price. It still protects payment credentials. It still validates every action.
The model should never be able to say:
{ "userId": "another-user", "price": 1, "isAdmin": true}and have the server trust those values.
The model can help decide that the user wants to buy a product. The application decides whether the action is valid and what data should be used to perform it.
This is the same principle I use for tool-using agents and RAG systems generally: the model can propose an action, but trusted application code decides what is actually executable.
I covered those broader boundaries in Building Production-Ready RAG & AI Agent Systems with TypeScript, LangChain and LangGraph.
What I would ship first
For a first version, I would keep the component set small.
Maybe the assistant only knows how to render a product grid, comparison table, cart summary, and confirmation card.
That is already enough to make the experience much better than plain chat for a shopping use case.
I would validate every UI event, keep product and cart actions on the backend, and use persistent LangGraph state only for flows that actually need to continue across several steps.
I would also test the UI contract without using an LLM.
An unknown component should fail validation. An old component revision should not replace a new one. An out-of-stock product should not be added to the cart even if the browser still shows it as available. A purchase confirmation should not charge the user twice if the same request is retried.
Then I would add an end-to-end test around the real flow:
Ask for headphones, render the product grid, click Add to Cart, ask to buy the product, show the confirmation card, confirm it, resume the same LangGraph thread, and verify that the purchase runs once.
Those tests tell me whether the system works as a product, not just whether the model can produce a nice response.
Final thought
This is the version of Generative UI that makes the most sense to me.
The model does not generate the application.
It understands what the user is asking for and helps choose the right interface.
LangGraph manages the workflow when the conversation has multiple steps. The backend fetches real data and performs real actions. React renders components the application already owns.
For a user, the experience can still feel very dynamic. They ask for headphones and get product cards. They ask for a comparison and get a comparison view. They decide to buy something and get a confirmation card.
But underneath that experience, the system still looks like a normal, maintainable web application.
That is exactly what I want.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article