Skip to content

Joshlo/bun-dotnet-api

Repository files navigation

bun-server-pipe

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.

Quick start

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 });

Concepts

Pipeline

Every incoming request flows through middleware in registration order. Each middleware can:

  1. Short-circuit — return a Response directly (e.g. auth rejection)
  2. Pass through — call next() to continue to the next middleware
  3. Wrap — call next(), then modify the response before returning it
Request → [logger] → [cors] → [auth] → [router] → Response

Context (PipeContext)

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().

Built-in middleware

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

Route groups

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);
});

Run the example

bun run dev

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors