CORS in Nextjs Application on Vercel

Viewed 8129

I am currently working wiht my first bigger NextJS application and I ran into the classic CORS problem.

I have a backend, which is hosted on a different server/url, I get my json data from this backend. My frontend written in NextJS is deployed on Vercel.

I do know, that I have to enable CORS both on the backend side, as well as on the frontend side, in my localhost dev, everything is working fine (even fetching data from backend)

I already followed this guide: https://vercel.com/knowledge/how-to-enable-cors, to enable CORS in my NextJS Application. I modified the nextjs config:

module.exports = {
  async headers() {
    return [
      {
        source: "/.*",
        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" },
        ]
      }
    ]
  }
};

However, when deploying the app on vercel, I receive the following error:

Access to fetch at 'https://<my-censored-backend-url>' from origin 'https://<my-frontend-url>.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

In my backend (written in rails), I already configured my frontend on vercel to be allowed for CORS. Is there anything I am missing?

Do you guys have any experience in CORS and fetching data for NextJS from a different server? I am using getStaticProps, getServerSideProps AND SWR for fetching.

Any help would be appreciated

0 Answers
Related