This directory contains working examples demonstrating various Bungate features and configurations.
A minimal gateway setup demonstrating basic routing and proxying.
Features:
- Simple route configuration
- Basic proxying
- Minimal setup
Run:
bun run examples/basic.tsProduction-ready security-hardened gateway with comprehensive security features.
Features:
- ✅ TLS 1.3 with strong cipher suites
- ✅ API key authentication
- ✅ Rate limiting per user/IP
- ✅ Security headers (HSTS, CSP, X-Frame-Options)
- ✅ Input validation
- ✅ Request size limits
- ✅ CORS configuration
- ✅ WebSocket support
- ✅ Health checks and metrics
- ✅ Graceful shutdown
Authentication:
- JWT authentication for user endpoints
- API key authentication for public/metrics endpoints
- Multiple authentication strategies
Run:
# Set required environment variables
export JWT_PRIMARY="your-secret-key"
export TLS_CERT_PATH="./examples/cert.pem"
export TLS_KEY_PATH="./examples/key.pem"
# Run the gateway
bun run examples/security-hardened.ts
# Test with API key
curl -H "X-API-Key: public-api-key-1" https://localhost:3443/api/public/test --insecureTest Endpoints:
# Health check (public, no auth)
curl http://localhost:3080/health
# Metrics (requires API key)
curl -H "X-API-Key: metrics-key" http://localhost:3080/metrics
# User API (requires API key - JWT-only not working)
curl -H "X-API-Key: public-api-key-1" https://localhost:3443/api/users/123 --insecure
# Admin API (requires API key)
curl -H "X-API-Key: admin-key" https://localhost:3443/api/admin/users --insecureComprehensive TLS/HTTPS configuration examples.
Includes 7 different scenarios:
- Basic HTTPS - Simple TLS setup
- HTTP Redirect - Automatic HTTP→HTTPS redirect
- Custom Cipher Suites - Advanced TLS configuration
- Mutual TLS (mTLS) - Client certificate authentication
- Buffer Certificates - Loading certs from memory
- Production TLS - Production-grade configuration
- TLS Proxy - HTTPS gateway to HTTP backend
Run an example:
# Basic HTTPS
bun run examples/tls-example.ts
# Follow the prompts to select different examplesTest:
# Basic HTTPS test
curl https://localhost:4443/test --insecure
# With client certificate (mTLS)
curl --cert client-cert.pem --key client-key.pem https://localhost:4443/test --cacert ca.pemComprehensive load balancing configuration with all available strategies.
Load Balancing Strategies:
round-robin- Distribute evenly in sequenceleast-connections- Route to server with fewest active connectionsrandom- Random distributionweighted- Control distribution percentagesip-hash- Session affinity based on client IPp2c(power-of-two-choices) - Pick best of two random serverslatency- Route to fastest responding serverweighted-least-connections- Weighted with connection awareness
Features:
- Health checks
- Circuit breakers
- Retry logic
- Failover handling
Run:
# Start backend servers first
bun run examples/echo-server-0.ts &
bun run examples/echo-server-1.ts &
# Start the load balancer
bun run examples/lb-example-all-options.ts
# Test
curl http://localhost:3000/api/testMulti-core clustering for maximum performance.
Features:
- Automatic worker spawning
- Load distribution across CPU cores
- Worker health monitoring
- Graceful restarts
- Zero-downtime deployments
Run:
bun run examples/cluster-example.tsInput validation and sanitization examples.
Features:
- Request body validation
- Query parameter validation
- Custom validation rules
- Error handling
Run:
bun run examples/validation-example.ts
# Test validation
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"John","email":"john@example.com","age":25}'echo-server-0.ts,echo-server-1.ts- Test backend servers for load balancing examplescert.pem,key.pem- Self-signed certificates for TLS examples (for development only)
# Install Bun (if not already installed)
curl -fsSL https://bun.sh/install | bash
# Install dependencies
bun install# Generate self-signed certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes \
-subj "/CN=localhost"
# Move to examples directory
mv cert.pem key.pem examples/import { BunGateway } from 'bungate'
const gateway = new BunGateway()
// Basic API key auth
gateway.addRoute({
pattern: '/api/*',
target: 'http://backend:3000',
auth: {
apiKeys: ['key1', 'key2', 'key3'],
apiKeyHeader: 'X-API-Key',
},
})
await gateway.listen(3000)Test:
# Valid request
curl -H "X-API-Key: key1" http://localhost:3000/api/data
# Invalid request
curl -H "X-API-Key: wrong-key" http://localhost:3000/api/data
# Returns: 401 Unauthorizedgateway.addRoute({
pattern: '/api/*',
target: 'http://backend:3000',
auth: {
apiKeys: ['service-key-1', 'service-key-2'],
apiKeyHeader: 'X-API-Key',
apiKeyValidator: async (key: string) => {
// Custom validation logic
console.log('Validating key:', key)
// Check format
if (!key.startsWith('service-')) {
return false
}
// Check against database (example)
const isValid = await checkDatabase(key)
return isValid
},
},
})// Public route - no auth
gateway.addRoute({
pattern: '/public/*',
target: 'http://backend:3000',
})
// Service API - requires API key
gateway.addRoute({
pattern: '/api/services/*',
target: 'http://backend:3000',
auth: {
apiKeys: ['service-key-1'],
apiKeyHeader: 'X-Service-Key',
},
})
// Admin API - requires different API key
gateway.addRoute({
pattern: '/api/admin/*',
target: 'http://backend:3000',
auth: {
apiKeys: ['admin-master-key'],
apiKeyHeader: 'X-Admin-Key',
},
})- Main README - Full documentation
- Security Guide - Security best practices
- TLS Configuration - Detailed TLS guide
- API Documentation - Complete API reference
- Troubleshooting - Common issues and solutions
Found an issue or want to add an example?
- Fork the repository
- Create a new example file
- Update this README
- Submit a pull request
MIT Licensed - see LICENSE for details.