TanStackT
TanStack4mo ago
5 replies
safe-amethyst

Using zod to parse environment

In the docs there is a runtime validation example in https://tanstack.com/start/latest/docs/framework/react/environment-variables#runtime-validation

// src/config/env.ts
import { z } from 'zod'
const envSchema = z.object({
  DATABASE_URL: z.string().url(),
})
const clientEnvSchema = z.object({
  VITE_APP_NAME: z.string(),
})
export const serverEnv = envSchema.parse(process.env)
export const clientEnv = clientEnvSchema.parse(import.meta.env)


I'm struggling to get this to work as this file end up getting included in the client and the serverEnv parse produces and error.

I'e tried a couple of things
* splitting into different files - but it ends up being included anyway
export const serverEnv = createServerOnlyFn(() => schema.parse(process.env));


But I feel like this will impact performance as throughout the code I'll be using serverEnv() everywhere so it's always reparsing.

What's the "right" pattern here?
Learn how to securely configure and use environment variables in your TanStack Start application across different contexts (server functions, client code, and build processes). Quick Start TanStack St...
Environment Variables | TanStack Start React Docs
Was this page helpful?