简体   繁体   中英

CORS in Nextjs Application on Vercel

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

You can add a vercel.json file to your project root with the following configuration.

{
  "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" }
      ]
    }
  ]
}

You can find more information about it from How can I enable CORS on Vercel? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM