10LOC

#http-server

Bunintermediate

A static file router that falls back to Bun.file

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

A WebSocket server using Bun.serve's built-in upgrade

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

Streaming a file response with Bun.file(), no extra deps

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

Bun.serve() with a routes object: a zero-dependency HTTP server

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.