Add environment config to your Phoenix JavaScript
The other day I ended up enabling latency simulation in a production Phoenix LiveView. Luckily I caught it soon after deployment and was able to roll it back.
NOTE: Remember that rolling it back isn’t simply to remove liveSocket.enableLatencySim(1000)
, but you need to add liveSocket.disableLatencySim()
to make sure it’s disabled for anyone who has already loaded the page.
This led me to figure out how to ensure I only run latency simulation in development.
To solve this, we can use esbuild’s --define
flag that allows you to define build variables.
You can update your esbuild config in config/config.exs
and add --define:ENV=\"#{config_env()}\"
to the args.
This will replace ENV
in your javascript with the current environment. You can then add a check to your javascript to run different code based on the environment. ENV !== 'prod'
will become 'dev' !== 'prod'
in your javascript for development and build optimisation should remove the code entirely from production.
Here’s an updated config from a recent project:
config :esbuild,
version: "0.17.11",
we_table: [
args:
~w(js/app.js --bundle --target=es2017 --define:ENV=\"#{config_env()}\" --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
Now you can use the ENV
"compile time" variable in your javascript.
if (ENV !== 'prod') {
// expose liveSocket on window for web console debug logs and latency simulation:
liveSocket.enableDebug()
liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
}