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.

How do CORS work?

CORS is enforced by the browser through HTTP headers that tell which origins are allowed to access the resource server. When this cross-origin request is made, the browser sends an ‘OPTION’ preflight request to the server to check if the request is safe or not. If the server response does not include the appropriate CORS headers, the browser blocks the request.

Common Reasons for CORS Errors

  • API Misconfiguration: This happens when the API server is not configured to accept requests from requesting domain.
  • Incorrect Client-Side Implementation: This is when the client-side application, like a web browser, doesn’t use the right methods or headers when making a request. It’s akin to speaking a foreign language to the server; if the server doesn’t understand it, it won’t respond favorably.

These are the following methods for Fixing CORS Errors in Next.js and Vercel:

Table of Content

  • CORS Configuration in API
  • Configuring CORS headers Using next.config.mjs
  • Using Middleware in Next.js API Routes
  • Configuring Vercel
  • Using External Libraries
  • Debugging CORS Issues

CORS Configuration in API

If we have control over the API, we must configure it to allow requests from our domain that hosts the frontend.

JavaScript
//index.js 
//configuring cors in express.js server.

const express = require('express');
const cors = require('cors');
const app = express();

const corsOptions = {
  // Replace with your domain
  origin: 'https://yourdomain.com',
  methods: 'GET, HEAD, PUT, PATCH, POST, DELETE',

  // Enable this if you need to
  // send cookies or HTTP authentication
  credentials: true,
  optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

// Your routes
app.listen(3000, () => {
  console.log('Server running on port 3000');
});

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.

JavaScript
// 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',
                    },
                ],
            },
        ];
    },
};

Using Middleware in Next.js API Routes

Next.js API routes, we can use middleware to handle CORS.

JavaScript
// pages/api/hello.js
import Cors from 'cors'

// Initialize the cors middleware
const cors = Cors({
    methods: ['GET', 'HEAD', 'POST'],
    // Replace with your domain
    origin: 'https://yourdomain.com',
    credentials: true
})

// Helper method to wait for middleware to execute before continuing
function runMiddleware(req, res, fn) {
    return new Promise((resolve, reject) => {
        fn(req, res, (result) => {
            if (result instanceof Error) {
                return reject(result)
            }
            return resolve(result)
        })
    })
}

export default async function handler(req, res) {
    // Run the middleware
    await runMiddleware(req, res, cors)

    // Rest of your API logic here
    res.json({ message: 'Hello Everyone!' })
}

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:

JavaScript
// 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"
          }
    ]
}
    ]
  }

Using External Libraries

You can also use third-party libraries like nextjs-cors to simplify the process:

Install the following:

npm i nextjs-cors
JavaScript
// pages/api/hello.js
import NextCors from 'nextjs-cors';

export default async function handler(req, res) {
    // Run the cors middleware
    await NextCors(req, res, {

        // Options
        methods: ['GET', 'HEAD', 'PUT', 'PATCH',
            'POST', 'DELETE'],
        // Replace with your domain
        origin: 'https://yourdomain.com',
        optionsSuccessStatus: 200,
    });

    // Your API logic here
    res.json({ message: 'Hello Everyone!' });
}

Debugging CORS Issues

If CORS errors persist, try following:

  • Checking the Browser Console: Dive into the browser console for a closer look at the CORS error messages.
  • Verifying API Headers: We can use tools like postman or curl to check the headers are set correctly by sending http requests through them.
  • Reviewing Server Logs: Server log is history book, that records each event. If preflight or actual request is blocked then log tells the issue and provide insights that are needed to solve the persisted problem.


Contact Us