ProGM
ProGM

Reputation: 7108

How to set CORS headers for fonts in Phoenix?

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

Upvotes: 2

Views: 2011

Answers (1)

Dogbert
Dogbert

Reputation: 222198

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.

Upvotes: 7

Related Questions