DEV Community

How to fix CORS headers in a single page application

Roelof Jan Elsinga on September 27, 2019

How to fix CORS headers in a single page application Making cross-domain XHR requests can be a pain when building a web application as...
Collapse
 
lawrencejohnson profile image
Lawrence • Edited

Using * for access isn't great practice. CORS protection exists for a reason. Here's something for Apache that we use that also helps migrating between environments that you can specify upfront.

SetEnvIf Origin "https?://(staging\.|www\.)?mywebsite.com$" AccessControlAllowOrigin=$0
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Collapse
 
roelofjanelsinga profile image
Roelof Jan Elsinga

I fully agree with you, that's why I've included all the different examples to explain each concept in detail and added the disclaimer: "Below will follow a few examples that you can copy/paste, be mindful how much you want to allow the browser to do though."

Something you can use for the origin is also this:

add_header Access-Control-Allow-Origin $http_origin;

This way it adds the requesting origin to the "whitelisted" domains. But yes, as you said, it's best to restrict these and not leave them wide open.