NextRush

@nextrush/adapter-bun

Bun HTTP adapter for NextRush with graceful shutdown and TLS support.

Connect your NextRush application to Bun's native HTTP server.

This adapter bridges NextRush's middleware system to Bun's native Bun.serve() API, handling context creation, in-flight request tracking, and graceful shutdown.


Installation

$ pnpm add @nextrush/adapter-bun @nextrush/core

Bun Runtime Required

This adapter requires Bun 1.0 or later. It uses Bun's native Bun.serve() API for optimal performance.


Quick Start

import { createApp } from '@nextrush/core';
import { listen } from '@nextrush/adapter-bun';

const app = createApp();

app.use(async (ctx) => {
  ctx.json({ runtime: 'bun', message: 'Hello World!' });
});

listen(app, 3000);
// Output: 🚀 NextRush listening on http://localhost:3000 (Bun)

Run with Bun:

bun run src/index.ts

API Reference

serve(app, options?)

Start the HTTP server with full configuration control.

import { createApp } from '@nextrush/core';
import { serve } from '@nextrush/adapter-bun';

const app = createApp();

const server = serve(app, {
  port: 3000,
  hostname: '0.0.0.0',
  development: true,
  onListen: ({ port, hostname }) => {
    console.log(`Server running at http://${hostname}:${port}`);
  },
  onError: (error) => {
    console.error('Server error:', error);
  },
});

ServeOptions

Options

PropertyTypeDescription
portnumber= 3000Port to listen on
hostnamestring= '0.0.0.0'Hostname to bind to
onListen?(info: { port: number; hostname: string }) => voidCallback when server starts listening
onError?(error: Error) => voidCustom handler for uncaught server errors
tls?{ cert: string | Buffer; key: string | Buffer; ca?: string | Buffer }TLS/HTTPS configuration
maxRequestBodySize?numberMaximum request body size in bytes (Bun default: 128 MB)
developmentboolean= falseEnable Bun development mode with additional logging
shutdownTimeoutnumber= 30000Grace period in ms to drain in-flight requests during shutdown

ServerInstance

The returned server instance provides control methods:

interface ServerInstance {
  server: ReturnType<typeof Bun.serve>; // Underlying Bun server
  port: number; // Actual port
  hostname: string; // Actual hostname

  close(): Promise<void>; // Graceful shutdown (drains in-flight requests)
  address(): { port: number; hostname: string };
  reload(options?: Partial<ServeOptions>): void; // Reload server configuration
}

close() stops accepting new connections, waits up to shutdownTimeout ms for in-flight requests to complete, then force-closes remaining connections and notifies plugins via app.close().


listen(app, port?)

Quick-start shorthand with default logging.

import { createApp } from '@nextrush/core';
import { listen } from '@nextrush/adapter-bun';

const app = createApp();
const server = listen(app, 3000);
// Output: 🚀 NextRush listening on http://localhost:3000 (Bun)

createHandler(app)

Create a raw fetch handler for advanced use cases.

import { createApp } from '@nextrush/core';
import { createHandler } from '@nextrush/adapter-bun';

const app = createApp();
const handler = createHandler(app);

// Use directly with Bun.serve
Bun.serve({
  fetch: handler,
  port: 3000,
});

TLS/HTTPS

Enable HTTPS with TLS certificates:

import { serve } from '@nextrush/adapter-bun';

const server = serve(app, {
  port: 443,
  tls: {
    cert: Bun.file('./cert.pem'),
    key: Bun.file('./key.pem'),
    ca: Bun.file('./ca.pem'), // Optional CA certificate
  },
});

Hot Reload

Bun adapter supports runtime configuration reload:

const server = serve(app, { port: 3000 });

// Update non-structural configuration at runtime
server.reload({ development: true });

reload() passes options to Bun's server.reload(). Structural changes like port may not take effect.


Request Body Limits

Configure maximum request body size:

const server = serve(app, {
  port: 3000,
  // 10MB limit
  maxRequestBodySize: 10 * 1024 * 1024,
});

Bun's default is 128MB. Set this lower for APIs that don't need large uploads.


Development Mode

Enable development mode for additional logging:

const server = serve(app, {
  port: 3000,
  development: true, // Enables Bun's dev logging
});

Graceful Shutdown

The adapter tracks in-flight requests and drains them on shutdown. Configure the drain timeout with shutdownTimeout (default: 30 seconds):

const server = serve(app, {
  port: 3000,
  shutdownTimeout: 10_000, // 10s drain window
});

process.on('SIGTERM', async () => {
  await server.close();
  process.exit(0);
});

close() performs three steps:

  1. Stops accepting new connections
  2. Waits for active requests to finish (up to shutdownTimeout)
  3. Force-closes remaining connections and calls app.close()

Client IP Access

The adapter automatically extracts client IP from Bun's requestIP():

app.use(async (ctx) => {
  // Available via context
  const ip = ctx.ip; // Extracted from Bun server
  ctx.json({ clientIp: ip });
});

TypeScript

Full TypeScript support with proper types:

import type { Application } from '@nextrush/core';
import type { ServeOptions, ServerInstance } from '@nextrush/adapter-bun';
import { serve, listen, createHandler } from '@nextrush/adapter-bun';

const options: ServeOptions = {
  port: 3000,
  development: process.env.NODE_ENV !== 'production',
};

const server: ServerInstance = serve(app, options);

On this page