mschae / cors_plug

An Elixir Plug to add CORS.

Home Page:https://hex.pm/packages/cors_plug

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Configuration not working with Elixir 1.9 releases

jfcalvo opened this issue · comments

I'm using Elixir 1.9 and configuring the release using the recommended config/releases.exs file with the following line:

config :cors_plug, origin: [System.fetch_env!("CORS_ORIGIN")]

Looks like the previous line is not working as expected and the built release is not allowing requests from the origin set on the CORS_ORIGIN env var.

I'm doing something wrong? The other configs are working fine so I think this is an specific problem with cors_plug.

If I define the following line on prod.exs the requests works as expected (but of course I lose the possibility of configure the origin executing the release):

config :cors_plug, origin: ["http://192.168.1.128:8080"]

@jfcalvo As far as I know that happens because the place where the config is fetched, the init/1 callback of the plug runs at compile-time. So when the release starts and update the config, the previous value is already inlined by the compiler.

What I usually do is to pass a function that returns the allowed origins, as described in the docs. And in there, I make sure to fetch the config at runtime.

# endpoint.ex
plug CORSPlug, origin: &MyCors.my_fun/0

# my_cors.ex
defmodule MyCors do
  def my_fun do
    Application.fetch_env!(:my_app, :my_allowed_origins)
  end
end

# config/releases.exs
config :my_app, my_allowed_origins: System.fetch_env!("MY_CORS_ORIGIN")

with elixir 1.9 releases you put the dynamic stuff in config/releases.exs like this:

import Config
config :cors_plug, origin: [System.fetch_env!("CORS_ORIGIN")]

https://hexdocs.pm/mix/Mix.Tasks.Release.html#module-runtime-configuration

if you imported Mix.Config instead of Config it would reproduce the behavior you're seeing, I'm pretty sure.

I'm considering this closed for now, please let me know if there is anything I can do on my end and I'll reopen!