Flexible CORS headers with Heroku and Capacitor

Flexible CORS headers with Heroku and Capacitor

CORS headers are an important security feature which you should take advantage of. There are some use cases where you have to supply specific urls for it. For example when you're building an hybrid app and use cookies and credentials in your request, as there you can't use * as Access-Control-Allow-Origin.

Simply suppling a specific url is simple, but not enough if you don't want to have specific .htaccess for each environment you're running it in.
A better way is to have a more flexible Access-Control-Allow-Origin variant in your .htaccess.

For our example we want to enable the following urls:

  • https://our-app.com (Production url for web)
  • capacitor://our-app.com (Production url for Capacitor)
  • http://our-app.localhost (Local dev url for web)
  • capacitor://our-app.localhost (Local dev url for Capacitor)
  • https://our-app-pr-20.herokuapp.com (Heroku review app for web)
  • capacitor://our-app-pr-20.herokuapp.com (Heroku review app for Capacitor)

The our-app-pr- is our custom prefix we configure on Heroku for the review apps. This way we can make sure, that nobody else is able to use it.

To be able to configure all this urls, we need to make use of SetEnvIf and a regex. The result will be the following:

SetEnvIf Origin "(http|https|capacitor)://(our-app.(com|localhost)|our-app-pr-.*.herokuapp.com)"$ AccessControlAllowOrigin=$0
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header merge Access-Control-Allow-Credentials "true"

And that's it. With this setup we can have the same .htaccess in all environments and are still able have working CORS headers.