How to set configuration of a dependency (an Elixir application) from a Phoenix project?

I’ve an Elixir application that reads from a website’s API. The API is private and needs a secret key. The application reads the API key from a configuration variable. In the config.exs I have something like this:

config :my_app, api_key: System.get_env("API_KEY")

to set the API key. Then I have a private function to access this configuration variable throughout the code:

defp api_key, do: Application.get_env(:my_app, :api_key)

That works fine.

Now I want to use this application in a Phoenix project. It will have more than one user and each user needs its own API key. The API keys will be stored in a database.
How can I pass the API key read from database to that Elixir application?

Change the dependency to retrieve the API key as a function argument.

Do you mean that I need to to pass the API key to all functions as an argument? In my current implementation there’s a function that all other functions call it. I get the API key in this function.
Is there a way that doesn’t need to directly pass the configuration to all functions?

You saif the API key will change in each users context, so changing the applications env for each user after fetching the key from the database, you will end up with race conditions earlyer or later.

Therefore you need a thread safe way to communicate the key to where its needed, the easiest way is to pass it as an argument in the function call.

1 Like