Skip to content

Commit c502530

Browse files
authored
Add CORS headers to API routes (#152)
* Add CORS headers to API routes Allow cross-origin requests to /api/* endpoints by adding a Next.js proxy (the v16 replacement for middleware) that sets Access-Control-Allow-Origin: * on all API responses and handles OPTIONS preflight requests. * Fix import ordering for biome lint
1 parent 820c88b commit c502530

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

src/proxy.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import type { NextRequest } from "next/server";
2+
import { NextResponse } from "next/server";
3+
4+
export function proxy(request: NextRequest) {
5+
if (request.method === "OPTIONS") {
6+
return new NextResponse(null, {
7+
status: 204,
8+
headers: {
9+
"Access-Control-Allow-Origin": "*",
10+
"Access-Control-Allow-Methods": "GET, OPTIONS",
11+
"Access-Control-Allow-Headers": "Content-Type",
12+
},
13+
});
14+
}
15+
16+
const response = NextResponse.next();
17+
response.headers.set("Access-Control-Allow-Origin", "*");
18+
response.headers.set("Access-Control-Allow-Methods", "GET, OPTIONS");
19+
response.headers.set("Access-Control-Allow-Headers", "Content-Type");
20+
return response;
21+
}
22+
23+
export const config = {
24+
matcher: "/api/:path*",
25+
};

0 commit comments

Comments
 (0)