Static File Server
To serve static files you can either use the built-in static assets feature, which bundles files directly into the worker, or mount a directory into the sandbox and read files at runtime. The former being the recommended approach for simplicity reasons.
Using static assets (recommended)
Section titled “Using static assets (recommended)”Bundle files directly into the worker binary at build time and serve them via env.ASSETS. See the guide for the full setup.
import type { ExportedHandler } from "kyushu-types";
export default { async fetch(request, env) { return env.ASSETS.fetch(request); },} satisfies ExportedHandler;Using a mounted directory
Section titled “Using a mounted directory”Serve files from a directory mounted into the sandbox at runtime. Useful when you want to serve files that change without rebuilding the worker.
import type { ExportedHandler } from "kyushu-types";import { readFile, access } from "node:fs/promises";import { join } from "node:path";import mime from "mime-types";
export default { async fetch({ url: requestUrl }) { const url = URL.parse(requestUrl);
if (url === null) { return { status: 400, body: "Bad Request" }; }
const { pathname } = url;
const sanitizedPathname = pathname === "/" ? "/index.html" : pathname; const filepath = join(process.cwd(), "public", sanitizedPathname);
try { await access(filepath); } catch { return { status: 404, body: "Not Found" }; }
try { const file = await readFile(filepath); const mimeType = mime.lookup(filepath);
return { status: 200, headers: { "content-type": typeof mimeType === "string" ? mimeType : "application/octet-stream", }, body: file, }; } catch { return { status: 500, body: "Internal Server Error" }; } },} satisfies ExportedHandler;Mount a directory containing your static files into the sandbox.
[[worker.mounts]]host = "./dist"guest = "/"Try it
Section titled “Try it”Start the development server.
kyu dev kyushu.tomlThen send a request to test it.
curl http://localhost:5987Or open your browser at http://localhost:5987.