forked from ryzwan29/explorer-winscan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
48 lines (39 loc) · 1.64 KB
/
middleware.ts
File metadata and controls
48 lines (39 loc) · 1.64 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Clean URL parameters - remove leading/trailing spaces from path segments
const pathname = request.nextUrl.pathname;
const cleanedPathname = pathname
.split('/')
.map(segment => decodeURIComponent(segment).trim())
.map(segment => encodeURIComponent(segment))
.join('/');
// Redirect if pathname has changed after cleaning
if (cleanedPathname !== pathname && !pathname.startsWith('/api/')) {
const url = request.nextUrl.clone();
url.pathname = cleanedPathname;
return NextResponse.redirect(url);
}
if (request.nextUrl.pathname.startsWith('/api/')) {
const response = NextResponse.next();
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', 'Content-Type, Authorization');
response.headers.set('Access-Control-Max-Age', '86400'); // 24 hours
// Force no-cache for API routes
response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
response.headers.set('Pragma', 'no-cache');
response.headers.set('Expires', '0');
if (request.method === 'OPTIONS') {
return new NextResponse(null, {
status: 204,
headers: response.headers
});
}
return response;
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)', '/api/:path*'],
};