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

Basically what it means is that, if you are on site and trying to request information from 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);
    req.headers.origin ? req.headers.origin : "*"
    "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") {
//Your rest of the code below

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 *