When exposing certain env vars to the client, most examples follow the advice here:
https://remix.run/docs/en/main/guides/envvars#browser-environment-variables
This works, but it's inefficient (in our case) to return the client env from the loader as it will be sent in every revalidation, and the data will never change (we can't return false in our root shouldRevalidate as we return other non-static data).
Is there any issue with simply setting the same global var on the server and client so everything works as expected on both server and client renders?
This example assumes that you have a custom server (ex. using the https://github.com/remix-run/react-router-templates/tree/main/node-custom-server template)
- add the global var to the server-side env in
app.ts
globalThis["__ENV"] = {CDN_URL: "http://some.cdn.server"}
- add the global var to the window obj in
root.tsx(before<Scripts/>)
<script dangerouslySetInnerHTML={{__html:`window["__ENV"] = ${JSON.stringify(__ENV)}`}}/>
- use it
<img src={`${__ENV.CDN_URL}/image.png`}/>