The Lightning-Fast HTTP Gateway & Load Balancer for the Modern Web. Zero config, maximum performance.
Built for developers who demand performance without sacrificing developer experience
Optimized specifically for Bun's runtime with minimal overhead. Achieves 18K+ requests/second with single-digit millisecond average latency and sub-30ms 99th percentile response times in production benchmarks.
Full TypeScript support with comprehensive type definitions for all APIs. Enjoy excellent IDE autocomplete, type safety, and inline documentation as you build.
Works out of the box with sensible defaults. Get started in seconds without sacrificing power, flexibility, or performance. Production-ready from day one.
8 intelligent strategies: round-robin, least-connections, weighted, ip-hash, random, p2c (power-of-two-choices), latency-based, and weighted-least-connections. Session affinity with cookie-based persistence.
Circuit breakers, health checks, auto-failover, timeout management, and graceful degradation. Built for reliability and resilience in production environments.
Production-grade security with TLS/HTTPS, input validation, CSRF protection, security headers, JWT key rotation, and trusted proxy validation. Built-in protection against injection attacks, information disclosure, and DoS attacks.
Production-ready HTTP gateway with full TypeScript support and intelligent load balancing
// Install: bun add bungate
import { BunGateway } from 'bungate'
// Create gateway with cluster mode & auth
const gateway = new BunGateway({
server: { port: 3000 },
cluster: {
enabled: true,
workers: 4 // Multi-process
},
auth: {
secret: process.env.JWT_SECRET,
excludePaths: ['/health', '/auth/*'],
},
metrics: { enabled: true },
})
// Intelligent load balancing with health checks
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'least-connections',
targets: [
{ url: 'http://api1.example.com' },
{ url: 'http://api2.example.com' },
{ url: 'http://api3.example.com' },
],
healthCheck: {
enabled: true,
interval: 15000,
path: '/health',
},
},
circuitBreaker: {
enabled: true,
failureThreshold: 5
},
})
// Rate limiting with JWT auth
gateway.addRoute({
pattern: '/admin/*',
target: 'http://admin.example.com',
rateLimit: {
max: 100,
windowMs: 60000,
keyGenerator: (req) => req.user?.id || 'unknown',
},
})
await gateway.listen()
console.log('🚀 Bungate cluster running on :3000')
Choose the right algorithm for your traffic patterns and architecture
Equal distribution across all targets. Perfect for stateless services with uniform capacity.
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'round-robin',
targets: [
{ url: 'http://api1.example.com' },
{ url: 'http://api2.example.com' },
{ url: 'http://api3.example.com' },
],
},
})
Route to the server with fewest active connections. Ideal for variable request durations.
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'least-connections',
targets: [
{ url: 'http://api1.example.com' },
{ url: 'http://api2.example.com' },
],
},
})
Distribute based on server capacity and weights. Perfect for heterogeneous server specs.
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'weighted',
targets: [
{ url: 'http://api1.example.com', weight: 70 },
{ url: 'http://api2.example.com', weight: 20 },
{ url: 'http://api3.example.com', weight: 10 },
],
},
})
Consistent routing based on client IP. Maintains session affinity for stateful applications.
gateway.addRoute({
pattern: '/app/*',
loadBalancer: {
strategy: 'ip-hash',
targets: [
{ url: 'http://app1.example.com' },
{ url: 'http://app2.example.com' },
],
},
})
Randomized distribution for simple, even load. Low overhead with good distribution.
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'random',
targets: [
{ url: 'http://api1.example.com' },
{ url: 'http://api2.example.com' },
],
},
})
Pick the better of two random targets by load/latency. Balances efficiency with performance.
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'p2c',
targets: [
{ url: 'http://api1.example.com' },
{ url: 'http://api2.example.com' },
{ url: 'http://api3.example.com' },
],
},
})
Prefer the target with lowest average response time. Optimizes for user experience.
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'latency',
targets: [
{ url: 'http://api1.example.com' },
{ url: 'http://api2.example.com' },
],
},
})
Combines weights with connection count. Best for mixed capacity with variable load.
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'weighted-least-connections',
targets: [
{ url: 'http://api1.example.com', weight: 3 },
{ url: 'http://api2.example.com', weight: 2 },
{ url: 'http://api3.example.com', weight: 1 },
],
},
})
Production-grade security features that protect against OWASP Top 10 threats
Encrypted communications with automatic HTTPS upgrade
const gateway = new BunGateway({
server: { port: 443 },
security: {
tls: {
enabled: true,
cert: './cert.pem',
key: './key.pem',
minVersion: 'TLSv1.3',
cipherSuites: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
],
redirectHTTP: true, // Auto-redirect :80 → :443
redirectPort: 80,
},
},
})
// All traffic now encrypted with TLS 1.3! 🔐
Secure authentication with automatic key rotation and JWKS support
const gateway = new BunGateway({
security: {
jwtKeyRotation: {
secrets: [
{
key: process.env.JWT_SECRET_NEW,
algorithm: 'HS256',
kid: '2024-11',
primary: true // New tokens use this
},
{
key: process.env.JWT_SECRET_OLD,
algorithm: 'HS256',
kid: '2024-10',
deprecated: true // Still validates old tokens
},
],
jwksUri: 'https://auth.example.com/.well-known/jwks.json',
jwksRefreshInterval: 3600000, // 1 hour
},
},
})
gateway.addRoute({
pattern: '/api/*',
target: 'http://backend:3000',
auth: {
secret: process.env.JWT_SECRET_NEW,
jwtOptions: {
algorithms: ['HS256', 'RS256'],
issuer: 'https://auth.example.com',
},
},
})
Protection against injection attacks and malformed data
const gateway = new BunGateway({
security: {
inputValidation: {
maxPathLength: 2048,
maxHeaderSize: 16384,
maxHeaderCount: 100,
allowedPathChars: /^[a-zA-Z0-9\/_\-\.~%]+$/,
blockedPatterns: [
/\.\./, // Directory traversal
/%00/, // Null byte injection
/<script>/i, // XSS attempts
/javascript:/i, // JavaScript protocol
],
sanitizeHeaders: true,
},
sizeLimits: {
maxBodySize: 10 * 1024 * 1024, // 10 MB
maxUrlLength: 2048,
},
},
})
// Requests with '../../../etc/passwd' → Blocked! 🚫
// Requests with '<script>alert(1)</script>' → Blocked! 🚫
HSTS, CSP, X-Frame-Options, and more automatically applied
const gateway = new BunGateway({
security: {
securityHeaders: {
enabled: true,
hsts: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
},
contentSecurityPolicy: {
directives: {
'default-src': ["'self'"],
'script-src': ["'self'"],
'style-src': ["'self'"],
'frame-ancestors': ["'none'"],
},
},
xFrameOptions: 'DENY',
xContentTypeOptions: true,
referrerPolicy: 'strict-origin-when-cross-origin',
},
},
})
// Every response gets security headers automatically! 🛡️
Secure client IP extraction with CDN support
const gateway = new BunGateway({
security: {
trustedProxies: {
enabled: true,
trustedIPs: [
'10.0.0.0/8', // Private network
'172.16.0.0/12', // Private network
],
trustedNetworks: [
'cloudflare', // Cloudflare IPs
'aws', // AWS CloudFront
'gcp', // Google Cloud CDN
'azure', // Azure CDN
],
maxForwardedDepth: 3,
},
},
})
// Prevents IP spoofing attacks! 🎯
// Only trusts X-Forwarded-For from verified proxies
All security features combined for maximum protection
import { BunGateway } from 'bungate'
const gateway = new BunGateway({
server: { port: 443 },
security: {
// TLS/HTTPS
tls: {
enabled: true,
cert: process.env.TLS_CERT,
key: process.env.TLS_KEY,
minVersion: 'TLSv1.3',
redirectHTTP: true,
redirectPort: 80,
},
// Input validation
inputValidation: {
maxPathLength: 2048,
sanitizeHeaders: true,
blockedPatterns: [/\.\./, /%00/, /<script>/i],
},
// Security headers
securityHeaders: {
enabled: true,
hsts: { maxAge: 31536000, preload: true },
contentSecurityPolicy: {
directives: {
'default-src': ["'self'"],
'frame-ancestors': ["'none'"],
},
},
xFrameOptions: 'DENY',
},
// Size limits
sizeLimits: {
maxBodySize: 10 * 1024 * 1024,
maxUrlLength: 2048,
},
// Trusted proxies
trustedProxies: {
enabled: true,
trustedNetworks: ['cloudflare', 'aws'],
},
// JWT key rotation
jwtKeyRotation: {
secrets: [
{ key: process.env.JWT_NEW, primary: true },
{ key: process.env.JWT_OLD, deprecated: true },
],
},
},
})
gateway.addRoute({
pattern: '/api/*',
target: 'http://backend:3000',
auth: {
secret: process.env.JWT_NEW,
jwtOptions: { algorithms: ['HS256'] },
},
rateLimit: {
max: 1000,
windowMs: 60000,
},
})
await gateway.listen()
console.log('🔒 Production gateway secured!')
Comprehensive security hardening to protect against modern threats
Full TLS 1.2+ support with configurable cipher suites, automatic HTTP to HTTPS redirection, and certificate validation. Protect against man-in-the-middle attacks with encrypted communications.
Comprehensive input validation and sanitization for paths, headers, and query parameters. Protection against injection attacks, directory traversal, and malformed data with RFC-compliant validation.
Automatic security headers including HSTS, CSP, X-Frame-Options, X-Content-Type-Options, and Referrer-Policy. Configurable Content Security Policy with report-only mode for testing.
Support for multiple JWT secrets with automatic key rotation. JWKS endpoint integration with automatic refresh, zero-downtime key updates, and deprecation warnings for monitoring.
Secure client IP extraction with trusted proxy configuration. CIDR notation support, predefined trusted networks (Cloudflare, AWS, GCP, Azure), and forwarded header chain validation.
Built-in Cross-Site Request Forgery protection with automatic token generation and validation. Configurable for state-changing operations with path-based exclusions.
Configurable limits for request body, headers, URL length, and query parameters. Protection against resource exhaustion and DoS attacks with early rejection and appropriate HTTP status codes.
Cryptographically secure session ID generation with minimum 128 bits of entropy. Automatic expiration, secure cookie attributes (Secure, HttpOnly, SameSite), and session validation.
Production-safe error responses that prevent information disclosure. Sanitized error messages, no stack traces in production, and comprehensive internal logging for debugging.
Enterprise-grade features for modern API gateways
Multi-process clustering for maximum CPU utilization. Zero-downtime rolling restarts with SIGUSR2, dynamic scaling (scaleUp/Down/To), and exponential backoff with jitter for worker restarts.
8 different strategies including round-robin, least-connections, weighted, ip-hash, latency-based, and power-of-two-choices for optimal traffic distribution.
Automatic failure detection and recovery with configurable thresholds. Prevent cascading failures and improve system resilience.
Secure JSON Web Token authentication with JWKS support, role-based authorization, and custom claims validation built right in.
Powerful async/await middleware pipeline for custom request/response processing. CORS support, path rewriting, URL transformation, and comprehensive lifecycle hooks.
Prometheus metrics, structured JSON logging with request tracing, health check APIs, real-time statistics, and custom metric collection for complete visibility.
Flexible rate limiting with custom key generation. Protect your APIs from abuse with per-IP, per-user, or custom limits and configurable time windows.
Leveraging Bun's speed with developer-friendly APIs
Build high-performance HTTP gateways with Bun today