forked from Vizzuality/mangrove-atlas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
49 lines (39 loc) · 1.46 KB
/
Copy pathproxy.ts
File metadata and controls
49 lines (39 loc) · 1.46 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
import { NextRequest, NextResponse } from 'next/server';
const HIDDEN_IN_PROD = ['/auth'];
const allowedOrigins = new Set([
'https://mrtt.globalmangrovewatch.org',
'https://mrtt-staging.globalmangrovewatch.org',
'http://localhost:3000',
]);
const corsBaseHeaders: Record<string, string> = {
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-CSRF-Token, X-Requested-With',
'Access-Control-Allow-Credentials': 'true',
Vary: 'Origin',
};
function withCors(request: NextRequest, response: NextResponse) {
const origin = request.headers.get('origin');
if (origin && allowedOrigins.has(origin.replace(/\/$/, ''))) {
response.headers.set('Access-Control-Allow-Origin', origin);
for (const [k, v] of Object.entries(corsBaseHeaders)) response.headers.set(k, v);
}
return response;
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
if (process.env.NEXT_PUBLIC_ENVIRONMENT === 'production') {
if (HIDDEN_IN_PROD.some((p) => pathname === p || pathname.startsWith(`${p}/`))) {
return NextResponse.rewrite(new URL('/404', request.url));
}
}
if (pathname.startsWith('/api/auth')) {
return NextResponse.next();
}
if (request.method === 'OPTIONS') {
return withCors(request, new NextResponse(null, { status: 204 }));
}
return withCors(request, NextResponse.next());
}
export const config = {
matcher: ['/api/:path*'],
};