NEXT JS strapi CORS error

System Information
  • Strapi Version: 4.15
  • Operating System: Ubuntu
  • Database: MYSQL
  • Node Version: 18.19
  • NPM Version: 10.2
  • Yarn Version:

I have hosted my Strapi Application on AWS and I created a API and made it public when I test this API end point with postman I am getting a successful response with data being fetched from the strapi. However when I am trying to fetch the data from the NEXTJS using axios it is throwing me a CORS error.

Does this happen only in NextJS client code, or is the same problem when you do a fetch from the backend?

The issue you are having is within the NextJS application, which appears to have provided a ‘same origin’ content security policy (CSP) header to the browser. This will prevent any ‘fetch’ on a resource URL that lies outside the origin of your app. (In your case, that appears to be ‘localhost’.)

This is a pretty common issue with decoupled front ends, I have found many ways of fixing this, for example:

  • Allowing all origins, on the backend (strapi in this case), not recommended.
  • Creating a proxy for your front end app, which can be hard to mantain

But in fact I recommend NextJS rewrites, the best option for me.

// NextJS Config
beforeFiles: [
      {
        source: '/backend/:path*',
        destination: 'https://my-backend.com/:path*',
      },
],

Note that the ‘source’ is a local address, meaning if you were requesting to https://my-backend/api now you will request to /backend/api on your axios request