I'm encountering CORS issues while deploying my Next.js 13 application on Vercel, specifically when interacting with a MongoDB-based API. The API comprises basic CRUD operations, and my current fetch configuration is as follows:
// individual PUT/DELETE/GET
const res = await fetch(`http://localhost:3000/api/topics/${id}`, {
cache: 'no-store',
});
// generic GET/POST
const res = await fetch(`http://localhost:3000/api/topics/`, {
cache: 'no-store',
});
I suspect the CORS issue might be related to the API endpoint, and I wonder if I need to modify it when deploying to Vercel. Could someone clarify if this endpoint is correct or if adjustments are required?
Additionally, I've attempted to resolve the CORS issue by configuring the Next.js headers in my next.config.js file as follows:
/** @type {import('next').NextConfig} */
const nextConfig = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: 'http://localhost:3000/api/topics' },
{ key: 'Access-Control-Allow-Methods', value: 'GET, DELETE, PATCH, 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' },
],
},
];
},
};
module.exports = nextConfig;
Despite these configurations, the CORS issue persists. Could anyone provide guidance on resolving this CORS problem?
Folder Structure:
/app/api/topics/route.ts - Generic routes /app/api/topics/[id]/route.ts - Individual routes
Additionally, considering the deployment on Vercel, is it correct to point to http://localhost:3000 in my fetch configuration, or should this be modified for the deployed environment?
http://localhost:3000/api/topicsis not a valid Web origin.