-
Notifications
You must be signed in to change notification settings - Fork 7
/
middleware.ts
45 lines (42 loc) · 1.36 KB
/
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
36
37
38
39
40
41
42
43
44
45
// middleware.ts
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!_next/static|_next/image|favicon.ico).*)",
],
};
export function middleware(request: NextRequest) {
const TIMEOUT = 60;
const LIMIT = 5;
const now = Math.floor(Date.now() / 1000);
const cookies = request.cookies.get('usage');
let [timestamp, counter] = (cookies ? cookies.value.split(':') : [now, 0]).map(Number);
counter += 1;
if ( request.nextUrl.pathname === '/api/send' ) {
const isReset = (now - timestamp) > TIMEOUT;
if ( isReset ) counter = 1;
const usage = isReset ? `${now}:1` : `${timestamp}:${counter}`;
const requestHeaders = new Headers(request.headers);
requestHeaders.set('usage', usage);
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
response.cookies.set('usage', usage);
console.log('middleware', {usage, isReset});
if ( counter > LIMIT ) {
request.nextUrl.pathname = '/api/ratelimit';
return NextResponse.redirect(request.nextUrl);
}
return response;
}
return NextResponse.next();
}