Strapi V4, configure cors origin to be enabled only for my frontend domain

Hi, I’m new to Strapi, First I want to thank all contributors and developers for this awesome CMS.
My question is, I’m using strapi V4, and I want to configure cors to not be a wildcard ( Cross-Origin Resource Sharing: "*" ) I want to configure it to be like this : ( Cross-Origin Resource Sharing : ["http://localhost:3000] ), I mean I want my API to be accessible only by my frontend origin, and didn’t know how to implement it, I know I need to change something in middlewares but if there is an example it would be great.
Thank you in advance

4 Likes

i am also facing such issue. Did u resolve your issue?

I am facing the same issue. Setting the cors in middlewares.js does not block direct API calls. My configuration is

{
    name: 'strapi::cors',
    config: {
      enabled: true,
      origin: ['http://localhostsdfsg:1337'],
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
      headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],
    }
  },

This does block the admin console and spits the error “http://localhost:1337 is not a valid origin”. However, direct API calls still work from any origin.

Same issue here, do you have documentation to achieve this ?

Note that in my case, strapi::cors was initially defined before strapi::poweredBy but it only works in exactly this order (cors must be after poweredBy not before).

module.exports = [
  'strapi::errors',
  'strapi::security',
  'strapi::poweredBy',
  {
    name: 'strapi::cors',
    config: {
      enabled: true,
      headers: '*',
      origin: ['http://localhost:1337', 'http://example2']
    }
  },
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];