Home > OS >  How do API work with CORS policies to serve multiple apps
How do API work with CORS policies to serve multiple apps

Time:02-12

I am creating an API that would serve data to my frontend app. The API is on api.myapp.com and the app on www.myapp.com (same domain, just another subdomain). They communicate with AJAX requests and CORS is all set up, working fine.

But I have another app on another domain (www.myotherapp.com) which partialy uses the same data as myapp, so I was thinking of reusing the API so myotherapp could requests data from it too.

I think it is one use case of API, to be reusable, right?

But then, there is something that I may have missed, because as my API has CORS enabled with "Access-Control-Allow-Origin: www.myapp.com", it won't allow other apps to use its endpoints, right? Their AJAX requests would fail with CORS policies.

So how are public API built and configured? How should I set my API so it can serve several apps (ideally, only the ones I allow)?

Thanks for the explanations :)

CodePudding user response:

There is an Origin header in the request and your API should check if this header is one of the allowed. If it is, then return it as an Access-Control-Allow-Origin header.

If the API is public, it can returns * as Access-Control-Allow-Origin header.

  • Related