forked from pagescms/pagescms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
47 lines (40 loc) · 1.22 KB
/
proxy.ts
File metadata and controls
47 lines (40 loc) · 1.22 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
function isAllowedOrigin(originHeader: string, hostHeader: string): boolean {
try {
const originUrl = new URL(originHeader);
return originUrl.host.toLowerCase() === hostHeader.toLowerCase();
} catch {
return false;
}
}
export function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const isStaticAsset =
pathname.startsWith("/_next/") ||
pathname === "/favicon.ico" ||
/\.[^/]+$/.test(pathname);
if (isStaticAsset) {
return NextResponse.next();
}
if (pathname.startsWith("/api/") && pathname !== "/api/webhook/github" && request.method !== "GET") {
const originHeader = request.headers.get("Origin");
const hostHeader = request.headers.get("Host");
if (!originHeader || !hostHeader || !isAllowedOrigin(originHeader, hostHeader)) {
return new NextResponse(null, {
status: 403
});
}
}
const requestHeaders = new Headers(request.headers);
const returnTo = `${request.nextUrl.pathname}${request.nextUrl.search}`;
requestHeaders.set("x-return-to", returnTo);
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}
export const config = {
matcher: "/:path*"
}