forked from vercel-labs/gemini-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
29 lines (23 loc) · 837 Bytes
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { kv } from '@vercel/kv'
import type { NextFetchEvent, NextRequest } from 'next/server'
import { kasadaHandler } from './lib/kasada/kasada-server'
const MAX_REQUESTS = 50
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
if (req.method === 'POST') {
const realIp = req.headers.get('x-real-ip') || 'no-ip'
const pipeline = kv.pipeline()
pipeline.incr(`rate-limit:${realIp}`)
pipeline.expire(`rate-limit:${realIp}`, 60 * 60 * 24)
const [requests] = (await pipeline.exec()) as [number]
if (process.env.NODE_ENV === 'development') {
return undefined
}
if (requests > MAX_REQUESTS) {
return new Response('Too many requests', { status: 429 })
}
return kasadaHandler(req, ev)
}
}
export const config = {
matcher: ['/', '/chat/:id*', '/share/:id*']
}