Skip to content

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.

Bundle files directly into the worker binary at build time and serve them via env.ASSETS. See the guide for the full setup.

src/index.ts
import type { ExportedHandler } from "kyushu-types";
export default {
async fetch(request, env) {
return env.ASSETS.fetch(request);
},
} satisfies ExportedHandler;

Serve files from a directory mounted into the sandbox at runtime. Useful when you want to serve files that change without rebuilding the worker.

src/index.ts
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.

kyushu.toml
[[worker.mounts]]
host = "./dist"
guest = "/"

Start the development server.

Terminal window
kyu dev kyushu.toml

Then send a request to test it.

Terminal window
curl http://localhost:5987

Or open your browser at http://localhost:5987.