This uses the global window variable in window to pass values, but gives you a universal interface for accessing values in the browser and node.
In publicEnv.js :
// Env variable to push to the client. Careful on what you put here! const publicEnv = [ 'API_URL', 'FACEBOOK_APP_ID', 'GA_ID' ]; // These 2 lines make sure we pick the value in the right place on node and the browser const isBrowser = typeof window !== 'undefined'; const base = (isBrowser ? window.__ENV__ : process.env) || {}; const env = {}; for (const v of publicEnv) { env[v] = base[v]; } export default env;
In the HTML page template file, I have:
import publicEnv from 'publicEnv.js'; ... <script> window.__ENV__ = ${stringify(publicEnv)};
So, now I can get the values of env variables for both frontend and backend with:
import publicEnv from 'publicEnv.js'; ... console.log("Google Analytic code is", publicEnv.GA_ID);
Hope this helps.
source share