On this page

Examples (Bun)

Using Node.js? See the Node.js Examples for @joint-ops/hitlimit.

Production-ready rate limiting patterns for Bun applications. Each example includes complete, copy-paste ready code with explanations of why limits are set as they are.

Quick Start Examples

Get rate limiting running in seconds with these minimal setups:

Bun.serve
import { hitlimit } from '@joint-ops/hitlimit-bun'

const limiter = hitlimit({ limit: 100, window: '1m' })

Bun.serve({
  port: 3000,
  async fetch(req) {
    const ip = this.requestIP(req)?.address ?? '127.0.0.1'
    const result = await limiter.check(ip)
    if (!result.allowed) {
      return new Response('Too Many Requests', { status: 429 })
    }
    return new Response('Hello!')
  }
})
Elysia
import { Elysia } from 'elysia'
import { hitlimit } from '@joint-ops/hitlimit-bun/elysia'

new Elysia()
  .use(hitlimit({ limit: 100, window: '1m' }))
  .get('/', () => 'Hello!')
  .listen(3000)
Hono on Bun
import { Hono } from 'hono'
import { hitlimit } from '@joint-ops/hitlimit-bun/hono'

const app = new Hono()

app.use(hitlimit({ limit: 100, window: '1m' }))
app.get('/', (c) => c.text('Hello!'))

export default app

Detailed Examples

Common Patterns

Custom Key Extraction

Bun.serve({
  port: 3000,
  async fetch(req) {
    // Use Bun's native requestIP for accurate client identification
    const ip = this.requestIP(req)?.address ?? '127.0.0.1'

    // Combine IP with route for per-endpoint limits
    const url = new URL(req.url)
    const key = `${ip}:${url.pathname}`

    const result = await limiter.check(key)
    if (!result.allowed) {
      return new Response('Too Many Requests', { status: 429 })
    }

    return handleRequest(req)
  }
})

Multiple Limiters for Different Routes

import { hitlimit } from '@joint-ops/hitlimit-bun'

// Strict limits for authentication endpoints
const authLimiter = hitlimit({ limit: 5, window: '15m' })

// Relaxed limits for general API usage
const apiLimiter = hitlimit({ limit: 100, window: '1m' })

Bun.serve({
  port: 3000,
  async fetch(req) {
    const ip = this.requestIP(req)?.address ?? '127.0.0.1'
    const url = new URL(req.url)

    // Choose limiter based on route
    const limiter = url.pathname.startsWith('/auth')
      ? authLimiter
      : apiLimiter

    const result = await limiter.check(ip)
    if (!result.allowed) {
      return new Response('Too Many Requests', {
        status: 429,
        headers: { 'Retry-After': String(result.retryAfter) }
      })
    }

    return handleRequest(req)
  }
})