Configuring Vercel
In addition to setting headers in next.config.mjs, ensure that Vercel is properly configured. You can use a vercel.json file to set custom headers:
// vercel.json
{
"headers": [
{
"source": "/(.*)",
"headers": [
{
"key": "Access-Control-Allow-Credentials",
"value": "true"
},
{
"key": "Access-Control-Allow-Origin",
"value": "*" // Replace with your domain
},
{
"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"
}
]
}
]
}
How to Fix CORS Errors in Next.js and Vercel?
Cross-Origin Resource Sharing (CORS) is a security feature that restricts web apps from making requests to a different domain than the one that served the web page to it. This is needed for security, although sometimes it can block legitimate requests, especially when working with APIs. In this article, we will learn fixing the CORS errors in the Next.js application deployed on Vercel.