-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
39 lines (32 loc) · 1.04 KB
/
middleware.ts
File metadata and controls
39 lines (32 loc) · 1.04 KB
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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { checkRateLimit } from '@/lib/rateLimit';
export function middleware(request: NextRequest) {
// We only run this on API routes
if (request.nextUrl.pathname.startsWith('/api')) {
const ip = request.headers.get('x-forwarded-for') ?? request.headers.get('x-real-ip') ?? 'unknown';
const { success, headers } = checkRateLimit(ip);
if (!success) {
return NextResponse.json(
{ message: 'Too Many Requests' },
{
status: 429,
headers: {
...headers,
'Retry-After': Math.ceil((parseInt(headers['X-RateLimit-Reset']) - Date.now()) / 1000).toString()
}
}
);
}
const response = NextResponse.next();
// Add rate limit headers to the response
Object.entries(headers).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}
return NextResponse.next();
}
export const config = {
matcher: '/api/:path*',
};