Bunintermediate
import { serve, file } from "bun";
const PUBLIC_DIR = `${import.meta.dir}/public`;
const server = serve({
A fetch handler can serve API routes first and fall back to Bun.file for anything else, building a static file server without a separate static-file middleware.
Bunintermediate
export const wsServer = Bun.serve({
fetch(req, server) {
return server.upgrade(req) ? undefined : new Response("Upgrade failed", { status: 500 });
},
websocket: {
Bun.serve() upgrades an HTTP request to a WebSocket in the fetch handler and reuses one handler object across every connection, no ws package needed.
Bunintermediate
import { serve, file } from "bun";
const server = serve({
async fetch(req) {
const pathname = new URL(req.url).pathname;
Bun.file() returns a lazy file handle that streams straight into a Response, so serving a large file never buffers it fully in memory.
Bunintermediate
export const app = Bun.serve({
routes: {
"/api/health": new Response("ok"),
"/api/users/:id": (req) => Response.json({ id: req.params.id }),
"/api/users": {
Bun.serve()'s routes option matches paths, HTTP methods, and :params natively, replacing a router dependency for most REST APIs.