For the “Direct to Frontity” installation Frontity uses an external domain. The REST API doesn’t have CORS headers. We can create a PHP plugin for that.
User Stories
As a Frontity user
I want to add easily CORS headers to the REST API
so that I can use a different domain
I’m not sure this is necessary. It seems that WP does set headers for CORS (I tried one clean installation with Nginx in production and it worked just fine).
Also, in the rest_pre_serve_request hook there is already a function registered called rest_send_cors_headers that sets the headers:
You might not see them when calling the REST API directly from the browser or from an app like Postman because the Origin header is not populated therefore the CORS headers are not set. But if you try setting the Origin header in Postman you’ll see that the CORS headers will be set on the response.
I’ve just discovered that this is a really bad approach, because if your cache of the REST API response includes headers and doesn’t overwrite them with a general CORS header ("*") then it will return the previous URL. This means that, if you are using that REST API for local development, it can cache Access-Control-Allow-Origin: localhost:3000, and your production site will stop working.
The thing is that, the code that WordPress is using right now is as “safe” as using "*" because it will copy the domain you pass in the Origin header. So, I guess it’s better to set it directly to "*" and avoid caching issues.
Strangely though my other rest calls aren’t having the same issue. And my site seems to operate just fine (minus an issue where if I open the site on a permalink, the homepage spins out if I navigate there while all other pages work fine and the homepage works fine if I start from the homepage.
**Edit. This seems to be fixed now. … I think I needed to clear by browser cache. But I’m not 100% positive. Cloudways is doing some odd things over here caching wise.