Browse the docs

HTTP & Middleware

@putnami/application provides the HTTP server, routing, and middleware layer built on Bun's native server.

HTTP server

Basic setup

import { application, http } from '@putnami/application';

export const app = () =>
  application()
    .use(http({ port: 3000 }));

Configuration options

http({
  port: 3000,              // Server port
  originGuard: {           // Cross-origin CSRF protection (enabled by default)
    trustedOrigins: ['https://admin.example.com'],
  },
  securityHeaders: {       // Secure response headers (enabled by default)
    contentSecurityPolicy: "default-src 'self'; script-src 'self' https://cdn.example.com",
  },
})

Built-in CSRF protection: The origin guard validates Origin and Sec-Fetch-Site headers on all state-changing requests (POST, PUT, DELETE, PATCH) and rejects cross-origin requests with 403. It is enabled by default. Set originGuard: false to disable. See Auth security considerations for full details.

Secure-by-default headers: Every response carries hardened security headers — X-Content-Type-Options: nosniff, X-Frame-Options: DENY, a restrictive Content-Security-Policy, Referrer-Policy, Permissions-Policy, Strict-Transport-Security (over HTTPS), and X-XSS-Protection — without any extra plugin. A JSON response (application/json or a +json type) is never rendered as a document, so it carries only X-Content-Type-Options: nosniff, Content-Security-Policy: frame-ancestors 'none', HSTS over HTTPS, and any header you set explicitly through securityHeaders. Override individual headers via securityHeaders (set a header to false to omit it) or set securityHeaders: false to disable them entirely.

YAML configuration

http:
  port: 3000
  hostname: '0.0.0.0'

Manual routing

While file-based routing is recommended, you can register routes programmatically.

Basic routes

import { http } from '@putnami/application';

const httpPlugin = http({ port: 3000 });

// GET route
httpPlugin.get('/health', () => ({ status: 'ok' }));

// POST route
httpPlugin.post('/users', async (ctx) => {
  const body = await ctx.body();
  return { created: true, user: body };
});

// PUT route
httpPlugin.put('/users/:id', async (ctx) => {
  const { id } = ctx.params;
  const body = await ctx.body();
  return { updated: true, id, data: body };
});

// DELETE route
httpPlugin.delete('/users/:id', (ctx) => {
  const { id } = ctx.params;
  return { deleted: true, id };
});

// PATCH route
httpPlugin.patch('/users/:id', async (ctx) => {
  const { id } = ctx.params;
  const body = await ctx.body();
  return { patched: true, id, data: body };
});

Route with options

httpPlugin.route('GET', '/api/data', handler, {
  accept: ['application/json'],
  statusCode: 200,
});

Merging routes

// Merge routes from another controller
const apiRoutes = new RouteController();
apiRoutes.route('GET', '/users', listUsers);
apiRoutes.route('POST', '/users', createUser);

httpPlugin.merge('/api', apiRoutes);
// Results in: GET /api/users, POST /api/users

Request rewrites

A rewrite routes a request at another path, before route matching:

http().rewrite((req, path) => (new URL(req.url).hostname === 'fr.example.com' ? `/fr${path}` : undefined));

The first rewrite, in registration order, that returns a path a route serves wins; the query stays. A path no route serves is ignored, so /assets/app.js on fr.example.com keeps its own route. Route matching, middleware and the handler see the rewritten URL in ctx.url and ctx.path(); ctx.req.url keeps the client's. A merged plugin's rewrites run in the plugin it is merged into. Native routes are not rewritten.

Middleware

Middleware functions process requests before they reach route handlers.

Middleware signature

type HttpMiddleware = (
  context: HttpRequestContext,
  next: () => Promise<HttpResponse | undefined>,
) => Promise<HttpResponse | undefined>;

Creating middleware

import type { HttpMiddleware } from '@putnami/application';
import { unauthorized, badRequest } from '@putnami/application';

// Logging middleware
export const logger: HttpMiddleware = async (ctx, next) => {
  const start = Date.now();
  console.log(`--> ${ctx.method} ${ctx.path()}`);

  const response = await next();

  const duration = Date.now() - start;
  console.log(`<-- ${ctx.method} ${ctx.path()} ${duration}ms`);

  return response;
};

// Authentication middleware
export const requireAuth: HttpMiddleware = async (ctx, next) => {
  const token = ctx.headers.get('authorization')?.replace('Bearer ', '');

  if (!token) {
    return unauthorized('Missing token');
  }

  try {
    const user = await verifyToken(token);
    // Store user for later use (via context or DI)
    return next();
  } catch {
    return unauthorized('Invalid token');
  }
};

// Content-type validation
export const requireJson: HttpMiddleware = async (ctx, next) => {
  const contentType = ctx.headers.get('content-type');

  if (ctx.method !== 'GET' && !contentType?.includes('application/json')) {
    return badRequest('Content-Type must be application/json');
  }

  return next();
};

Registering middleware

const httpPlugin = http({ port: 3000 });

// Append middleware (runs after existing middleware)
httpPlugin.use(logger);
httpPlugin.use(requireJson);

// Prepend middleware (runs before existing middleware)
httpPlugin.prepend(corsMiddleware);

Middleware order

Middleware executes in the order registered:

httpPlugin.use(middleware1);  // Runs 1st
httpPlugin.use(middleware2);  // Runs 2nd
httpPlugin.use(middleware3);  // Runs 3rd
// Route handler runs last

Early return

Middleware can return early without calling next():

import { json } from '@putnami/application';

export const maintenanceMode: HttpMiddleware = async (ctx, next) => {
  if (isMaintenanceMode()) {
    return json(
      { error: 'Service temporarily unavailable' },
      { status: 503 }
    );
  }
  return next();
};

Modifying responses

Middleware can modify responses from downstream handlers:

export const addSecurityHeaders: HttpMiddleware = async (ctx, next) => {
  const response = await next();

  if (response) {
    response.setHeader('X-Content-Type-Options', 'nosniff');
    response.setHeader('X-Frame-Options', 'DENY');
    response.setHeader('X-XSS-Protection', '1; mode=block');
  }

  return response;
};

Common middleware patterns

CORS

import { CorsMiddleware, http, endpoint } from '@putnami/application';

http().use(CorsMiddleware({
  origin: 'https://app.example.com',
  credentials: true,
}));

export default endpoint()
  .cors({ origin: 'https://app.example.com', credentials: true })
  .handle(() => ({ ok: true }));

CSRF protection

import { http } from '@putnami/application';

// Enable token-based CSRF (double-submit cookie) on the server
const server = http({ port: 3000, csrf: true });

// Or with options
const server2 = http({
  port: 3000,
  csrf: {
    headerName: 'X-CSRF-Token',
    secret: process.env.CSRF_SECRET,
  },
});

When CSRF is enabled, the @putnami/web client runtime automatically injects the X-CSRF-Token header on state-changing requests:

  • <Form> actions — the token is read from the _csrf cookie and attached to every POST submission.
  • useFetch hook — the token is injected for POST, PUT, DELETE, and PATCH requests. Safe methods (GET, HEAD, OPTIONS) are skipped.

No client-side code changes are required — enable csrf: true on the server and the React client handles the rest. For manual fetch() calls, read the token from document.cookie and include it in the X-CSRF-Token header.

Rate limiting

import { RateLimitMiddleware, http, endpoint } from '@putnami/application';

http().use(RateLimitMiddleware({ windowMs: 60_000, max: 100 }));

export default endpoint()
  .rateLimit({ windowMs: 60_000, max: 10 })
  .handle(() => ({ ok: true }));

Custom store example (Redis/DB). A store implements consume only, and an async store MUST implement it atomically (e.g. Redis INCR + Lua, or a DB upsert with RETURNING), so concurrent requests cannot bypass the limit:

import { RateLimitMiddleware, type RateLimitStore } from '@putnami/application';

const store: RateLimitStore = {
  async consume(key, limit, windowMs) {
    // One atomic server-side operation, such as a Redis INCR in a Lua script
    const { count, resetAt } = await redis.incrementWindow(key, windowMs);
    return { allowed: count <= limit, remaining: Math.max(0, limit - count), resetAt };
  },
};

http().use(RateLimitMiddleware({ store }));

Request timing

export const timing: HttpMiddleware = async (ctx, next) => {
  const start = performance.now();

  const response = await next();

  const duration = performance.now() - start;
  response?.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);

  return response;
};

Error handling

import { json, internalServerError } from '@putnami/application';

export const errorHandler: HttpMiddleware = async (ctx, next) => {
  try {
    return await next();
  } catch (error) {
    console.error('Unhandled error:', error);

    if (error instanceof HttpException) {
      return json(
        { error: error.message },
        { status: error.status }
      );
    }

    return internalServerError('An unexpected error occurred');
  }
};

Compression

import { CompressionMiddleware, http } from '@putnami/application';

http().use(CompressionMiddleware({
  threshold: 1024,
  encodings: ['gzip', 'deflate'],
}));

Automatic HTTP methods

The HTTP plugin automatically handles HEAD, OPTIONS, and (optionally) TRACE requests. No explicit route registration is needed.

Configuration

http({
  port: 3000,
  httpMethods: {
    head: true,      // default — derive HEAD from GET handlers
    options: true,   // default — respond with Allow header
    trace: false,    // default — disabled for security
  },
})

Disable all automatic methods:

http({ port: 3000, httpMethods: false })
Option Type Default Description
head boolean true Derive HEAD responses from GET handlers. Static routes skip the handler and return pre-computed metadata; dynamic routes execute the handler and strip the body.
options boolean true Respond with 204 No Content and an Allow header listing every method registered for the path (plus HEAD and OPTIONS themselves).
trace boolean false Echo the request back as message/http. Sensitive headers (Cookie, Authorization, Proxy-Authorization) are excluded. Disabled by default to prevent XST attacks.

A HEAD request to a path that has a GET handler returns the status line and headers without the body.

Static and cached content — Routes with pre-computed headMeta (like static files) skip handler execution entirely and return known metadata: Content-Type, Content-Length, Last-Modified, ETag, Cache-Control, Content-Encoding, and Vary. If-None-Match → 304 is also handled without touching the body.

Dynamic content — When no headMeta is available, the framework executes the full middleware chain and GET handler, then strips the response body.

You can provide custom HEAD metadata via RouteOptions:

httpPlugin.route('GET', '/data', handler, {
  headMeta: (ctx) => new HttpResponse(undefined, {
    status: 200,
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': String(size),
      ETag: etag,
    },
  }),
});

Return undefined from headMeta to fall back to handler execution.

OPTIONS

An OPTIONS request returns 204 with an Allow header:

Allow: DELETE, GET, HEAD, OPTIONS, POST

When CorsMiddleware is active, it handles CORS preflight OPTIONS (requests carrying an Origin header). The automatic OPTIONS responder is a fallback for non-CORS clients.

TRACE

TRACE is disabled by default because it can enable Cross-Site Tracing (XST) attacks. When enabled, the framework echoes the request back but always strips sensitive headers to reduce risk.

// Opt-in — not recommended in production
http({ port: 3000, httpMethods: { trace: true } })

Explicit routes take precedence

If you register an explicit HEAD, OPTIONS, or TRACE route with httpPlugin.route(method, path, handler), it takes precedence over the automatic behaviour.

Route-level middleware

An endpoint runs middleware of its own with .use(), such as a tenant guard or a webhook signature check, without a global middleware that tests the path:

// src/api/webhooks/post.ts
import { createHmac, timingSafeEqual } from 'node:crypto';
import { endpoint, HttpResponse, type HttpMiddleware } from '@putnami/application';

const secret = process.env.WEBHOOK_SECRET;
if (!secret) throw new Error('WEBHOOK_SECRET is required');
const MAX_BYTES = 64 * 1024;

/**
 * The request body, or `undefined` past `max` bytes: an unsigned body is never
 * read whole. It reads a clone, so the handler can still read the body.
 */
async function readAtMost(req: Request, max: number): Promise<Uint8Array | undefined> {
  const declared = Number(req.headers.get('content-length') ?? 0);
  if (!Number.isInteger(declared) || declared > max) return undefined;
  const body = req.clone().body;
  if (!body) return new Uint8Array(0);
  const reader = body.getReader();
  const chunks: Uint8Array[] = [];
  let size = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) return Buffer.concat(chunks);
    size += value.byteLength;
    if (size > max) {
      // Not awaited: the cancel of a cloned body can wait on the branch nobody reads.
      void reader.cancel().catch(() => {});
      return undefined;
    }
    chunks.push(value);
  }
}

const verifySignature: HttpMiddleware = async (ctx, next) => {
  const body = await readAtMost(ctx.req, MAX_BYTES);
  if (!body) return HttpResponse.json({ error: 'body too large' }, { status: 413 });
  const expected = createHmac('sha256', secret).update(body).digest();
  const given = Buffer.from(ctx.headers.get('x-signature') ?? '', 'hex');
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
    return HttpResponse.json({ error: 'bad signature' }, { status: 401 });
  }
  return next();
};

export default endpoint()
  .csrfExempt()
  .use(verifySignature)
  .handle(async (ctx) => ({ received: (await ctx.req.text()).length }));

A request runs the application's middleware first, then the endpoint's own in the order the builder declares them, .use(), .cors(), .cache(), .rateLimit() and .secure() alike, the first declared outermost, then input validation and the handler. Built-in middleware takes its place in that order too: .use(guard).secure() runs the guard before authentication, .secure().use(guard) after it, with ctx.user set on an HTTP or SSE request. A middleware that returns a response without calling next() answers the request, and the handler does not run; one that returns nothing lets the router try the next route. A validation error passes through the endpoint's middleware as a thrown HttpException.

.use() takes one or more middlewares and can be called several times. A preset, a function that returns a configured builder, adds one like any other option:

import { endpoint, HttpResponse, type HttpMiddleware } from '@putnami/application';

const tenantGuard: HttpMiddleware = async (ctx, next) =>
  ctx.headers.get('x-tenant') ? next() : HttpResponse.json({ error: 'tenant required' }, { status: 400 });

const tenantScoped = () => endpoint().secure().use(tenantGuard);

export const GET = tenantScoped().handle(() => ({ items: [] }));

On a stream endpoint, the endpoint's middleware only admits or refuses the stream. It runs on the SSE request, on the upgrade of a provider-owned WebSocket, on the init frame of a first-party WebSocket, against the request that frame rebuilds, and on a Connect or gRPC call, where a refusal becomes an error status that keeps the body's message. The raw WebSocket upgrade of a stream with no first-party client contract (an external operation included) runs the middleware that admits or refuses, .use(), .secure() and .rateLimit(), in the order the builder declares them, so the upgrade is refused where the SSE request would be, before any socket opens, with 401 or 403 from .secure(), 429 from .rateLimit() or the status a .use() middleware chose; each upgrade counts as one request against the rate limit. .cors() and .cache() do not run on it: neither refuses a request, a 101 response carries their headers to no reader, and browsers apply no CORS check to a WebSocket, so a route that checks the upgrade's Origin does it in a .use() middleware. There the socket opens when next() returns, so a middleware must refuse before it calls next(): a refusal after next() arrives too late.

A few edges follow from where the middleware runs. A refusal on a first-party WebSocket init frame reaches the client as unauthorized, without its message. On a Connect call the middleware sees a request rebuilt with no body, so a check of the body's signature refuses every call. And a preset must be a function: one builder object shared by two routes shares its middleware and its declared errors between them.

A route Bun matches stays on its compiled path, with or without .use(): the endpoint's middleware runs inside its handler. An endpoint that declares none keeps its handler unwrapped and the validators the build compiles for it.

Request context

Available properties

export async function handler(ctx: HttpRequestContext) {
  // Request information
  ctx.url;        // The routed URL; a rewrite replaces its path
  ctx.method;     // HTTP method
  ctx.headers;    // Headers object
  ctx.req;        // Raw Bun Request, with the client's URL

  // Route information
  ctx.route;      // Matched route pattern
  ctx.params;     // Route parameters
  ctx.statusCode; // Response status (modifiable)
  ctx.user;       // Authenticated user claims (when set by auth middleware)

  // Server
  ctx.server;     // Bun server instance
}

Available methods

export async function handler(ctx: HttpRequestContext) {
  // URL helpers
  ctx.queryParams();  // URLSearchParams
  ctx.secured();      // true if HTTPS
  ctx.host();         // Host with port
  ctx.domain();       // Domain without port
  ctx.path();         // URL path
  ctx.query();        // Query string

  // Body
  const body = await ctx.body<MyType>();

  // Error
  ctx.throw(400, 'Bad request');
}

Response handling

HttpResponse and factory functions

import { HttpResponse, json, badRequest, unauthorized, forbidden, notFound, internalServerError } from '@putnami/application';

// JSON response
json({ data: 'value' });
json({ data: 'value' }, { status: 201 });

// Redirect
HttpResponse.redirect('/new-location');
HttpResponse.redirect('/new-location', 301);

// Error responses
badRequest('Invalid input');
unauthorized('Not authenticated');
forbidden('Not allowed');
notFound('Resource not found');
internalServerError('Server error');

Custom responses

import { HttpResponse, json } from '@putnami/application';

// Create from a body and a ResponseInit
const response = new HttpResponse('Hello', {
  status: 200,
  headers: { 'Content-Type': 'text/plain' },
});

// Modify headers
response.setHeader('X-Custom', 'value');
response.pushHeader('Set-Cookie', 'session=abc');

// Chain modifications
json({ ok: true })
  .setHeader('Cache-Control', 'no-store')
  .setHeader('X-Request-Id', requestId);