T
TanStack4h ago
deep-jade

Environment variables best practices

In one example here (https://tanstack.com/start/latest/docs/framework/react/execution-model), I noticed a code snipped saying to use createServerOnlyFn to return an environment variable so that it's not accidentally leaked to the client. However, in another section (https://tanstack.com/start/latest/docs/framework/react/environment-variables) it says that env variables aren't even accessible in client code unless the name is prefixed with VITE_. I'm struggling to understand in which circumstance each solution is supposed to be used, as from my understanding they both result in the same end functionality of the variable being withheld from the client bundle. Can anyone shed some light on this and help me understand the specific cases in which one approach should be preffered? Thanks!
1 Reply
absent-sapphire
absent-sapphire3h ago
As I understand it, the VITE prefix only matters if you want an environment variable to appear in import.meta.env, because process isn’t available in the client. So what’s the actual problem? If you reference process.env.* somewhere in code that gets bundled for the client, Vite will read that value at build time and inline it as a constant. As a result, you can end up leaking environment variables that you never intended to expose with VITE_. The solution is simple: Keep server-only code separate from isomorphic/shared code — for example, by wrapping access in server-only functions or T3 stack.

Did you find this page helpful?