-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
63 lines (54 loc) · 2.3 KB
/
Copy pathmiddleware.ts
File metadata and controls
63 lines (54 loc) · 2.3 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { checkRateLimitMemory, createRateLimitResponse } from '@/lib/rate-limit'
export async function middleware(request: NextRequest) {
const response = NextResponse.next()
// Security headers
response.headers.set('X-Frame-Options', 'DENY')
response.headers.set('X-Content-Type-Options', 'nosniff')
response.headers.set('X-XSS-Protection', '1; mode=block')
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin')
response.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()')
// Content Security Policy (adjust as needed for your app)
response.headers.set(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none';"
)
// Rate limiting for API routes using in-memory store (Edge Runtime compatible)
if (request.nextUrl.pathname.startsWith('/api/')) {
try {
const { allowed, remaining, resetTime } = checkRateLimitMemory(
request,
request.nextUrl.pathname
)
if (!allowed) {
return createRateLimitResponse(resetTime)
}
// Add rate limit headers to successful responses
response.headers.set('X-RateLimit-Remaining', remaining.toString())
response.headers.set('X-RateLimit-Reset', Math.ceil(resetTime / 1000).toString())
} catch (error) {
console.error('Rate limiting middleware error:', error)
// Continue with request if rate limiting fails
}
}
// Additional protection for admin routes
if (request.nextUrl.pathname.startsWith('/admin')) {
// Add additional security headers for admin panel
response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
response.headers.set('Pragma', 'no-cache')
response.headers.set('Expires', '0')
}
return response
}
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)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
}