How to serve a spec from a Worker route
Because a spec is plain JSON, a Worker can generate one per request and return
it. The page then fetches the spec and passes it to <Anvil>.
Add a route¶
app.get("/anim/:id", (c) => {
const spec = buildSpecForRequest(c.req.param("id")); // your code
return c.json(spec, 200, {
"cache-control": "public, max-age=60",
"access-control-allow-origin": "*",
});
});
Validate before returning¶
Catch malformed specs early so the route returns a clean error instead of shipping a broken page:
import { assertSpec } from "@acoyfellow/anvil/spec";
try {
assertSpec(spec);
} catch (err) {
return c.json({ error: String(err) }, 400);
}
Fetch it on the page¶
const res = await fetch("/anim/hero");
const spec = await res.json();
// <Anvil {spec} />
This is exactly how the gallery works: see Worker routes for the routes anvil ships.