Add cors headers into middleware.js, remove .well-known from rate limit for now

This commit is contained in:
austinkelsay 2024-11-15 14:04:30 -06:00
parent 1d54f3d123
commit 9957d1acbf
No known key found for this signature in database
GPG Key ID: 44CB4EC6D9F2FA02

View File

@ -44,28 +44,50 @@ const ratelimit = process.env.NODE_ENV === 'production'
// Define which routes you want to rate limit // Define which routes you want to rate limit
export const config = { export const config = {
matcher: '/api/:path*', matcher: [
// Exclude .well-known routes from middleware
'/((?!.well-known).*)',
]
}; };
export default async function middleware(request) { export default async function middleware(request) {
const ip = request.ip ?? '127.0.0.1'; // Add CORS headers for all responses
const { success, limit, remaining, reset } = await ratelimit.limit( const response = NextResponse.next();
`ratelimit_middleware_${ip}`
); // Add CORS headers
response.headers.set('Access-Control-Allow-Origin', '*');
if (!success) { response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
return new NextResponse('Too Many Requests', { response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
status: 429,
headers: { // Handle OPTIONS request
'Retry-After': Math.ceil((reset - Date.now()) / 1000).toString(), if (request.method === 'OPTIONS') {
}, return new NextResponse(null, {
status: 200,
headers: response.headers
}); });
} }
const response = NextResponse.next(); // Only apply rate limiting to API routes
response.headers.set('X-RateLimit-Limit', limit.toString()); if (request.nextUrl.pathname.startsWith('/api')) {
response.headers.set('X-RateLimit-Remaining', remaining.toString()); const ip = request.ip ?? '127.0.0.1';
response.headers.set('X-RateLimit-Reset', reset.toString()); const { success, limit, remaining, reset } = await ratelimit.limit(
`ratelimit_middleware_${ip}`
);
if (!success) {
return new NextResponse('Too Many Requests', {
status: 429,
headers: {
'Retry-After': Math.ceil((reset - Date.now()) / 1000).toString(),
'Access-Control-Allow-Origin': '*',
},
});
}
response.headers.set('X-RateLimit-Limit', limit.toString());
response.headers.set('X-RateLimit-Remaining', remaining.toString());
response.headers.set('X-RateLimit-Reset', reset.toString());
}
return response; return response;
} }