api/src/lib/ratelimit/index.ts

24 lines · 943 bytes

1 symbol in this file
 1/**
 2 * Rate limit middleware factory
 3 * Basic measure to prevent obvious abuse for public routes
 4 * Uses CF's native rate-limiting API, configurable in wrangler.toml
 5 * The binding is selectable, so different routes can use different limits
 6 * By default, there's no rate-limiting on self-hosted/Bun versions
 7 */
 8import type { MiddlewareHandler } from 'hono'
 9import { ApiError } from '@/lib/errors'
10import type { AppEnv, HonoEnv, RateLimiter } from '@/types'
11
12export const rateLimit =
13  (
14    pick: (env: AppEnv) => RateLimiter | undefined = (env) => env.RATE_LIMIT,
15  ): MiddlewareHandler<HonoEnv> =>
16  async (c, next) => {
17    const limiter = pick(c.env)
18    if (!limiter) return next()
19    const key =
20      c.req.header('cf-connecting-ip') ?? c.req.header('x-forwarded-for') ?? 'anon'
21    const { success } = await limiter.limit({ key })
22    if (!success) throw new ApiError('RATE_LIMITED', 'Too many requests', 429)
23    return next()
24  }