Configuring CORS headers Using next.config.mjs
Next.js allows you to configure CORS headers directly in the next.config.js file. Set custom headers as follows.
// next.config.mjs
export default {
async headers() {
return [
{
// Apply headers to all routes
source: '/(.*)',
headers: [
{
key: 'Access-Control-Allow-Credentials',
value: 'true',
},
{
key: 'Access-Control-Allow-Origin',
// Replace with your domain
value: '*',
},
{
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.