Skip to content

Latest commit

Β 

History

History
381 lines (291 loc) Β· 7.92 KB

File metadata and controls

381 lines (291 loc) Β· 7.92 KB

πŸš€ Quick Start Guide

Get up and running with Bungate in less than 5 minutes!

Table of Contents

Installation

Prerequisites

Install Bungate

# Create a new project
mkdir my-gateway && cd my-gateway
bun init -y

# Install Bungate
bun add bungate

Your First Gateway

Create 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.ts

Test it:

curl http://localhost:3000/api/posts/1

Adding Routes

Routes 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()

Load Balancing

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 targets
  • least-connections - Route to server with fewest connections
  • weighted - Distribute based on server weights
  • ip-hash - Session affinity based on client IP
  • random - Random distribution
  • p2c - Power of two choices
  • latency - Route to fastest server
  • weighted-least-connections - Weighted by connections and capacity

See Load Balancing Guide for detailed information.

Adding Security

Rate Limiting

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'
    },
  },
})

Authentication

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.

TLS/HTTPS

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.

Running Your Gateway

Development Mode

# Run with hot reload
bun --watch gateway.ts

Production Mode

# Build (optional)
bun build gateway.ts --outfile dist/gateway.js

# Run in production
NODE_ENV=production bun run gateway.ts

With Cluster Mode

Scale 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.

Testing Your Setup

Basic Health Check

curl http://localhost:3000/health

Test API Routes

# 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"

Check Metrics

If you enabled metrics:

curl http://localhost:3000/metrics

Load Testing

# Install wrk
brew install wrk  # macOS
# or
apt-get install wrk  # Linux

# Run load test
wrk -t4 -c100 -d30s http://localhost:3000/api/health

Next Steps

Now that you have a basic gateway running, explore more features:

πŸ“š Documentation

🎯 Common Next Steps

  1. Enable Metrics & Monitoring

    const gateway = new BunGateway({
      metrics: { enabled: true },
      logger: new PinoLogger({ level: 'info' }),
    })
  2. Add Circuit Breakers

    gateway.addRoute({
      pattern: '/api/*',
      target: 'http://api-service:3001',
      circuitBreaker: {
        enabled: true,
        failureThreshold: 5,
        timeout: 5000,
        resetTimeout: 30000,
      },
    })
  3. Configure CORS

    const gateway = new BunGateway({
      cors: {
        origin: ['https://myapp.com'],
        credentials: true,
        methods: ['GET', 'POST', 'PUT', 'DELETE'],
      },
    })
  4. 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
        },
      ],
    })

πŸ› οΈ Development Tools

  • VS Code Extension: Enable Bun extension for better TypeScript support
  • Testing: Use bun:test for testing your gateway configuration
  • Debugging: Set level: 'debug' in logger for detailed logs

🌐 Community & Support


Ready to build something amazing? Check out the Examples for real-world implementations!