Part III — Advanced Systems · Chapter 15 · Lesson 4 of 7 · 7 min read
Lesson 4: TypeScript Client and React Integration
Lesson level: Advanced
Purpose: Call PeaLang rules from TypeScript with types derived from the contract, and present rule results in React without trusting the browser for final decisions.
Learning objectives
By the end of this lesson you will be able to:
- derive TypeScript types and runtime validators from a contract;
- write a server-side TypeScript client for the sidecar;
- expose rule results to a React front end through your own API;
- handle loading, error, and stale states in React components;
- avoid exposing sidecar tokens or rule internals to the browser; and
- explain why browser-side results are advisory only.
4.1 Where TypeScript runs
TypeScript appears in two very different places. On a Node.js server, it is a trusted host that can call the sidecar with a secret token. In the browser, it is untrusted: anything it receives can be read, and anything it sends can be forged. Keep this distinction in every design decision in this lesson.
The rule of thumb is simple: the browser calls your API, your API calls the sidecar, and only your server decides prices.
4.2 Types from the contract
Generate types and validators from the contract file with a schema library such as Zod. The type describes the shape at compile time; the schema checks the shape at run time.
// src/pricing/contract.ts (generated from pricing.contract.toml)
import { z } from "zod";
export const LineItem = z.object({
sku: z.string().max(32),
qty: z.number().int().min(1).max(999),
price: z.number().min(0),
});
export const QuoteInput = z.object({
customer_id: z.string().regex(/^C[0-9]{6}$/),
currency: z.enum(["EUR", "GBP", "USD"]),
items: z.array(LineItem).min(1).max(200),
});
export const QuoteOutput = z.object({
subtotal: z.number().min(0),
discount_pct: z.number().min(0).max(30),
reason: z.enum(["NONE", "GOLD_100", "BULK_250"]),
});
export type QuoteInput = z.infer<typeof QuoteInput>;
export type QuoteOutput = z.infer<typeof QuoteOutput>;
Because the type is inferred from the schema, the two cannot disagree. A TypeScript type alone would compile happily against a response that does not match it at run time.
4.3 A server-side client
// src/pricing/client.ts (Node.js only)
import { QuoteInput, QuoteOutput } from "./contract";
export class PricingError extends Error {
constructor(public code: string, public retryable: boolean) { super(code); }
}
const BASE = process.env.PEA_SIDECAR_URL ?? "http://127.0.0.1:7071";
const TOKEN = process.env.PEA_SIDECAR_TOKEN ?? "";
export async function quote(input: QuoteInput, requestId: string): Promise<QuoteOutput & { version: string }> {
const args = QuoteInput.parse(input);
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 150);
try {
const res = await fetch(`${BASE}/v1/modules/pricing/exports/quote`, {
method: "POST",
headers: {
Authorization: `Bearer ${TOKEN}`,
"Content-Type": "application/json",
"X-Request-Id": requestId,
},
body: JSON.stringify({ args: [args] }),
signal: ctrl.signal,
});
const body = await res.json();
if (!res.ok) {
throw new PricingError(body?.error?.code ?? "UNKNOWN", res.status === 503);
}
const result = QuoteOutput.safeParse(body.result);
if (!result.success) throw new PricingError("INVALID_DECISION", false);
return { ...result.data, version: String(body.module_version) };
} catch (e) {
if (e instanceof PricingError) throw e;
throw new PricingError("SIDECAR_UNAVAILABLE", true);
} finally {
clearTimeout(timer);
}
}
The token is read from the server environment and never appears in code that ships to a browser. Note that QuoteInput.parse throws a validation error for bad input; catch it in the route below and return 400 so caller mistakes are not mistaken for an unavailable sidecar.
4.4 Your API route
// src/routes/quote.ts (Express)
import { Router } from "express";
import { randomUUID } from "node:crypto";
import { ZodError } from "zod";
import { quote, PricingError } from "../pricing/client";
import { cartFromSession } from "../cart";
export const router = Router();
router.post("/api/quote", async (req, res) => {
const requestId = randomUUID();
try {
const cart = await cartFromSession(req); // server-side cart, not req.body
const q = await quote(cart, requestId);
res.json({ subtotal: q.subtotal, discountPct: q.discount_pct,
reason: q.reason, requestId });
} catch (e) {
if (e instanceof ZodError) return res.status(400).json({ code: "INVALID_CART", requestId });
if (e instanceof PricingError && e.retryable)
return res.status(503).json({ code: "PRICING_UNAVAILABLE", requestId });
req.log?.error({ requestId, code: (e as PricingError).code });
res.status(502).json({ code: "PRICING_ERROR", requestId });
}
});
The route builds the cart from server-side session state, not from the request body. A browser can send any prices it likes; it cannot change what the server already knows about the cart. The response omits module_version and usage data: they help operators, not shoppers.
4.5 A React hook for quotes
// web/src/useQuote.ts
import { useEffect, useRef, useState } from "react";
type Quote = { subtotal: number; discountPct: number; reason: string };
type State =
| { status: "loading" }
| { status: "ready"; quote: Quote }
| { status: "unavailable" }
| { status: "error"; requestId?: string };
export function useQuote(cartVersion: number): State {
const [state, setState] = useState<State>({ status: "loading" });
const latest = useRef(0);
useEffect(() => {
const call = ++latest.current;
setState({ status: "loading" });
fetch("/api/quote", { method: "POST", credentials: "same-origin" })
.then(async (res) => {
const body = await res.json();
if (call !== latest.current) return; // ignore stale responses
if (res.ok) setState({ status: "ready", quote: body });
else if (res.status === 503) setState({ status: "unavailable" });
else setState({ status: "error", requestId: body.requestId });
})
.catch(() => call === latest.current && setState({ status: "unavailable" }));
}, [cartVersion]);
return state;
}
The latest counter prevents a slow response for an old cart from overwriting the quote for the current cart, a common bug when shoppers change quantities quickly.
// web/src/QuoteSummary.tsx
export function QuoteSummary({ cartVersion }: { cartVersion: number }) {
const q = useQuote(cartVersion);
if (q.status === "loading") return <p aria-busy="true">Calculating your price…</p>;
if (q.status === "unavailable") return <p>Prices are being updated. Please try again shortly.</p>;
if (q.status === "error") return <p>We couldn't price your cart (ref {q.requestId}).</p>;
const { subtotal, discountPct, reason } = q.quote;
return (
<dl>
<dt>Subtotal</dt><dd>{subtotal.toFixed(2)}</dd>
{discountPct > 0 && (<><dt>Discount</dt><dd>{discountPct}% ({REASON_TEXT[reason]})</dd></>)}
</dl>
);
}
const REASON_TEXT: Record<string, string> = {
NONE: "", GOLD_100: "Gold member offer", BULK_250: "Bulk order saving",
};
Reason codes are mapped to shopper-friendly text in the front end. Codes stay stable for tests and audits; wording can change without touching the rule.
4.6 What the browser must never decide
| Concern | Browser | Server |
|---|---|---|
| Show an estimated discount | Yes | Yes |
| Decide the charged price | No | Yes, at checkout, re-evaluated |
| Hold the sidecar token | Never | Yes, in environment or secret store |
| See module version and usage | No | Yes, in logs |
| Retry on 503 | Yes, with back-off | Narrowly, in the client |
At checkout, the server evaluates the rule again with the final cart. If the result differs from what the shopper saw, show the new price and ask for confirmation instead of silently charging a different amount.
4.7 Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Calling the sidecar from the browser | Token exposed; rules callable by anyone | Browser calls your API; server calls the sidecar |
| TypeScript types without runtime checks | Bad responses pass silently | Infer types from Zod or similar schemas |
| Taking prices from the request body | Shoppers set their own prices | Build the cart from server-side state |
| Showing reason codes to users | Confusing, brittle wording | Map codes to text in the front end |
| Ignoring stale responses | Old quotes overwrite new ones | Track the latest request and drop older results |
| Trusting the estimate at checkout | Charged price differs from rule result | Re-evaluate on the server and confirm changes |
Guided practice
- Generate the Zod schemas automatically from pricing.contract.toml with a small script.
- Add exponential back-off with a maximum of three attempts to the hook for 503 responses.
- Write a test that sends a forged price in the request body and proves the quote ignores it.
- Add a LOYALTY reason code end to end, following the release order from Lesson 1.
- Add an accessible live region so screen readers announce the updated discount.
Hands-on lab
Build a small checkout page that shows a live quote as quantities change. Implement the server client, API route, hook, and summary component. Add a checkout endpoint that re-evaluates the rule and returns a PRICE_CHANGED response when the final result differs from the last quote the shopper saw.
Deliverable: the server and web source, tests for forged input and stale responses, and a short screen recording or screenshots of the loading, ready, unavailable, and price-changed states.
Review questions
- Why is TypeScript in the browser treated differently from TypeScript on the server?
- What does inferring types from a schema give you that a plain type does not?
- Why does the API route ignore cart data in the request body?
- How does the hook prevent stale responses from winning?
- Why are reason codes mapped to text in the front end?
- What must happen at checkout, and why?
Applied challenge
Add an offline preview of the pricing rule using the browser execution model from Chapter 23. Show the preview instantly, replace it with the server quote when it arrives, and display a clear notice whenever the two differ. Explain why the preview can never be used to charge a customer.
Lesson summary
TypeScript hosts derive types and validators from the shared contract. Server-side clients hold secrets, validate both directions, and map errors to stable codes. React components call your own API, handle loading, error, unavailable, and stale states, and translate reason codes for people. The browser may display estimates, but only the server decides what a customer pays.
Transition to Lesson 5
Lesson 5 returns to Python with FastAPI integration patterns: dependency injection for runtimes, request-scoped limits, and the standard exception handlers.
Lesson status: Ready for review.