Best way for runtime validation of environment variables in Tanstack Start #6362
Unanswered
wizard-knight
asked this question in
Q&A
Replies: 1 comment
-
|
what I ended up doing is the creation of separate files for client and server env parsing: // src/config/env.client.ts
import { z } from 'zod'
const clientEnvSchema = z.object({
VITE_APP_NAME: z.string(),
VITE_API_URL: z.string().url(),
VITE_AUTH0_DOMAIN: z.string(),
VITE_AUTH0_CLIENT_ID: z.string(),
})
export const clientEnv = createClientOnlyFn(() => clientEnvSchema.parse(import.meta.env))()// src/config/env.server.ts
import { z } from 'zod'
const envSchema = z.object({
DATABASE_URL: z.string().url(),
JWT_SECRET: z.string().min(32),
NODE_ENV: z.enum(['development', 'production', 'test']),
})
export const serverEnv = createServerOnlyFn(() => envSchema.parse(process.env))()the use of |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
According to the docs, the suggested way for handling runtime validation of environment variables is as follows:
Runtime Validation
Use Zod for runtime validation of environment variables:
https://github.com/TanStack/router/blob/main/docs/start/framework/react/guide/environment-variables.md#runtime-validation
The issue with this approach is that whenever the
clientEnvorserverEnvis used in the code, this file will run and the parsing logic based on client and server env will be executed regardless ofserverEnvorclientEnvbeing used. This results in errors in client thrown by the validation library during server env parsing and also exposes the names of server envs used (not corresponding values)(this was checked in dev build only 😅).While exploring better solutions for this issue came across a message in discord mentioning the use of
createIsomorphicFn.https://discord.com/channels/719702312431386674/1424531973929566360/1424584313407799317
The issue with this approach is that the resulting env will not have a type safety based on the context it's being used.
another solution was to use the t3-env, which I'm yet to try
Thus, if anyone have any alternative ideas or better ways to handle validation of envs in tanstack start, feel free to share your views.
Beta Was this translation helpful? Give feedback.
All reactions