1

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?

2

1 Answer 1

1

So i solve this by adding a env variable to store the correct url

NEXT_PUBLIC_BASE_API_URL=http://localhost:3000

and add it to every fetch like below line

  const rest = await fetch(`${BASE_API_URL}/api/topics`, {
      cache: 'no-store',
    });

but since I will deploy this to vercel y didn't configure it over there till the app was deployed so when the deployment finished I have now the correct url then I set the env variable in Vercel console and the GETS started to work.

only in production the URL will be the next one (example one)

NEXT_PUBLIC_BASE_API_URL=crud-next-git-main.vercel.app

so thats one thing removing the localhost if is not production.

but still i was getting cors issue so i update next config to this:

const nextConfig = {
  async headers() {
    return [
      {
        // matching all API routes
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          { key: 'Access-Control-Allow-Origin', value: '*' },
          {
            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;

now the api works fine without any Cors issues. I reference this URL article that helped me to understand what was going on. https://blog.logrocket.com/using-cors-next-js-handle-cross-origin-requests/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.