-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
54 lines (45 loc) · 1.62 KB
/
middleware.ts
File metadata and controls
54 lines (45 loc) · 1.62 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
import { NextRequest, NextResponse } from 'next/server';
import { checkRateLimit } from './lib/rate-limiter';
const SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
};
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Apply security headers to all responses
for (const [key, value] of Object.entries(SECURITY_HEADERS)) {
response.headers.set(key, value);
}
if (!request.nextUrl.pathname.startsWith('/api/')) {
return response;
}
// Use session cookie as primary rate limit key (harder to spoof than IP headers).
// Fall back to common reverse-proxy IP headers. (`request.ip` was removed in
// Next 15; the platform now expects you to read it from headers explicitly.)
const sessionId = request.cookies.get('db-session')?.value;
const ip =
request.headers.get('x-real-ip') ||
request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
'0.0.0.0';
const rateLimitKey = sessionId || ip;
const { allowed, retryAfter } = checkRateLimit(rateLimitKey, request.nextUrl.pathname);
if (!allowed) {
return NextResponse.json(
{ error: 'Too many requests. Please try again later.' },
{
status: 429,
headers: {
...SECURITY_HEADERS,
'Retry-After': String(retryAfter || 60),
},
}
);
}
return response;
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};