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.
The pattern in Astro
Section titled “The pattern in Astro”// 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()insrc/lib/shop-page.tstakespagefromAstro.request: its path and query, and the browser’sCookie.fragment()sendsGET /droplets/<id>?<params>toSHOP_INTERNAL_URLwithaccept: text/html,x-droplet-locationset to the origin ofSHOP_PUBLIC_URL, the shop’s own cookies from it (cart_id,shop_admin) and the page’s URL asreferer.redirect: "manual"keeps a droplet’s 3xx:finish()returns it as the page’sResponse, with the fragments’Set-Cookie, and otherwise appends them toAstro.response.headers. Both answers areprivate, no-store.- Only a
text/htmlanswer (a 2xx, or a 500 carrying the droplet’s error page) is pasted;set:htmlwrites it unescaped. is:inlinekeeps Astro from bundling the/index.jsscript. Endpoints that exportALL(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, recorded
Section titled “The shop demo, recorded”The shop demo on Astro 5, recorded by the end-to-end test. How the pieces fit has the diagram.
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).
Pieces and ports
Section titled “Pieces and ports”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 |
How a page gets a droplet
Section titled “How a page gets a droplet”A server fetch in the page’s frontmatter, rendered with set:html:
---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 redirectif (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>What it proxies
Section titled “What it proxies”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:
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.
Gotchas
Section titled “Gotchas”- The public origin is read at runtime. Astro’s own form check
(
security.checkOrigin) trusts the request’s host only whensecurity.allowedDomainslists it, and that list is compiled in at build. Soastro.config.mjsturns it off andsrc/middleware.tsruns the same check againstSHOP_PUBLIC_URLfrom the environment: one image runs under any origin. Any request but aGET,HEADorOPTIONS(prerendered pages aside) that is form-urlencoded, multipart,text/plainor has no content type answers403unless itsOriginis that origin. The shop checksOriginagain on its side. - Cookies go through
Astro.response.headers, appended as the shop sent them; a droplet’s redirect is returned as aResponsewith its own status. is:inlineon every script. Without it Astro would bundle/index.jsand the speculation rules into its own assets.
Run it
Section titled “Run it”cd examples/hosts/astrodocker compose up --buildopen http://localhost:8005/gallery # log in as admin / dropletsSet 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 Svelte example
Section titled “The Svelte example”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.



