Features Overview
OneBun is a complete, batteries-included backend framework for Bun.js. It provides everything needed to build production-grade TypeScript services — from HTTP routing to database integration, from message queues to observability.
Core Framework (@onebun/core)
Dependency Injection & Modules
NestJS-inspired module system with automatic constructor-based DI, module imports/exports, and service scoping. → API Reference
Controllers & Routing
Decorator-based HTTP controllers with @Get, @Post, @Put, @Delete, @Patch. Path parameters, query parameters, body parsing, header extraction. Standardized ApiResponse format across the application. → API Reference
Guards
Custom guard support for authentication and authorization. Write guard functions and apply them via decorators to protect routes. → API Reference
Middleware
Request/response middleware with @UseMiddleware decorator. Supports middleware chaining on individual routes. → API Reference
Static file serving
Serve a static directory (e.g. SPA build) from the same host and port as the API. Configure static.root, optional pathPrefix and fallbackFile (e.g. index.html) for client-side routing. → API Reference
WebSocket (@onebun/core)
WebSocket Gateway
Decorator-based WebSocket handlers with @WebSocketGateway, @SubscribeMessage. Built on Bun's native WebSocket support for maximum performance.
Socket.IO Support
Optional Socket.IO adapter for browser compatibility, rooms, namespaces, and broadcasting.
Typed WebSocket Client
Auto-generated typed client for type-safe frontend ↔ backend WebSocket communication. → API Reference
Microservices (@onebun/core)
MultiServiceApplication
Run multiple services from a single codebase and Docker image:
- Development: all services in one process (
bun run src/index.ts) - Production: one service per process (
ONEBUN_SERVICES=users bun run src/index.ts) - Flexible: any combination via environment variables
Inter-Service Communication
Typed HTTP clients with createServiceDefinition + createServiceClient. HMAC authentication for service-to-service calls.
Kubernetes-Ready
Environment-based service selection, external service URL configuration, single Docker image for all services. → Multi-Service Example
Validation (@onebun/core + ArkType)
Single Source of Truth
One ArkType schema serves as:
- TypeScript type (compile-time safety)
- Runtime validation (request body, query params)
- OpenAPI 3.1 schema (auto-generated documentation)
Zero duplication between types, validation rules, and API docs.
@Body() Validation
Pass ArkType schema to @Body decorator for automatic validation with typed error responses. → API Reference
API Documentation (@onebun/docs)
OpenAPI Auto-Generation
Automatic OpenAPI 3.1 spec from decorators and ArkType schemas. Install @onebun/docs and get Swagger UI with zero configuration.
Documentation Decorators
@ApiTags, @ApiOperation, @ApiResponse for additional metadata. → API Reference
Database (@onebun/drizzle)
Drizzle ORM Integration
Schema-first approach with full type inference. Supports PostgreSQL and SQLite (via bun:sqlite).
Migrations
- CLI:
bunx onebun-drizzle generate/push/studio - Programmatic:
generateMigrations(),pushSchema() - Auto-migrate on startup:
autoMigrate: true
Repository Pattern
BaseRepository with built-in CRUD operations, custom queries via Drizzle query builder. → API Reference
Queue & Scheduler (@onebun/core + @onebun/nats)
Queue System
Background job processing with multiple backends:
- In-memory — zero config, for development and simple use cases
- Redis Pub/Sub — distributed queues via Redis
- NATS — high-performance messaging (via @onebun/nats)
- JetStream — persistent, at-least-once delivery (via @onebun/nats)
Scheduler
Cron-like task scheduling with the same backend options. → API Reference
Caching (@onebun/cache)
CacheModule
- In-memory cache — with TTL, max size, cleanup intervals
- Redis cache — with shared connection pool support
- Batch operations: getMany, setMany, deleteMany
- Cache-aside, invalidation, and warming patterns → API Reference
HTTP Client (@onebun/requests)
createHttpClient()
Full-featured HTTP client with:
- Authentication: Bearer, API Key, Basic, HMAC (inter-service)
- Retries: fixed, linear, exponential backoff strategies
- Typed responses:
ApiResponse<T>with success/error discrimination
Typed Service Clients
createServiceDefinition() + createServiceClient() for type-safe inter-service REST communication without code generation. → API Reference
Observability
Prometheus Metrics (@onebun/metrics)
- Automatic HTTP request metrics (duration, count, status codes)
- System metrics (CPU, memory, event loop, GC)
- Custom metrics: Counter, Gauge, Histogram
- Decorator-based: @Timed(), @Counted()
- Endpoint: GET /metrics → API Reference
OpenTelemetry Tracing (@onebun/trace)
- Automatic HTTP request tracing
- @Span() decorator for custom spans
- Trace context propagation in logs
- Configurable sampling, export to external collectors → API Reference
Structured Logging (@onebun/logger)
- JSON (production) and pretty (development) output
- Log levels: trace, debug, info, warn, error, fatal
- Child loggers with context inheritance
- Automatic trace context in log entries → API Reference
Configuration (@onebun/envs)
Type-Safe Environment Variables
- Schema definition with Env.string(), Env.number(), Env.boolean(), Env.array()
- Validation, defaults, transforms
- Sensitive value masking in logs
- .env file support
- Per-service overrides in MultiServiceApplication → API Reference
Production Features
Graceful Shutdown
Enabled by default. Handles SIGTERM/SIGINT, closes HTTP server, WebSocket connections, and Redis connections.
Shared Redis Connection
Single Redis connection pool shared between Cache, WebSocket, and Queue modules. Reduced memory footprint and connection count.
Effect.js Integration
Internal architecture built on Effect.js for type-safe side effect management. Optional Effect API for advanced use cases.
For NestJS Developers
If you're coming from NestJS, here's what to expect:
Same patterns
- @Module, @Controller, @Service decorators
- Constructor-based dependency injection
- Module imports/exports for service sharing
- Guards for route protection
- Middleware support
Improved in OneBun
- Validation: ArkType schema = TypeScript type = OpenAPI spec = runtime validation (vs class-validator + Swagger decorators + separate TS types in NestJS)
- Microservices: Single Docker image, env-based service selection (vs separate entry points in NestJS)
- Observability: Prometheus metrics + OpenTelemetry tracing built-in (vs community packages in NestJS)
- Performance: Bun.js native, no Express/Fastify adapter layer
- Configuration: Type-safe env schema with sensitive value masking (vs @nestjs/config)
Different approach
- ArkType instead of class-validator/class-transformer
- Drizzle ORM instead of TypeORM (schema-first, not entity-first)
- Effect.js internally (optional for application code)
- Bun.js runtime only (not Node.js compatible)
Not yet available
- Interceptors and Pipes (planned)
- GraphQL integration (planned, separate package)
- CQRS module
- Extensive third-party ecosystem
