Skip to content

Astro

How an Astro site embeds droplets: a page’s frontmatter fetches each fragment on the server, and set:html renders it into the page.

// src/lib/shop.ts, fragment() (trimmed)
async function fragment(page: PageRequest, id: string, params = new URLSearchParams()): Promise<Fragment> {
const url = `${internal}/droplets/${encodeURIComponent(id)}?${params}`;
const headers: Record<string, string> = { accept: "text/html", "x-droplet-location": origin, referer: origin + page.path };
const cookie = shopCookies(page.cookie);
if (cookie) headers["cookie"] = cookie;
const result: Fragment = { html: "", status: 502, location: null, cookies: [], link: null };
const response = await fetch(url, { headers, redirect: "manual", cache: "no-store" });
result.status = response.status;
result.cookies = response.headers.getSetCookie();
result.link = response.headers.get("link");
if (response.status >= 300 && response.status < 400) {
result.location = response.headers.get("location");
} else if (
(response.ok || response.status === 500) &&
(response.headers.get("content-type") ?? "").startsWith("text/html")
) {
result.html = await response.text();
return result;
}
// … anything else: result.html becomes a "droplet is unavailable" note
return result;
}
<!-- src/layouts/Shop.astro, in <head>: once per page -->
<script type="module" src="/index.js" is:inline></script>
<!-- src/pages/gallery.astro: the fragment's HTML, as it came -->
<aside><Fragment set:html={filter} /></aside>
  • shopPage() in src/lib/shop-page.ts takes page from Astro.request: its path and query, and the browser’s Cookie. fragment() sends GET /droplets/<id>?<params> to SHOP_INTERNAL_URL with accept: text/html, x-droplet-location set to the origin of SHOP_PUBLIC_URL, the shop’s own cookies from it (cart_id, shop_admin) and the page’s URL as referer.
  • redirect: "manual" keeps a droplet’s 3xx: finish() returns it as the page’s Response, with the fragments’ Set-Cookie, and otherwise appends them to Astro.response.headers. Both answers are private, no-store.
  • Only a text/html answer (a 2xx, or a 500 carrying the droplet’s error page) is pasted; set:html writes it unescaped.
  • is:inline keeps Astro from bundling the /index.js script. Endpoints that export ALL (src/pages/{index.js,env.js,index.css}.ts, src/pages/{droplets,assets,api}/[...path].ts) pass /index.js, /env.js, /index.css, /droplets/*, /assets/* and /api/* on to the shop.

The shop demo on Astro 5, recorded by the end-to-end test. How the pieces fit has the diagram.

The shop flow on Astro 5, recorded by the end-to-end test.
  • The gallery, on Astro 5The gallery
  • A product in the cart, on Astro 5A product in the cart
  • The admin: stock set to 0, on Astro 5The admin: stock set to 0
  • The product page: out of stock, on Astro 5The product page: out of stock

The shop flow on Astro 5

The code is in examples/hosts/astro/src: the pages, lib/shop-page.ts (the Astro side) and lib/shop.ts (the framework-free fetches and proxy).

docker-compose.yml starts three services:

Service Port What it is
web 8005, public Astro with the Node adapter (output: "server"): the shop’s pages, the proxy, and the basic page at /
shop 8300, internal only the shop’s droplets server (examples/shop)
droplets 8000, public the Svelte example’s droplets server, for / only
On web Value Used for
SHOP_INTERNAL_URL http://shop:8300 internal: fragment fetches and the proxy
SHOP_PUBLIC_URL http://localhost:8005 public: this host’s own origin, sent as x-droplet-location
DROPLETS_INTERNAL_URL, DROPLETS_PUBLIC_URL http://droplets:8000, http://localhost:8000 the same pair, for the basic page

A server fetch in the page’s frontmatter, rendered with set:html:

src/pages/gallery.astro
---
const query = new URLSearchParams(Astro.url.search);
const page = await shopPage(Astro.request, [
["product-filter", query],
["product-library", query],
]);
const answered = finish(Astro, page); // Set-Cookie onto Astro.response, or the droplet's redirect
if (answered) return answered;
const [filter, library] = page.fragments;
---
<aside><Fragment set:html={filter} /></aside>
<div><Fragment set:html={library} /></div>

shopPage fetches each fragment, plus toast-center and shopping-cart with variant=badge for the header, in parallel (Promise.all) from SHOP_INTERNAL_URL with x-droplet-location, the shop’s cookies from the browser’s Cookie, the page’s URL as Referer (the droplet’s host, query included), redirect: "manual" and cache: "no-store". Only text/html answers are pasted; anything else becomes a “droplet is unavailable” note. The product page first reads GET /droplets/product-page/_data?slug=… for the product’s id and name, and answers 404 when there is none. src/layouts/Shop.astro writes the fragments’ Link preloads into the head as <link> tags (only preload and modulepreload, only on this host’s origin) and loads <script type="module" src="/index.js"> once, through the proxy. The toast-center fragment comes first in its body; /index.js installs window.shopMessageQueue before any droplet starts (the shop’s src/hooks.client.ts):

<body class="shop">
<Fragment set:html={toasts} />
<header class="shop-header">…<div class="shop-cart"><Fragment set:html={cart} /></div>…</header>

Endpoints that export ALL forward /index.js, /env.js and /index.css (src/pages/{index.js,env.js,index.css}.ts), /droplets/* (fragments, _data, form actions), /assets/* and /api/* (src/pages/{droplets,assets,api}/[...path].ts) to shop.proxy(request) in src/lib/shop.ts:

src/pages/droplets/[...path].ts
export const ALL: APIRoute = ({ request }) => shop.proxy(request);

The proxy sends x-droplet-location (the origin of SHOP_PUBLIC_URL) and passes on only accept, accept-language, content-type, if-none-match, origin, referer, user-agent, x-droplet-props and x-droplets-build, plus cookie cut down to the shop’s own cart_id and shop_admin: nothing that names a host, and no other app’s cookie on this origin. The body streams through (duplex: "half"), redirects are not followed, each request times out (15 seconds; fragments 10, the product lookup 5), and the answer comes back with its Set-Cookie untouched, minus content-encoding, content-length and the hop-by-hop headers. When the shop is down it answers 502. The shop’s cookies are first-party, and nothing is cross-origin; the shop sets them only from form actions and /api, which come through here.

  • The public origin is read at runtime. Astro’s own form check (security.checkOrigin) trusts the request’s host only when security.allowedDomains lists it, and that list is compiled in at build. So astro.config.mjs turns it off and src/middleware.ts runs the same check against SHOP_PUBLIC_URL from the environment: one image runs under any origin. Any request but a GET, HEAD or OPTIONS (prerendered pages aside) that is form-urlencoded, multipart, text/plain or has no content type answers 403 unless its Origin is that origin. The shop checks Origin again on its side.
  • Cookies go through Astro.response.headers, appended as the shop sent them; a droplet’s redirect is returned as a Response with its own status.
  • is:inline on every script. Without it Astro would bundle /index.js and the speculation rules into its own assets.
Terminal window
cd examples/hosts/astro
docker compose up --build
open http://localhost:8005/gallery # log in as admin / droplets

Set SHOP_SECRET and DROPLETS_SECRET first; compose refuses to start without them. The shop trusts one origin besides its own, DROPLETS_TRUSTED_ORIGINS: http://localhost:8005, this host’s; the rest of its environment is the same on every host: see Running a host.

The same app serves the Svelte example at /: its three droplets, one per mode, from examples/frameworks/svelte (the droplets service), fetched in the page’s frontmatter.

With output: "server" and the Node adapter, an Astro page runs per request and can fetch fresh fragments in its frontmatter.

---
import { DROPLETS_PUBLIC_URL, fragment } from "../lib/droplets.ts";
const who = Astro.url.searchParams.get("who") ?? "Astro";
const ids = ["client", "ssr-hydrate", "ssr-nohydrate"];
const fragments = await Promise.all(ids.map((id) => fragment(id, { who })));
---
<html lang="en">
<head>
<script type="module" src={`${DROPLETS_PUBLIC_URL}/index.js`} is:inline></script>
</head>
<body>
{fragments.map((html) => <Fragment set:html={html} />)}
</body>
</html>

is:inline tells Astro to leave the external module script alone instead of bundling it. fragment() in src/lib/droplets.ts asks for GET /droplets/<id> on DROPLETS_INTERNAL_URL with x-droplet-location set to DROPLETS_PUBLIC_URL:

// src/lib/droplets.ts (trimmed)
export async function fragment(
droplet: string,
props: Record<string, string> = {},
): Promise<string> {
const url = new URL(`/droplets/${encodeURIComponent(droplet)}`, DROPLETS_INTERNAL_URL);
for (const [key, value] of Object.entries(props)) url.searchParams.set(key, value);
try {
const response = await fetch(url, {
headers: { accept: "text/html", "x-droplet-location": DROPLETS_PUBLIC_URL },
redirect: "manual",
signal: AbortSignal.timeout(5000),
});
// Only an HTML answer is a fragment (a 500 carries the droplet's error
// page); anything else may echo the props, so it is never pasted.
const isFragment =
(response.ok || response.status === 500) && (response.headers.get("content-type") ?? "").startsWith("text/html");
if (isFragment) return await response.text();
await response.body?.cancel();
return `<p class="error">droplet "${escapeHtml(droplet)}" unavailable: HTTP ${response.status}</p>`;
} catch (error) {
return `<p class="error">droplet "${escapeHtml(droplet)}" unavailable: ${escapeHtml(String(error))}</p>`;
}
}

Here the page loads /index.js from the droplets server’s own origin (http://localhost:8000), so the browser fetches bundles and data across origins: the Svelte example runs with cors: true, and the droplets service lists both DROPLETS_URL and WEB_URL in DROPLETS_TRUSTED_ORIGINS.