import { getContainer } from "@cloudflare/containers"; import type { HandleFetch } from "@sveltejs/kit"; function isBackendPath(pathname: string): boolean { return ( pathname === "/api" || pathname.startsWith("/api/") || pathname === "/metrics" || pathname === "/ready" || pathname.startsWith("/xrpc/") ); } // Browser /api hits the Worker fetch handler, which forwards to the container. // SvelteKit server loads fetch("/api/...") inside this isolate, so send those // to the same named container. The event.fetch request carries no cookies, // so the browser's cookie header is forwarded explicitly: without it the // container answers as anonymous and logged-in users bounce to /auth/login. export const handleFetch: HandleFetch = async ({ event, request, fetch }) => { const url = new URL(request.url); if (url.origin !== event.url.origin || !isBackendPath(url.pathname)) { return fetch(request); } const glean = event.platform?.env?.GLEAN; if (!glean) { throw new Error("GLEAN container binding missing"); } const headers = new Headers(request.headers); const cookie = event.request.headers.get("cookie"); if (cookie && !headers.has("cookie")) { headers.set("cookie", cookie); } return getContainer(glean, "glean").fetch(new Request(request, { headers })); };