-
In my Remix app I use the recommended approach to expose certain (non-secret) environment variables to the browser. I then made an isomorphic import { config } from "~/config.server";
/**
* Get an env value that's available on the `window` object for client side but also needs to
* be accessed server side.
* @param key
* @returns
*/
export function getPublicEnv<T extends keyof PublicConfig>(
key: T
): PublicConfig[T] {
return typeof window === "undefined"
? config[key]
: window.appConfig[key];
} This is very useful for certain things like public-facing api keys that are used in a React component, say to render some URL. E.g. const MapImage = ({lat,lng}) => {
return <img src={`https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/${lng},${lat}?access_token=${getPublicEnv('mapboxToken')}`} />
} Because this component itself may be rendered by both the client and server, the This works fine with the Remix server and bundler, but since migrating to Vite I get an error when bundling:
This is not too surprising and likely a result of how Vite separates client and server code. My question is how to enable this behaviour with Vite. Given that React components in Remix themselves are isomorphic, I'd expect this to be possible. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Use the The See this example: |
Beta Was this translation helpful? Give feedback.
-
I think it's simpler to define |
Beta Was this translation helpful? Give feedback.
Use the
serverOnly$
export fromvite-env-only
instead of naming it*.server
The
.server
suffix should only be applied to a file where all exports are on the server.See this example:
https://github.com/kiliman/remix-global-data/blob/main/app/global-data.ts#L23