I am using Next.js version 13.4.4 and have an endpoint at http://localhost:5000/logout. In my src/app/logout/route.tsx
file, I have the following code:
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
return new NextResponse("POST: /logout");
}
Now, I am trying to call this endpoint from another application running at http://localhost:3000. However, I keep encountering the following error:
Access to XMLHttpRequest at 'http://localhost:5000/logout' from origin 'http://localhost:3000' 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.
How can I resolve this CORS error and successfully make a POST request to the http://localhost:5000/logout endpoint in Next.js 13.4.4?
const response = await fetch('http://localhost:5000/logout', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
});
3
Answers
I THINK this is what you’re asking for, not sure though. Gonna throw it in just in case though haha
This is what I have set up, I think it might work well in your case if you are trying to restrict the fetch methods:
In withMethods.ts (you can also have this in the same file)
In your API route file, in your case
src/app/logout/route.tsx
Note: The withMethods code snippet is taken from Josh Tried Coding’s youtube channel and from this video (highly recommend watching it)
cors
should be handled in middleware. if you know express, we installcors
package and register it inapp.js
. in nextjs13 you dont need to install this packagein next.js middleware file
then from docs, you should alse set the headers in response inside route handlers. this is your route handler
you can also view this github discussion for different options
Let’s understand the issue :
CORS is a protocol defining the way your server is handling the special requests.
What is special request
If the server thinks that the same user requested the API (or resource ) from multiple domain then we can call that a special request.
How server is getting such requests ?
Possible Solution to your problem :
Still having some confusions
You can visit