-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
48 lines (43 loc) · 1.24 KB
/
middleware.ts
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 { NextRequest, NextResponse } from "next/server";
import { corsOptions } from "./config";
export async function middleware(request: NextRequest) {
if (process.env.NODE_ENV === "test") {
// Response
const response = NextResponse.next();
// Allowed origins check
const origin = request.headers.get("origin") ?? "";
if (
corsOptions.allowedOrigins.includes("*") ||
corsOptions.allowedOrigins.includes(origin)
) {
response.headers.set("Access-Control-Allow-Origin", origin);
}
// Set default CORS headers
response.headers.set(
"Access-Control-Allow-Credentials",
corsOptions.credentials.toString()
);
response.headers.set(
"Access-Control-Allow-Methods",
corsOptions.allowedMethods.join(",")
);
response.headers.set(
"Access-Control-Allow-Headers",
corsOptions.allowedHeaders.join(",")
);
response.headers.set(
"Access-Control-Expose-Headers",
corsOptions.exposedHeaders.join(",")
);
response.headers.set(
"Access-Control-Max-Age",
corsOptions.maxAge?.toString() ?? ""
);
// Return
return response;
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: "/api/:path*",
};