-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
50 lines (40 loc) · 1.42 KB
/
middleware.js
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
import { NextResponse } from 'next/server';
const allowedOrigins = [
'https://sayaptawon.github.io',
'https://sayaptawon.vercel.app',
];
const corsOptions = {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers':
'Content-Type, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials': 'true',
};
export function middleware (request) {
const { pathname } = request.nextUrl;
const origin = request.headers.get('origin') ?? '';
const isAllowedOrigin = allowedOrigins.includes(origin);
const isPreflight = request.method === 'OPTIONS';
if (isPreflight) {
const preflightHeaders = {
...(isAllowedOrigin && { 'Access-Control-Allow-Origin': origin }),
...corsOptions,
};
return NextResponse.json({}, { headers: preflightHeaders });
}
if (!pathname.endsWith('/') && !pathname.includes('.')) {
const newUrl = `${request.nextUrl.origin}${pathname}/`;
return NextResponse.redirect(newUrl);
}
const response = NextResponse.next();
if (isAllowedOrigin) {
response.headers.set('Access-Control-Allow-Origin', origin);
response.headers.set('Access-Control-Allow-Credentials', 'true');
}
Object.entries(corsOptions).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}
export const config = {
matcher: ['/api/:path*', '/((?!api|_next/static|_next/image|favicon.ico).*)'],
};