Skip to content

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.

At a Glance

  • NestJS-style architecture — modules, controllers and services with full dependency injection via Effect.ts
  • ArkType validation — one schema is the TypeScript type, the runtime check and the OpenAPI spec, wired end to end
  • Built-in Prometheus metrics and OpenTelemetry tracing — no community packages needed
  • Redis / in-memory caching with decorator-driven TTL
  • Typed environment variables with validation and defaults
  • WebSocket support — Socket.IO protocol, rooms, guards, typed clients
  • Queue system@Cron, @Interval, @Timeout and @Subscribe decorators
  • Drizzle ORM integration — database access with migrations
  • NATS / JetStream — message bus for microservices
  • OpenAPI / Swagger — generated from ArkType schemas and route decorators

Each of these is broken down below, and compared against other frameworks in Framework Comparison.

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

One @UseGuards() across HTTP routes, WebSocket @OnMessage handlers and queue @Subscribe consumers — class-level or method-level, with constructor DI on all three. Denial per transport: HTTP 403 (200 with httpEnvelope), a WebSocket error frame that leaves the socket open, a queue nack(false) with no redelivery. → API Reference

Interceptors

Universal handler wrapping across HTTP, WebSocket, and Queue transports. Use @UseInterceptors() at any level. Built-in: LoggingInterceptor, TimeoutInterceptor, CacheInterceptor. → API Reference

Middleware

Request/response middleware with @UseMiddleware decorator. Supports middleware chaining on individual routes. → API Reference

File Upload

Built-in multipart/form-data and JSON+base64 file upload support. @UploadedFile() for single files, @UploadedFiles() for multiple, @FormField() for non-file form fields — all with automatic content type detection. → API Reference

Extract cookie values directly with @Cookie() decorator. Works alongside @Header(), @Query(), and other parameter decorators. → 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, @OnMessage. 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)

OneBunApplication Multi-Service Mode

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)

Out-of-the-Box Validation

ArkType is re-exported from @onebun/core — no additional packages, no bridge libraries, no Swagger patches. One schema gives you:

  • TypeScript type (compile-time safety)
  • Runtime validation (request body, query params)
  • OpenAPI 3.1 schema (auto-generated documentation)

Install the framework — validation and OpenAPI work. No nestjs-zod, no patchNestJsSwagger(), no setup.

@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 (enabled by default — no configuration needed)
  • A configured database is required at boot: an unreachable server or a failing migration makes app.start() reject before the HTTP server binds. Opt out with allowDegradedStart: true in forRoot(), or DB_ALLOW_DEGRADED_START=true on the environment path. → Startup Contract

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. Choosing it makes Redis a startup dependency: unreachable within connectTimeout (default 5000ms) and app.start() fails without the listener ever opening, unless allowDegradedStart: true / CACHE_ALLOW_DEGRADED_START=true accepts a process-local cache instead. getBackendStatus() reports which backend is actually serving.
  • Batch operations: mget, mset
  • 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 — idempotent methods only by default; POST and PATCH must opt in via retries.methods. See the defaults table.
  • 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(), @Gauged()
  • 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 OneBunApplication multi-service mode → API Reference

Production Features

Graceful Shutdown

Enabled by default. On SIGTERM/SIGINT the application first refuses new requests with 503 while the listener stays open, drains the requests already being served, and only then closes the listener and runs the destroy hooks — so a rolling deploy stops cutting responses that were mid-flight. Bounded by shutdownTimeout (default 15s), idempotent, and in multi-service mode a single parent handler stops every service.

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 — and in OneBun the same decorator covers WebSocket and queue handlers too
  • Middleware support

Improved in OneBun

  • Validation: ArkType schema = TypeScript type = OpenAPI spec = runtime validation, wired out of the box (NestJS teams can achieve similar workflows with nestjs-zod — OneBun ships it without extra packages)
  • 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

  • GraphQL integration (post-1.0 consideration)
  • CQRS module
  • Extensive third-party ecosystem

Feature Comparison

How OneBun compares to other TypeScript backend frameworks.

Legend: ✅ built-in · 🔌 plugin/adapter · 👥 community · ❌ none

FeatureOneBunNestJSHonoElysia
DI / IoC container✅ Effect.Context✅ Custom container
Module system✅ @Module✅ @Module
Decorator routing
Guards / Auth👥👥
Middleware
Validation✅ ArkType🔌 class-validator👥✅ TypeBox
OpenAPI generation✅ Auto from schemas🔌 @nestjs/swagger👥
WebSocket✅ Native + Socket.IO🔌 @nestjs/websockets👥
File upload🔌 multer👥
Queue / Scheduler✅ In-memory, Redis, NATS🔌 @nestjs/bull
Prometheus metrics✅ @onebun/metrics👥
OpenTelemetry tracing✅ @onebun/trace👥👥👥
Structured logging✅ @onebun/logger👥👥👥
Database (ORM)✅ Drizzle🔌 TypeORM/Prisma
Caching✅ In-memory + Redis🔌 @nestjs/cache-manager
Env validation✅ @onebun/envs🔌 @nestjs/config
Multi-service✅ Single image
Graceful shutdown🔌
GraphQL❌ (post-1.0)🔌 @nestjs/graphql👥👥
Interceptors / Pipes✅ hooks
CQRS🔌 @nestjs/cqrs
Node.js support❌ Bun only❌ Bun only
Third-party ecosystem🆕 Growing✅ Mature✅ Growing👥 Growing

Released under the MPL-2.0 License.