npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dangao/bun-server

v3.3.1

Published

Readme

Bun Server

Examples: https://disb-examples-{example-name}.dangaogm.com

bun node typescript license

A high-performance, decorator-driven DI web framework with multi-runtime support (Bun & Node.js).

Why Bun Server

  • Multi-runtime: runs on Bun (optimal) and Node.js 22+ via the Platform Adapter Layer — same codebase, automatic runtime detection.
  • Native Bun performance: when running on Bun, uses Bun.serve, Bun.file, Bun.CryptoHasher and other native APIs for maximum performance.
  • Modern DX: decorators, metadata and DI everywhere — controllers, services, middleware, validation.
  • Lightweight yet extensible: modular DI + extension layer + logging provider that scales from MVP to enterprise.
  • Well-tested: unit, integration, stress and benchmark suites ship with the repo.
  • AI-friendly: source code and tests are included in the npm package, enabling AI tools (like Cursor) to provide better code analysis, suggestions, and understanding of the framework internals.

Features

  • 🚀 Fast HTTP stack powered by Bun with Application, Router, Context and ResponseBuilder helpers.
  • 🧩 Dependency injection container with @Injectable, @Inject, module metadata, lifecycle management and cached dependency plans.
  • 🗄️ Database v2 with db proxy, route-level pool/session strategy, multi-tenant manager and unified transactions.
  • 🧵 Middleware pipeline with global/class/method scopes plus built-ins (logging, error, CORS, upload, static, ...).
  • Input validation via decorators and ValidationError integration.
  • 📡 WebSocket gateways with @WebSocketGateway, @OnMessage, etc.
  • 📚 Docs & samples including multi-language docs, benchmark scripts and best practices.
  • 🧪 Testing module with Test.createTestingModule(), provider override, and built-in HTTP test client.
  • 🔄 Lifecycle hooksOnModuleInit, OnModuleDestroy, OnApplicationBootstrap, OnApplicationShutdown.
  • Async module configforRootAsync() with factory injection on ConfigModule, DatabaseModule, CacheModule and more.
  • 🔌 Type-safe client generation — extract route manifests and create typed API clients from controller metadata.
  • 🎨 Decorator compositionapplyDecorators() to merge multiple decorators into one reusable decorator.
  • 📊 Built-in dashboardDashboardModule provides a zero-dependency monitoring web UI with system info, routes and health status.
  • 🐛 Request replay / debugDebugModule records requests in a ring buffer with a debug UI for inspection and replay.
  • 🖥️ Zero-config clusterClusterManager auto-spawns reusePort workers matching CPU core count.

AI Modules (v2.0.0)

9 official AI modules for building production-grade LLM applications. All providers use Bun's native fetch() — zero external SDK dependencies.

| Module | Purpose | |--------|---------| | AiModule | LLM unified access (OpenAI, Claude, Gemini, Ollama) + Tool Calling + streaming | | ConversationModule | Multi-turn conversation memory (Memory/Redis/Database stores) | | PromptModule | Reusable prompt templates with {{variable}} interpolation and versioning | | EmbeddingModule | Text embedding generation (OpenAI, Ollama) | | VectorStoreModule | Vector similarity search (Memory, Pinecone, Qdrant) | | RagModule | Full RAG pipeline: ingest → chunk → embed → retrieve | | McpModule | MCP protocol server (JSON-RPC 2.0, SSE transport) | | AiGuardModule | PII detection, prompt injection detection, content moderation |

import { AiModule, OllamaProvider, AI_SERVICE_TOKEN, AiService } from '@dangao/bun-server';

AiModule.forRoot({
  providers: [{ name: 'ollama', provider: OllamaProvider, config: {}, default: true }],
  fallback: true,
});

@Injectable()
class ChatService {
  constructor(@Inject(AI_SERVICE_TOKEN) private ai: AiService) {}
  chat(message: string) { return this.ai.complete({ messages: [{ role: 'user', content: message }] }); }
}

See docs/ai.md for the complete AI modules guide and examples/05-ai/ for working examples including the AI Platform MVP Demo.

Architecture

Request Lifecycle

The following diagram shows the complete request processing flow:

HTTP Request
    ↓
┌─────────────────────────────────────┐
│         Middleware Pipeline         │  ← Global → Module → Controller → Method
│  (Logger, CORS, RateLimit, etc.)    │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│         Security Filter             │  ← Authentication / Authorization
│   (JWT, OAuth2, Role Check)         │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│         Router Matching             │  ← Path, Method, Params
│   (Static → Dynamic → Wildcard)     │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│       Interceptors (Pre)            │  ← Global → Controller → Method
│   (Cache, Log, Transform)           │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│       Parameter Binding             │  ← @Body, @Query, @Param, @Header
│       + Validation                  │  ← @Validate, IsString, IsEmail...
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│       Controller Method             │  ← Business Logic Execution
│   (with DI injected services)       │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│       Interceptors (Post)           │  ← Method → Controller → Global
│   (Response Transform)              │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│       Exception Filter              │  ← Exception Handling
│   (HttpException, ValidationError)  │
└─────────────────────────────────────┘
    ↓
HTTP Response

Execution Order: Middleware → Security → Router → Interceptors(Pre) → Validation → Handler → Interceptors(Post) → Exception Filter

Module System

Application
    │
    ├── ModuleRegistry
    │   │
    │   ├── ConfigModule (Configuration)
    │   ├── LoggerModule (Logging)
    │   ├── SecurityModule (Authentication)
    │   │   └── auth/ (JWT, OAuth2)
    │   ├── SwaggerModule (API Docs)
    │   ├── CacheModule (Caching)
    │   ├── DatabaseModule (Database)
    │   │   └── ORM (Entity, Repository, Transaction)
    │   ├── QueueModule (Job Queue)
    │   ├── SessionModule (Session)
    │   ├── MetricsModule (Metrics)
    │   ├── HealthModule (Health Check)
    │   └── Microservice/
    │       ├── ConfigCenterModule
    │       ├── ServiceRegistryModule
    │       ├── ServiceClient
    │       ├── Governance (Circuit Breaker/Rate Limit/Retry)
    │       └── Tracing
    │
    ├── ControllerRegistry
    │   └── All module controllers
    │
    ├── WebSocketGatewayRegistry
    │   └── WebSocket gateways
    │
    └── InterceptorRegistry
        └── Interceptor registry

DI Container

Container
    │
    ├── providers (Map<token, ProviderConfig>)
    │   ├── Singleton (shared globally)
    │   ├── Transient (new instance per resolve)
    │   └── Scoped (per-request instance)
    │
    ├── singletons (singleton instance cache)
    │
    ├── scopedInstances (WeakMap, request-level cache)
    │
    ├── dependencyPlans (dependency resolution plan cache)
    │
    └── postProcessors (instance post-processors)

For detailed lifecycle documentation, see Request Lifecycle.

Platform Adapter Layer

Bun Server abstracts all runtime-specific APIs behind a unified IPlatform interface, enabling transparent execution on Bun (optimal performance) and Node.js 22+ (broad compatibility).

┌──────────────────────────────────────────────────────┐
│                  Application Layer                    │
│   Controllers / Services / Modules / Middleware       │
└──────────────────────────┬───────────────────────────┘
                           │ getRuntime()
┌──────────────────────────▼───────────────────────────┐
│              Platform Adapter Layer                   │
│  IFsAdapter · ICryptoAdapter · IParserAdapter         │
│  IProcessAdapter · IHttpDriver · IWebSocket           │
└──────┬───────────────────────────────┬───────────────┘
       │                               │
┌──────▼──────┐                 ┌──────▼──────┐
│ BunPlatform │                 │ NodePlatform│
│ Bun.serve   │                 │ node:http   │
│ Bun.file    │                 │ node:fs     │
│ Bun.Crypto  │                 │ node:crypto │
│ spawn(bun)  │                 │ ws package  │
└─────────────┘                 └─────────────┘

DatabaseModule internally detects the platform via getRuntime().engine:

  • Bunbun:sqlite (SQLite) / Bun.SQL (PostgreSQL + MySQL)
  • Node.jsbetter-sqlite3 (SQLite) / postgres (PostgreSQL) / mysql2 (MySQL)

Platform support matrix:

| Feature | Bun | Node.js | |---|---|---| | HTTP Server | Bun.serve | node:http | | WebSocket | Bun.ServerWebSocket | ws package | | File I/O | Bun.file / write | node:fs | | Crypto (JWT) | Bun.CryptoHasher | node:crypto | | JSONC / JSON5 | Bun.JSONC / JSON5 | jsonc-parser / json5 | | Markdown | Bun.markdown | marked | | Cluster spawn | spawn (bun) | node:child_process | | SQLite | bun:sqlite | better-sqlite3 | | PostgreSQL | Bun.SQL | postgres package | | MySQL | Bun.SQL | mysql2 package | | Performance | Optimal | Good |

All features are transparent to the user — the framework auto-detects the runtime at startup.

Platform configuration:

// Option 1: code config (highest priority)
const app = new Application({ platform: 'node' });
app.registerModule(AppModule);
await app.listen(3000);

// Option 2: CLI argument
// bun run main.ts --platform=node

// Option 3: environment variable
// BUN_SERVER_PLATFORM=node node main.js

// Option 4: auto-detect (default, no config needed)
// Running under Bun → BunPlatform
// Running under Node.js → NodePlatform

Platform Differences

  • BunServer.getServer() now returns IServerHandle (platform-neutral). Use getNativeServer(): unknown to access the raw underlying instance (Bun: Bun.Server<T>, Node: http.Server). Raw access is discouraged.
  • WebSocket guards: WsArgumentsHost.getClient() returns IWebSocket<T> instead of Bun's ServerWebSocket<T>. This is the only breaking change in the WebSocket public API.
  • Database, HTTP, file I/O, crypto — all underlying implementations are automatically switched by the Platform Adapter. Zero user configuration needed.
  • idleTimeout / reusePort / SSE TCP keepalive are Bun-exclusive features; silently ignored on Node.js.

See docs/platform.md for the full platform guide.

Getting Started

Requirements

  • Bun >= 1.3.10

TypeScript Configuration ⚠️

Critical: Ensure your tsconfig.json includes these decorator settings:

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  }
}

Without these, dependency injection will fail (injected services will be undefined). See Troubleshooting Guide for details.

Install

bun install

Hello World

import { Application, Controller, GET, Injectable } from "@dangao/bun-server";

@Injectable()
class HealthService {
  public ping() {
    return { status: "ok" };
  }
}

@Controller("/api")
class HealthController {
  public constructor(private readonly service: HealthService) {}

  @GET("/health")
  public check() {
    return this.service.ping();
  }
}

const app = new Application({ port: 3100 });
app.getContainer().register(HealthService);
app.registerController(HealthController);
app.listen();

Useful scripts

bun --cwd=packages/bun-server test
bun --cwd=packages/bun-server run bench
bun --cwd=packages/bun-server run bench:router
bun --cwd=packages/bun-server run bench:di

Running bun test from the repo root fails because Bun only scans the current workspace. Use the commands above or cd packages/bun-server first.

Advanced Example: Interface + Symbol + Module

This example demonstrates using interfaces with Symbol tokens and module-based dependency injection:

import {
  Application,
  Body,
  CONFIG_SERVICE_TOKEN,
  ConfigModule,
  ConfigService,
  Controller,
  GET,
  Inject,
  Injectable,
  Module,
  Param,
  POST,
} from "@dangao/bun-server";

// Define service interface
interface UserService {
  find(id: string): Promise<{ id: string; name: string } | undefined>;
  create(name: string): { id: string; name: string };
}

// Create Symbol token for DI
const UserService = Symbol("UserService");

// Implement the interface
@Injectable()
class UserServiceImpl implements UserService {
  private readonly users = new Map<string, { id: string; name: string }>([
    ["1", { id: "1", name: "Alice" }],
  ]);

  public async find(id: string) {
    return this.users.get(id);
  }

  public create(name: string) {
    const id = String(this.users.size + 1);
    const user = { id, name };
    this.users.set(id, user);
    return user;
  }
}

@Controller("/api/users")
class UserController {
  public constructor(
    private readonly service: UserService,
    @Inject(CONFIG_SERVICE_TOKEN) private readonly config: ConfigService,
  ) {}

  @GET("/:id")
  public async getUser(@Param("id") id: string) {
    const user = await this.service.find(id);
    if (!user) {
      return { error: "Not Found" };
    }
    return user;
  }

  @POST("/")
  public createUser(@Body("name") name: string) {
    return this.service.create(name);
  }
}

// Define module with Symbol-based provider
@Module({
  controllers: [UserController],
  providers: [
    {
      provide: UserService,
      useClass: UserServiceImpl,
    },
  ],
  exports: [UserService],
})
class UserModule {}

// Configure modules
ConfigModule.forRoot({
  defaultConfig: {
    app: {
      name: "Advanced App",
      port: 3100,
    },
  },
});

// Register module and start application
@Module({
  imports: [ConfigModule],
  controllers: [UserController],
  providers: [
    {
      provide: UserService,
      useClass: UserServiceImpl,
    },
  ],
})
class AppModule {}

const app = new Application({ port: 3100 });
app.registerModule(AppModule);
app.listen();

Key points:

  • Interface-based design: Define contracts with TypeScript interfaces
  • Symbol tokens: Use Symbol() for type-safe dependency injection tokens
  • Module providers: Register providers using provide: Symbol, useClass: Implementation
  • Type-safe injection: Inject services using @Inject(Symbol) with interface types

Examples & Extensions

📚 Organized Examples

Examples are organized by difficulty and feature category:

  • Quick Start - Get started in 5 minutes

    • 01-hello-world.ts - Minimal example (5 lines)
    • 02-basic-routing.ts - HTTP methods and route parameters
    • 03-dependency-injection.ts - DI basics with services
  • Core Features - Deep dive into framework mechanics

    • basic-app.ts - DI + Logger + Swagger + Config integration
    • multi-module-app.ts - Module dependencies and organization
    • context-scope-app.ts - Request scoping and ContextService
    • full-app.ts - Validation, uploads, static files, WebSocket
    • lifecycle-app.ts - Lifecycle hooks (OnModuleInit, OnModuleDestroy, etc.)
    • async-config-app.ts - Async module config with forRootAsync()
    • idle-timeout-app.ts - Global and route-level idleTimeout
  • Official Modules - Ready-to-use modules

    • auth-app.ts - JWT + OAuth2 authentication (with Web UI)
    • session-app.ts - Session management
    • database-app.ts - Database connection and queries
    • nacos-auto-register-app.ts - Nacos autoRegister switch example
    • orm-app.ts - Entity + Repository pattern
    • cache-app.ts - Caching with decorators
    • queue-app.ts - Task queues and Cron jobs
    • dashboard-app.ts - Built-in monitoring dashboard (with Web UI)
  • Advanced - Custom framework extensions

    • custom-decorator-app.ts - Create custom decorators
    • apply-decorators-app.ts - Decorator composition with applyDecorators()
    • testing-app.ts - TestingModule with mock providers and HTTP client
    • type-safe-client-app.ts - Type-safe API client from controller metadata
    • debug-app.ts - Request recording and replay (with Web UI)
    • websocket-chat-app.ts - Complete WebSocket chat with rooms (with Web UI)
    • microservice-app.ts - Microservices architecture
  • Real World - Production-ready examples

    • database-test-app.ts - Database connection tester (Web UI)
    • perf/app.ts - Performance benchmarking
    • perf/cluster-app.ts - Zero-config cluster with ClusterManager

🔑 Symbol + Interface Pattern

This framework features a unique Symbol + Interface co-naming pattern that solves TypeScript's type erasure problem:

// 1. Define interface and Symbol with same name
interface UserService {
  find(id: string): Promise<User>;
}
const UserService = Symbol('UserService');

// 2. Implement interface
@Injectable()
class UserServiceImpl implements UserService {
  async find(id: string) { ... }
}

// 3. Register with Symbol token
@Module({
  providers: [{
    provide: UserService,      // Symbol token
    useClass: UserServiceImpl, // Implementation
  }],
})

// 4. Inject with type safety
constructor(private readonly userService: UserService) {}

Key: Import as import { UserService } (not import type { UserService }).

See Symbol + Interface Pattern Guide for details.

🔌 Extensions

  • packages/bun-server/src/extensions/: Official extensions (e.g. LoggerExtension) for plugging in external capabilities.

📖 Complete Example Index

See examples/README.md for the complete catalog with learning paths, difficulty ratings, and usage scenarios.

Benchmark Suite

Internal Micro-benchmarks

PerformanceHarness & StressTester based benchmarks:

| Script | Description | | ----------------- | --------------------------------------------------------------------- | | router.bench.ts | static/dynamic route hits, router.handle and stress runs | | di.bench.ts | singleton vs factory resolves, nested dependencies, concurrent stress |

bun benchmark/router.bench.ts
bun benchmark/di.bench.ts

Framework Comparison (bun-server vs Express vs NestJS)

Real HTTP load testing with wrk, comparing bun-server against Express 5 and NestJS 11. All frameworks run on the same Bun runtime to isolate framework overhead.

Prerequisites: wrk (brew install wrk / apt install wrk). The script automatically raises ulimit -n to 10240 for child processes.

bun benchmark/run-wrk-compare.ts        # full comparison (3 tiers)
TIER=0 bun benchmark/run-wrk-compare.ts  # Light tier only
bun benchmark/run-wrk.ts                 # bun-server only (3 tiers)

Environment: Apple M2 Pro (8P + 4E cores) / darwin arm64 / Bun 1.3.10

Req/Sec (Light: -t2 -c50 -d10s)

| Endpoint | bun-server | Express | NestJS | |-----------------------|--------------|----------|----------| | GET /ping | 31.41k | 30.01k | 26.52k | | GET /json | 28.22k | 25.99k | 23.64k | | GET /users/:id | 30.88k | 29.91k | 25.62k | | GET /search?q= | 29.96k | 28.70k | 25.17k | | POST /users | 27.65k | 21.37k | 19.38k | | POST /users/validated | 26.60k | 21.28k | 18.93k | | GET /middleware | 29.52k | 28.57k | 24.69k | | GET /headers | 30.98k | 29.57k | 26.43k | | GET /io | 21.37k | 19.46k | 18.49k |

Zero errors across all frameworks and tiers. See the full report for Medium and Heavy tier results.

📊 Full comparison report (3 tiers, latency breakdown, per-framework details): benchmark/REPORT_COMPARE.md

📋 Single-framework detailed report: benchmark/REPORT.md

Multi-process Benchmark (reusePort, Linux only)

bun benchmark/run-wrk-cluster.ts          # default: 1 worker per CPU core
WORKERS=4 bun benchmark/run-wrk-cluster.ts

Spawns N workers sharing the same port via SO_REUSEPORT. The kernel distributes connections across processes. Report saved to benchmark/REPORT_CLUSTER.md. Note: reusePort only works on Linux; macOS/Windows silently ignore it.

Docs & Localization

  • English (default): docs/api.md, docs/guide.md, docs/best-practices.md, docs/migration.md, docs/extensions.md, docs/deployment.md, docs/performance.md, docs/troubleshooting.md, docs/error-handling.md, docs/request-lifecycle.md.
  • Chinese: mirrored under docs/zh/. If something is missing, please fall back to the English source.
  • Skills & Troubleshooting:
    • In-repo troubleshooting cases: skills/
    • Agent skills repository: bun-server-skills
    • Install for Cursor (pick one):
      # bun
      bunx skills add https://github.com/dangaogit/bun-server-skills --skill bun-server-best-practices
      # npx
      npx skills add https://github.com/dangaogit/bun-server-skills --skill bun-server-best-practices
      # pnpm
      pnpm dlx skills add https://github.com/dangaogit/bun-server-skills --skill bun-server-best-practices
      # yarn
      yarn dlx skills add https://github.com/dangaogit/bun-server-skills --skill bun-server-best-practices
      # git (manual)
      mkdir -p ~/.cursor/skills && git clone https://github.com/dangaogit/bun-server-skills.git ~/.cursor/skills/bun-server-skills

Roadmap

Release history and changelogs are tracked in the .changelog/ directory.

AI-Assisted Development

Bun Server is designed to work seamlessly with AI coding assistants like Cursor, GitHub Copilot, and others. The framework includes source code and tests in the npm package distribution, enabling AI tools to:

  • Understand framework internals: AI can analyze the actual implementation code, not just type definitions, providing more accurate suggestions.
  • Provide context-aware help: When you ask about framework features, AI can reference the actual source code to give precise answers.
  • Suggest best practices: AI can learn from the framework's patterns and suggest similar approaches in your code.
  • Debug more effectively: AI can trace through the framework code to help diagnose issues.

Best Practices for AI-Assisted Development

  1. Reference framework source: When working with Bun Server, AI tools can access the source code at node_modules/@dangao/bun-server/src/ to understand implementation details.

  2. Use type hints: The framework provides comprehensive TypeScript types. Leverage these in your code to help AI understand your intent better.

  3. Follow framework patterns: The included source code serves as a reference for framework patterns. Ask AI to suggest code that follows similar patterns.

  4. Leverage test examples: The included test files demonstrate usage patterns and edge cases. Reference these when asking AI for implementation help.

  5. Ask specific questions: Since AI can access the framework source, you can ask specific questions like "How does the DI container resolve dependencies?" and get accurate answers based on the actual code.

Engineering Guidelines

  • Comments & log messages must be in English to keep the codebase international-friendly.
  • Documentation defaults to English; Chinese copies live in docs/zh/.
  • Benchmarks belong to benchmark/ and should run inside Bun environments.

Contributing

  1. Fork & create a feature branch.
  2. Run bun test (and relevant benchmarks if the change affects performance).
  3. Submit a PR with a clear description and test evidence.

Issues and discussions are welcome for new ideas or perf bottlenecks.

License

Released under the MIT License.

Other Languages

Enjoy building on Bun Server!