I am having a strange situation with a Next.js API. Here it is.
I have a website named Javascript Ecosystem. I can make requests in both localhost:3000 and in production with no issues.
If I use Postman to test the requests, it work as is supposed to.
Here is the problem.
I have a personal website named reynaldo.website where I am trying to use the subscriptions API from JavaScript Ecosystem to submit new subscribers in my personal website.
I am getting the CORS cross origin error. Which is strange because I can make requests in localhost in the Javascript Ecosystem and Postman, but not in the personal website.
I added custom headers to the Next.js app that contains the module.
module.exports = {
async headers() {
return [
{
// matching all API routes
source: "/api/(.*)",
headers: [
{ key: "Access-Control-Allow-Origin", value: "*" },
{
key: "Access-Control-Allow-Methods",
value: "GET,DELETE,POST,PUT"
}
]
}
];
}
};
However I am still unable to make requests from another app that is not the one that contains the API. Any idea on why is this happening?
Solved: I realized after reading the NextJs documentation that I need to make the call from the NextJs server and pass it to the client, otherwise the CORS issue will persist. That's why I could test the api from the Postman app but didn't work from another frontend app. So pretty much after you allow the cross origin in the NextJs app that holds the api, you will have to make the call from the server side api directory in NextJs that does not hold the API and consecuently pass it to the frontend by calling that route. Hopefully, that makes sense if you are facing that issue.