A .NET-style middleware pipeline for Bun's HTTP server. Chain middleware ("pipes") that run sequentially on every request — just like app.Use() in ASP.NET Core.
import { createApp, cors, logger, timing } from "bun-server-pipe";
const app = createApp();
// Middleware pipeline — runs top-to-bottom on every request
app.use(logger());
app.use(timing());
app.use(cors());
// Routes
app.get("/", (ctx) => ctx.json({ hello: "world" }));
app.get("/users/:id", (ctx) =>
ctx.json({ id: ctx.params.id }),
);
app.listen({ port: 3000 });Every incoming request flows through middleware in registration order. Each middleware can:
- Short-circuit — return a
Responsedirectly (e.g. auth rejection) - Pass through — call
next()to continue to the next middleware - Wrap — call
next(), then modify the response before returning it
Request → [logger] → [cors] → [auth] → [router] → Response
Every middleware and route handler receives a context object:
| Property | Description |
|---|---|
ctx.request |
The raw Request |
ctx.url |
Parsed URL |
ctx.method |
HTTP method (uppercase) |
ctx.params |
Route params (e.g. { id: "42" }) |
ctx.state |
Map<string, unknown> for sharing data |
ctx.server |
The underlying Bun.Server instance |
Response helpers: ctx.json(), ctx.text(), ctx.html(), ctx.redirect(), ctx.respond().
| Middleware | Description |
|---|---|
logger() |
Logs method, path, status, and duration |
timing() |
Adds Server-Timing header |
cors() |
CORS headers + preflight handling |
bearerAuth() |
Bearer token validation |
rateLimit() |
In-memory rate limiting |
Scope routes and middleware under a shared prefix:
app.group("/api", (api) => {
api.use(bearerAuth({ validate: (t) => t === "secret" }));
api.get("/users", handler);
api.post("/users", handler);
});bun run dev