-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
80 lines (69 loc) · 2.49 KB
/
middleware.ts
File metadata and controls
80 lines (69 loc) · 2.49 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { formSubmissionRateLimit, apiRateLimit } from '@/lib/rate-limit';
export async function middleware(request: NextRequest) {
// Environment URLs are now set statically in wrangler.jsonc for each environment
// No need for dynamic runtime environment detection with separate workers
const host = request.headers.get('host') || '';
// Debug middleware execution
console.log(
'Middleware running for path:',
request.nextUrl.pathname,
'Host:',
host
);
// Only apply to /api routes
if (request.nextUrl.pathname.startsWith('/api/')) {
console.log(
'Middleware running for API request:',
request.nextUrl.pathname
);
// Handle OPTIONS requests (preflight)
if (request.method === 'OPTIONS') {
return new NextResponse(null, {
status: 204,
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers':
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
'Access-Control-Max-Age': '86400',
},
});
}
// Apply rate limiting based on the endpoint
let rateLimitResponse = null;
if (
request.nextUrl.pathname.includes('/forms/') &&
request.method === 'POST'
) {
// Apply stricter rate limiting for form submissions
rateLimitResponse = await formSubmissionRateLimit(request);
} else {
// Apply general API rate limiting
rateLimitResponse = await apiRateLimit(request);
}
// If rate limit exceeded, return the rate limit response
if (rateLimitResponse) {
return rateLimitResponse;
}
// Get response with CORS headers
const response = NextResponse.next();
// Add CORS headers to all API responses
response.headers.set('Access-Control-Allow-Credentials', 'true');
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set(
'Access-Control-Allow-Methods',
'GET,POST,PUT,DELETE,OPTIONS'
);
response.headers.set(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
);
return response;
}
}
export const config = {
matcher: '/api/:path*',
};