forked from JhaSourav07/commitpulse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
64 lines (58 loc) · 1.76 KB
/
middleware.ts
File metadata and controls
64 lines (58 loc) · 1.76 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { rateLimit } from './lib/rate-limit';
/**
* Middleware to enforce rate limiting on specific API routes.
*
* Protected Routes:
* - /api/streak
* - /api/github
* - /api/track-user
* - /api/stats
* - /api/og
*
* Limit: 60 requests per minute per IP.
*/
export function middleware(request: NextRequest) {
// Use Vercel's ip property if available, fallback to headers, then localhost
const ip =
request.headers.get('x-forwarded-for')?.split(',')[0] ??
request.headers.get('x-real-ip') ??
'127.0.0.1';
// Apply rate limiting
// 60 requests per 60,000ms (1 minute)
const result = rateLimit(ip, 60, 60000);
if (!result.success) {
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: {
'Content-Type': 'application/json',
'X-RateLimit-Limit': result.limit.toString(),
'X-RateLimit-Remaining': result.remaining.toString(),
'X-RateLimit-Reset': result.reset.toString(),
},
}
);
}
// Add rate limit headers to the response for successful requests
const response = NextResponse.next();
response.headers.set('X-RateLimit-Limit', result.limit.toString());
response.headers.set('X-RateLimit-Remaining', result.remaining.toString());
response.headers.set('X-RateLimit-Reset', result.reset.toString());
return response;
}
/**
* Configure which routes should trigger this middleware.
* Using a matcher is more efficient than checking pathnames inside the middleware.
*/
export const config = {
matcher: [
'/api/streak/:path*',
'/api/github/:path*',
'/api/track-user/:path*',
'/api/stats/:path*',
'/api/og/:path*',
],
};