2

I have a Phoenix app, that should serve its static assets (fonts, mainly) to both www.domain.com and subdomain.domain.com.

The app is hosted on heroku.

How can I set up CORS headers?

I found this library, but it doesn't seems to work on static assets (I think).

I tried to configure it like this:

defmodule MyApp.CORS do
  use Corsica.Router

  resource "/fonts/*", origins: ["http://subdomain.domain.com"]
end

but the resulting headers are:

cache-control:public
content-length:839
content-type:image/svg+xml
date:Sun, 19 Jun 2016 09:40:01 GMT
etag:3AAE04D
server:Cowboy
ProGM
  • 6,383
  • 4
  • 28
  • 49

1 Answers1

7

You can use the optional :headers option to Plug.Static and set the Access-Control-Allow-Origin header to *.

In lib/my_app/endpoint.ex, add the following argument at the end of the plug Plug.Static call:

headers: %{"Access-Control-Allow-Origin" => "*"}

Your code should look something like:

plug Plug.Static,
  at: "/", from: :my_app, gzip: false,
  only: ~w(css fonts images js favicon.ico robots.txt),
  headers: %{"Access-Control-Allow-Origin" => "*"}

Note that this will not work if you want to allow more than 1 domain to work (a single domain or * would work), as I believe you have to dynamically calculate the value based on the request's Origin header for that, while Plug.Static only allows adding a static list of headers.

Community
  • 1
  • 1
Dogbert
  • 188,810
  • 39
  • 339
  • 353
  • Is it possible to set it with an env var? Like in config/prod with something like System.get_env("CORS_ORIGIN") or "${CORS_ORIGIN}" (for released versions) or because of the compilation time of the lib folder we can't? Thanks for your solution by the way! – coding addicted Jul 25 '17 at 19:34