mirror of
https://github.com/AustinKelsay/plebdevs.git
synced 2025-06-06 18:31:00 +00:00
Add cors headers into middleware.js, remove .well-known from rate limit for now
This commit is contained in:
parent
1d54f3d123
commit
9957d1acbf
@ -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;
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user