forked from m-abdelwahab/feedback-widget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
34 lines (27 loc) · 953 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
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server';
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.fixedWindow(10, '10 s'),
});
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(
`mw_${ip}`
);
event.waitUntil(pending);
const res = success
? NextResponse.next(request)
: NextResponse.rewrite(new URL('/api/blocked', request.url), request);
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/feedback',
};