-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
51 lines (43 loc) · 1.61 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
46
47
48
49
50
51
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { RateLimiter } from 'limiter';
// Create a Map to store rate limiters for each IP
const limiters = new Map<string, RateLimiter>();
export async function middleware(request: NextRequest) {
// Only apply to /api routes
if (request.nextUrl.pathname.startsWith('/api')) {
const ip = request.ip ?? '127.0.0.1';
// Get or create a rate limiter for this IP
let limiter = limiters.get(ip);
if (!limiter) {
limiter = new RateLimiter({
tokensPerInterval: 10,
interval: 'minute',
fireImmediately: true,
});
limiters.set(ip, limiter);
}
// Apply rate limiting
const remaining = await limiter.removeTokens(1);
if (remaining < 0) {
return new NextResponse(JSON.stringify({ error: 'Rate limit exceeded' }), {
status: 429,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*', // Adjust this for production
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
}
// Apply CORS
const response = NextResponse.next();
response.headers.set('Access-Control-Allow-Origin', '*'); // Adjust this for production
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
return response;
}
}
export const config = {
matcher: '/api/:path*',
};