Skip to content

Commit 7fe360c

Browse files
sayaptawonidugeni
andcommitted
fix: handle CORS and URL slashes
- Added middleware to manage CORS headers for allowed origins - Implemented automatic redirect to ensure URLs have trailing slashes Co-Authored-By: Jagad Brahma Wiraatmaja <officialelsa21@gmail.com>
1 parent 6089e3e commit 7fe360c

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

middleware.js

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
import { NextResponse } from 'next/server';
22

3-
const allowedOrigins = ['https://sayaptawon.github.io', 'https://sayaptawon.vercel.app'];
3+
const allowedOrigins = [
4+
'https://sayaptawon.github.io',
5+
'https://sayaptawon.vercel.app',
6+
];
47

58
const corsOptions = {
69
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
7-
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
10+
'Access-Control-Allow-Headers':
11+
'Content-Type, Authorization, X-Requested-With',
812
'Access-Control-Allow-Credentials': 'true',
913
};
1014

11-
export function middleware(request) {
15+
export function middleware (request) {
16+
const { pathname } = request.nextUrl;
1217
const origin = request.headers.get('origin') ?? '';
1318
const isAllowedOrigin = allowedOrigins.includes(origin);
1419
const isPreflight = request.method === 'OPTIONS';
@@ -21,6 +26,11 @@ export function middleware(request) {
2126
return NextResponse.json({}, { headers: preflightHeaders });
2227
}
2328

29+
if (!pathname.endsWith('/') && !pathname.includes('.')) {
30+
const newUrl = `${request.nextUrl.origin}${pathname}/`;
31+
return NextResponse.redirect(newUrl);
32+
}
33+
2434
const response = NextResponse.next();
2535

2636
if (isAllowedOrigin) {
@@ -36,8 +46,5 @@ export function middleware(request) {
3646
}
3747

3848
export const config = {
39-
matcher: [
40-
'/api/:path*',
41-
'/((?!api|_next/static|_next/image|favicon.ico).*)',
42-
],
49+
matcher: ['/api/:path*', '/((?!api|_next/static|_next/image|favicon.ico).*)'],
4350
};

0 commit comments

Comments
 (0)