Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js
For the fetch request on the front end, here is an example:
fetch(`https://backendname.herokuapp.com/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({"category":"_main"})
}).then(...);
In the backend file pages/api/data.js
:
export default function handler(req, res) {
req.body=JSON.parse(req.body);
res.setHeader("Access-Control-Allow-Origin", "https://frontendname.netlify.app/");
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
)
if(req.method!='POST')
return res.end();
res.json({...})
}
I have also made changes to my next.config.js:
module.exports = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "https://frontendname.netlify.app/" },
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
},
reactStrictMode: true,
}
However, despite these configurations, I am encountering the following error:
Access to fetch at 'https://backendname.herokuapp.com/data' from origin 'https://frontendname.netlify.app' 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.
I am striving to resolve this without resorting to third-party packages or solutions mentioned in the like of this question.