I've built an isomorphic React app based loosely on the starter kit in this repo. It uses webpack to build the production code.
Thing is, I need to expose the value of a few environment variables on the server to the client code in the browser without rebuilding the production code. I want to be able to change the value of the env vars, and have it the effect the client on next page refresh, without having to rebuild anything. And I don't want to complicate testing in order to do it.
I've found a few solutions, none of which are great:
Problems with these approaches:
I've done both 2 and 3 in the past and never was really intellectually satisfied by those solutions.
Any suggestions? Seems like this should be a common/solved problem. Maybe I'm just overthinking it and 3 is the way to go.
So the solution that I came up with is fairly simple. I just write a one-liner of javascript to save the value to local storage inside a script tag. Then read that local storage from my flux store when the app starts.
This is the relevant tag added to the index.html:
<script type="text/javascript"><%= config %></script>
This is the string that I splice into index.html using templating, before serving it:
let configJs = 'localStorage.setItem(\'ADMIN_API\', JSON.stringify(\'' + process.env.ADMIN_API + '/v3/' + '\'));';
const html = template({config: configJs});
res.status(200).send(html);
Then I read it with this, once the app starts:
import ls from 'local-storage';
....
let api = ls.get('ADMIN_API');