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.
//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');
});
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.