-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
66 lines (57 loc) · 2.18 KB
/
middleware.ts
File metadata and controls
66 lines (57 loc) · 2.18 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
import { corsHeaders } from '@/config/cors.config';
import { authMiddleware } from '@/middleware/auth.middleware';
import { validateRequest } from '@/middleware/validation.middleware';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
/**
* Main middleware function that runs on matched routes
* Composes multiple middleware functions together
*/
export async function middleware(request: NextRequest): Promise<NextResponse> {
try {
// Check if it's a server action POST request to the root
const isServerActionPost = request.method === 'POST' && request.nextUrl.pathname === '/';
// Temporarily bypass validation for server action POST requests
if (!isServerActionPost) {
const validationResponse = await validateRequest(request);
if (validationResponse instanceof NextResponse) {
return validationResponse;
}
}
// Run authentication middleware for Cloudflare API routes
const authResponse = await authMiddleware(request);
if (authResponse instanceof NextResponse) {
return authResponse;
}
// If all middleware passes, continue with the request
const response = NextResponse.next();
// Apply CORS and security headers
Object.entries(corsHeaders).forEach(([key, value]) => {
if (typeof value === 'string') {
response.headers.set(key, value);
}
});
// Add security headers
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-XSS-Protection', '1; mode=block');
response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
return response;
} catch (error) {
console.error('Middleware error:', error);
const headers = {
'Content-Type': 'application/json',
...corsHeaders,
} as const;
return new NextResponse(JSON.stringify({ success: false, message: 'Internal server error' }), {
status: 500,
headers,
});
}
}
/**
* Configure which paths this middleware runs on
*/
export const config = {
matcher: ['/api/:path*', '/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)'],
};