When building Phoenix LiveView apps, you might run into a case where you need a server-side config value inside a client-side JavaScript hook. Since LiveView hooks run on the client, they can't directly access your Elixir config.
Here's a simple and idiomatic way to pass config values from your Elixir backend to your LiveView hooks.
Read the Config Value in LiveView
Use Application.get_env/2
to pull the value from your app config and assign it to the socket:
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:my_config_value, Application.get_env(:my_app, :my_config_key)}
end
Render it in the DOM
Expose the value as a data-
attribute on the element using the hook:
<div
id="my-hooked-element"
phx-hook="MyHook"
data-config-value={@my_config_value}>
</div>
Access it in the JavaScript hook
Use the dataset API to read the config value in your hook:
const MyHook = {
mounted() {
const configValue = this.el.dataset.configValue;
console.log("Config value:", configValue);
// Use it in your logic here
}
};
export default MyHook;
Be Careful With Secrets
Avoid exposing sensitive config like API keys or secrets directly in the DOM. If you must, consider:
- Using a short-lived signed token
- Fetching it via an authenticated API call
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.