api/src/lib/ratelimit/index.ts
20 lines · 818 bytes
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 * Only applies to unauthenticated requests on the public instance
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 { HonoEnv } from '@/types'
11
12export const rateLimit = (): MiddlewareHandler<HonoEnv> => async (c, next) => {
13 const limiter = c.env.RATE_LIMIT
14 if (!limiter) return next()
15 const key =
16 c.req.header('cf-connecting-ip') ?? c.req.header('x-forwarded-for') ?? 'anon'
17 const { success } = await limiter.limit({ key })
18 if (!success) throw new ApiError('RATE_LIMITED', 'Too many requests', 429)
19 return next()
20}