CORS Errors and ways to Fix via NextJS/Vercel

What is CORS?

Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others. 

From Mozilla https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors

Basically what it means is that, if you are on site aorborc.com and trying to request information from doreorf.com via client side javascript, the browser will through this error.

Sample Errors


The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.


It does not have HTTP ok status.


How to fix it

If you are a nextjs/vercel user like us, when you respond from your server, just add the below code inside your API function

export default async function handler(req, res) {
  res.setHeader("Access-Control-Allow-Credentials", true);
  res.setHeader(
    "Access-Control-Allow-Origin",
    req.headers.origin ? req.headers.origin : "*"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET,OPTIONS,PATCH,DELETE,POST,PUT"
  );
  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"
  );
  //For CORS
  if (req.method === "OPTIONS") {
    res.status(200).end();
    return;
  }
//Your rest of the code below
res.status(200).json({result:"Ok"});
}

The above code should avoid CORS error for your custom next js server.

Leave a Reply

Your email address will not be published. Required fields are marked *