Before you mark this as duplicate, you should know that have tried using the three methods from adding cors middleware, using vercel.json, and next.config.js to set the header, yet I keep getting the same error. I am using the next.js API for the backend and with the front end, I use custom Axios with the base URL similar to the vercel default link. This works locally but when I deploy it to vercel , I get the cors error above
vercel.json
{
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Credentials", "value": "true" },
{ "key": "Access-Control-Allow-Origin", "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" }
]
}
]
}
next.config.js
const { withPlaiceholder } = require("@plaiceholder/next");
module.exports = withPlaiceholder({
images: {
domains: ["images.unsplash.com", 'i.ibb.co', 'wpbingosite.com', 'www.chicintuition.com'],
},
async headers() {
return [
{
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", 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" },
]
}
]
}
});
export default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
const cors = initMiddleware(
Cors({
methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'],
})
)
export default cors
and then in for the front end
let url
if (process.env.NODE_ENV === "development") {
url = config.urlDev
} else {
url = config.urlProd
}
interface CustomRequestProps extends AxiosRequestConfig {
headers: {
authorization: string
}
}
export const apiCall = Axios.create({
baseURL: url,
});
apiCall.interceptors.request.use(authRequestInterceptor)
async function authRequestInterceptor(config: AxiosRequestConfig) {
const token = await auth.currentUser?.getIdToken(true)
let customConfig: CustomRequestProps = {
...config,
headers: {
authorization: ''
}
}
if (token) {
customConfig.headers.authorization = `${token}`;
}
return customConfig;
}