-
Notifications
You must be signed in to change notification settings - Fork 7
/
middleware.ts
35 lines (29 loc) · 993 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
30
31
32
33
34
35
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server'
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.cachedFixedWindow(10, '10s'),
ephemeralCache: new Map(),
analytics: true
})
export default async function middleware(
request: NextRequest,
event: NextFetchEvent
): Promise<Response | undefined> {
const ip = request.ip ?? '127.0.0.1'
const { success, pending, limit, reset, remaining } = await ratelimit.limit(
`ratelimit_middleware_${ip}`
)
event.waitUntil(pending)
const res = success
? NextResponse.next()
: NextResponse.redirect(new URL('/api/blocked', request.url))
res.headers.set('X-RateLimit-Limit', limit.toString())
res.headers.set('X-RateLimit-Remaining', remaining.toString())
res.headers.set('X-RateLimit-Reset', reset.toString())
return res
}
export const config = {
matcher: '/api/generate'
}