-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
52 lines (46 loc) · 1.72 KB
/
middleware.ts
File metadata and controls
52 lines (46 loc) · 1.72 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Clone the request headers
const requestHeaders = new Headers(request.headers)
// Create response
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
})
// 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('Referrer-Policy', 'strict-origin-when-cross-origin')
// Add CORS headers for API routes
if (request.nextUrl.pathname.startsWith('/api/')) {
// Allow requests from same origin (adjust as needed for your use case)
const origin = request.headers.get('origin')
if (origin && (
origin === process.env.NEXT_PUBLIC_APP_URL ||
origin.includes('localhost') ||
origin.includes('127.0.0.1')
)) {
response.headers.set('Access-Control-Allow-Origin', origin)
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
response.headers.set('Access-Control-Allow-Credentials', 'true')
}
}
return response
}
// Configure which routes the middleware should run on
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}