Get up and running with Bungate in less than 5 minutes!
- Installation
- Your First Gateway
- Adding Routes
- Load Balancing
- Adding Security
- Running Your Gateway
- Testing Your Setup
- Next Steps
- Bun >= 1.2.18 (Install Bun)
# Create a new project
mkdir my-gateway && cd my-gateway
bun init -y
# Install Bungate
bun add bungateCreate a file called gateway.ts:
import { BunGateway } from 'bungate'
// Create a simple gateway
const gateway = new BunGateway({
server: { port: 3000 },
})
// Add your first route
gateway.addRoute({
pattern: '/api/*',
target: 'https://jsonplaceholder.typicode.com',
})
// Start the gateway
await gateway.listen()
console.log('π Gateway running on http://localhost:3000')Run it:
bun run gateway.tsTest it:
curl http://localhost:3000/api/posts/1Routes define how traffic is forwarded. You can add multiple routes with different patterns:
import { BunGateway } from 'bungate'
const gateway = new BunGateway({
server: { port: 3000 },
})
// API route
gateway.addRoute({
pattern: '/api/*',
target: 'http://api-service:3001',
})
// Static content route
gateway.addRoute({
pattern: '/static/*',
target: 'http://cdn-service:3002',
})
// Health check route
gateway.addRoute({
pattern: '/health',
handler: async () =>
new Response(JSON.stringify({ status: 'ok' }), {
headers: { 'Content-Type': 'application/json' },
}),
})
await gateway.listen()Distribute traffic across multiple backend servers:
import { BunGateway } from 'bungate'
const gateway = new BunGateway({
server: { port: 3000 },
})
gateway.addRoute({
pattern: '/api/*',
loadBalancer: {
strategy: 'least-connections', // or 'round-robin', 'weighted', etc.
targets: [
{ url: 'http://api-server-1:3001' },
{ url: 'http://api-server-2:3001' },
{ url: 'http://api-server-3:3001' },
],
healthCheck: {
enabled: true,
interval: 15000, // Check every 15 seconds
timeout: 5000, // 5 second timeout
path: '/health', // Health check endpoint
},
},
})
await gateway.listen()
console.log('π Load-balanced gateway running!')Available strategies:
round-robin- Distribute evenly across all targetsleast-connections- Route to server with fewest connectionsweighted- Distribute based on server weightsip-hash- Session affinity based on client IPrandom- Random distributionp2c- Power of two choiceslatency- Route to fastest serverweighted-least-connections- Weighted by connections and capacity
See Load Balancing Guide for detailed information.
Protect your services from abuse:
gateway.addRoute({
pattern: '/api/*',
target: 'http://api-service:3001',
rateLimit: {
max: 100, // 100 requests
windowMs: 60000, // per minute
keyGenerator: (req) => {
// Rate limit by IP address
return req.headers.get('x-forwarded-for') || 'unknown'
},
},
})Add JWT authentication:
const gateway = new BunGateway({
server: { port: 3000 },
auth: {
secret: process.env.JWT_SECRET,
jwtOptions: {
algorithms: ['HS256'],
issuer: 'https://auth.myapp.com',
},
excludePaths: ['/health', '/auth/login'],
},
})
gateway.addRoute({
pattern: '/api/*',
target: 'http://api-service:3001',
// This route automatically requires JWT authentication
})See Authentication Guide for more options including API keys and OAuth2.
Enable HTTPS with TLS:
const gateway = new BunGateway({
server: { port: 443 },
security: {
tls: {
enabled: true,
cert: './cert.pem',
key: './key.pem',
minVersion: 'TLSv1.3',
redirectHTTP: true,
redirectPort: 80,
},
},
})See TLS Configuration Guide for detailed setup.
# Run with hot reload
bun --watch gateway.ts# Build (optional)
bun build gateway.ts --outfile dist/gateway.js
# Run in production
NODE_ENV=production bun run gateway.tsScale horizontally with multiple worker processes:
const gateway = new BunGateway({
server: { port: 3000 },
cluster: {
enabled: true,
workers: 4, // Number of worker processes
},
})See Clustering Guide for advanced cluster management.
curl http://localhost:3000/health# GET request
curl http://localhost:3000/api/users
# POST request
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name": "John Doe"}'
# With authentication
curl http://localhost:3000/api/users \
-H "Authorization: Bearer YOUR_JWT_TOKEN"If you enabled metrics:
curl http://localhost:3000/metrics# Install wrk
brew install wrk # macOS
# or
apt-get install wrk # Linux
# Run load test
wrk -t4 -c100 -d30s http://localhost:3000/api/healthNow that you have a basic gateway running, explore more features:
- Authentication Guide - JWT, API keys, OAuth2
- Load Balancing - Strategies and configuration
- Clustering - Multi-process scaling
- Security Guide - Enterprise security features
- TLS Configuration - HTTPS setup
- Troubleshooting - Common issues and solutions
- API Reference - Complete API documentation
- Examples - Real-world use cases
-
Enable Metrics & Monitoring
const gateway = new BunGateway({ metrics: { enabled: true }, logger: new PinoLogger({ level: 'info' }), })
-
Add Circuit Breakers
gateway.addRoute({ pattern: '/api/*', target: 'http://api-service:3001', circuitBreaker: { enabled: true, failureThreshold: 5, timeout: 5000, resetTimeout: 30000, }, })
-
Configure CORS
const gateway = new BunGateway({ cors: { origin: ['https://myapp.com'], credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE'], }, })
-
Add Custom Middleware
gateway.addRoute({ pattern: '/api/*', target: 'http://api-service:3001', middlewares: [ async (req, next) => { console.log(`Request: ${req.method} ${req.url}`) const response = await next() console.log(`Response: ${response.status}`) return response }, ], })
- VS Code Extension: Enable Bun extension for better TypeScript support
- Testing: Use
bun:testfor testing your gateway configuration - Debugging: Set
level: 'debug'in logger for detailed logs
- π GitHub Repository
- π Report Issues
- π¬ Discussions
- π Star on GitHub
Ready to build something amazing? Check out the Examples for real-world implementations!