This is a question about Next.js 13 api routes. Next.js 13 was released in late 2022 and introduced a lot of changes.
I'm currently using Next.js 13.4.7 and trying to set up an API route to be accessible via a POST request from a browser-based app (also a Next.js app). However, I've been encountering some CORS issues.
Here's my API route, which I've implemented according to the Next.js documentation:
export async function POST(request: Request) {
return new Response("Hello, Next.js!", {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
});
}
I am using the app router. My folder structure looks like:
/app/api/cors-test/route.ts
This route is deployed and works fine when tested with Postman: https://next13-api-tester.vercel.app/api/cors-test
However, when I try to make a request from my browser-based app, I get a CORS error:
Access to fetch at 'https://next13-api-tester.vercel.app/api/test' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is the request I am making from my (other) app:
const res = await fetch("https://next13-api-tester.vercel.app/api/cors-test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "x@test.io",
project: "123456",
}),
});
I've tried a number of solutions, but nothing seems to work. I am obviously missing something here. Could someone please guide me on how to resolve this CORS issue in my Next.js app?
code can be found here: