Open History to see the last commit
1---
2id: environment-variables
3title: Environment Variables
4---
5β
6Learn how to securely configure and use environment variables in your TanStack Start application across different contexts (server functions, client code, and build processes).
7β
8> **Read env per-request, not at module scope.** On Cloudflare Workers and other edge SSR runtimes, env vars are injected at request time β module-level `process.env.X` reads run before the env exists and evaluate to `undefined` even on the server. Always read `process.env` inside `.handler()`, middleware `.server()`, server-route handlers, or other per-request callbacks. Reading at module scope also risks inlining secrets into the client bundle. (On Cloudflare Workers specifically, the canonical way to read env from anywhere β including module scope β is the [`cloudflare:workers` env binding](https://developers.cloudflare.com/workers/configuration/environment-variables/).)
9β
10## Quick Start
11β
12TanStack Start automatically loads `.env` files and makes variables available in both server and client contexts with proper security boundaries. Server code can read unprefixed variables from `process.env`; client code can only read variables exposed by your build tool's public prefix.
13β
14<!-- ::start:tabs variant="bundler" -->
15β
16# Vite
17β
18```bash
19# .env
20DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
21VITE_APP_NAME=My TanStack Start App
22```
23β
24```typescript
25// Server function - can access any environment variable
26const getUser = createServerFn().handler(async () => {
27 const db = await connect(process.env.DATABASE_URL) // β
Server-only
28 return db.user.findFirst()
29})
30β
31// Client component - only VITE_ prefixed variables
32export function AppHeader() {
33 return <h1>{import.meta.env.VITE_APP_NAME}</h1> // β
Client-safe
34}
35```
36β
37# Rsbuild
38β
39```bash
40# .env
41DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
42PUBLIC_APP_NAME=My TanStack Start App
43```
44β
45```typescript
46// Server function - can access any environment variable
47const getUser = createServerFn().handler(async () => {
48 const db = await connect(process.env.DATABASE_URL) // β
Server-only
49 return db.user.findFirst()
50})
51β
52// Client component - only PUBLIC_ prefixed variables by default
53export function AppHeader() {
54 return <h1>{import.meta.env.PUBLIC_APP_NAME}</h1> // β
Client-safe
55}
56```
57β
58<!-- ::end:tabs -->
59β
60## Environment Variable Contexts
61β
62### Server-Side Context (Server Functions & API Routes)
63β
64Server functions can access **any** environment variable using `process.env`:
65β
66```typescript
67import { createServerFn } from '@tanstack/react-start'
68β
69// Database connection (server-only)
70const connectToDatabase = createServerFn().handler(async () => {
71 const connectionString = process.env.DATABASE_URL // No prefix needed
72 const apiKey = process.env.EXTERNAL_API_SECRET // Stays on server
73β
74 // These variables are never exposed to the client
75 return await database.connect(connectionString)
76})
77β
78// Authentication (server-only)
79const authenticateUser = createServerFn()
80 .validator(z.object({ token: z.string() }))
81 .handler(async ({ data }) => {
82 const jwtSecret = process.env.JWT_SECRET // Server-only
83 return jwt.verify(data.token, jwtSecret)
84 })
85```
86β
87### Client-Side Context (Components & Client Code)
88β
89Client code can only access variables with your build tool's public prefix.
90β
91<!-- ::start:tabs variant="bundler" -->
92β
93# Vite
94β
95Vite exposes variables with the `VITE_` prefix:
96β
97```typescript
98// Client configuration
99export function ApiProvider({ children }: { children: React.ReactNode }) {
100 const apiUrl = import.meta.env.VITE_API_URL // β
Public
101 const apiKey = import.meta.env.VITE_PUBLIC_KEY // β
Public
102β
103 // This would be undefined (security feature):
104 // const secret = import.meta.env.DATABASE_URL // β Undefined
105β
106 return (
107 <ApiContext.Provider value={{ apiUrl, apiKey }}>
108 {children}
109 </ApiContext.Provider>
110 )
111}
112β
113// Feature flags
114export function FeatureGatedComponent() {
115 const enableNewFeature = import.meta.env.VITE_ENABLE_NEW_FEATURE === 'true'
116β
117 if (!enableNewFeature) return null
118β
119 return <NewFeature />
120}
121```
122β
123# Rsbuild
124β
125Rsbuild exposes variables with the `PUBLIC_` prefix by default:
126β
127```typescript
128// Client configuration
129export function ApiProvider({ children }: { children: React.ReactNode }) {
130 const apiUrl = import.meta.env.PUBLIC_API_URL // β
Public
131 const apiKey = import.meta.env.PUBLIC_KEY // β
Public
132β
133 // This would be undefined (security feature):
134 // const secret = import.meta.env.DATABASE_URL // β Undefined
135β
136 return (
137 <ApiContext.Provider value={{ apiUrl, apiKey }}>
138 {children}
139 </ApiContext.Provider>
140 )
141}
142β
143// Feature flags
144export function FeatureGatedComponent() {
145 const enableNewFeature = import.meta.env.PUBLIC_ENABLE_NEW_FEATURE === 'true'
146β
147 if (!enableNewFeature) return null
148β
149 return <NewFeature />
150}
151```
152β
153<!-- ::end:tabs -->
154β
155## Environment File Setup
156β
157### File Hierarchy (Loaded in Order)
158β
159TanStack Start automatically loads environment files in this order:
160β
161```
162.env.local # Local overrides (add to .gitignore)
163.env.production # Production-specific variables
164.env.development # Development-specific variables
165.env # Default variables (commit to git)
166```
167β
168### Example Setup
169β
170**.env** (committed to repository):
171β
172```bash
173# Public configuration (Vite uses VITE_; Rsbuild uses PUBLIC_ by default)
174VITE_APP_NAME=My TanStack Start App
175VITE_API_URL=https://api.example.com
176VITE_SENTRY_DSN=https://...
177PUBLIC_APP_NAME=My TanStack Start App
178PUBLIC_API_URL=https://api.example.com
179PUBLIC_SENTRY_DSN=https://...
180β
181# Server configuration templates
182DATABASE_URL=postgresql://localhost:5432/myapp_dev
183REDIS_URL=redis://localhost:6379
184```
185β
186**.env.local** (add to .gitignore):
187β
188```bash
189# Override for local development
190DATABASE_URL=postgresql://user:password@localhost:5432/myapp_local
191STRIPE_SECRET_KEY=sk_test_...
192JWT_SECRET=your-local-secret
193```
194β
195**.env.production**:
196β
197```bash
198# Production overrides
199VITE_API_URL=https://api.myapp.com
200PUBLIC_API_URL=https://api.myapp.com
201DATABASE_POOL_SIZE=20
202```
203β
204## Common Patterns
205β
206### Database Configuration
207β
208```typescript
209// src/lib/database.ts
210import { createServerFn } from '@tanstack/react-start'
211β
212const getDatabaseConnection = createServerFn().handler(async () => {
213 const config = {
214 url: process.env.DATABASE_URL,
215 maxConnections: parseInt(process.env.DB_MAX_CONNECTIONS || '10'),
216 ssl: process.env.NODE_ENV === 'production',
217 }
218β
219 return createConnection(config)
220})
221```
222β
223### Authentication Provider Setup
224β
225```typescript
226// src/lib/auth.ts (Server)
227export const authConfig = {
228 secret: process.env.AUTH_SECRET,
229 providers: {
230 auth0: {
231 domain: process.env.AUTH0_DOMAIN,
232 clientId: process.env.AUTH0_CLIENT_ID,
233 clientSecret: process.env.AUTH0_CLIENT_SECRET, // Server-only
234 }
235 }
236}
237β
238// src/components/AuthProvider.tsx (Client)
239export function AuthProvider({ children }: { children: React.ReactNode }) {
240 return (
241 <Auth0Provider
242 domain={import.meta.env.VITE_AUTH0_DOMAIN}
243 clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
244 // No client secret here - it stays on the server
245 >
246 {children}
247 </Auth0Provider>
248 )
249}
250```
251β
252### External API Integration
253β
254```typescript
255// src/lib/external-api.ts
256import { createServerFn } from '@tanstack/react-start'
257β
258// Server-side API calls (can use secret keys)
259const fetchUserData = createServerFn()
260 .validator(z.object({ userId: z.string() }))
261 .handler(async ({ data }) => {
262 const response = await fetch(
263 `${process.env.EXTERNAL_API_URL}/users/${data.userId}`,
264 {
265 headers: {
266 Authorization: `Bearer ${process.env.EXTERNAL_API_SECRET}`,
267 'Content-Type': 'application/json',
268 },
269 },
270 )
271β
272 return response.json()
273 })
274β
275// Client-side API calls (public endpoints only)
276export function usePublicData() {
277 const apiUrl = import.meta.env.VITE_PUBLIC_API_URL
278β
279 return useQuery({
280 queryKey: ['public-data'],
281 queryFn: () => fetch(`${apiUrl}/public/stats`).then((r) => r.json()),
282 })
283}
284```
285β
286### Feature Flags and Configuration
287β
288```typescript
289// src/config/features.ts
290export const featureFlags = {
291 enableNewDashboard: import.meta.env.VITE_ENABLE_NEW_DASHBOARD === 'true',
292 enableAnalytics: import.meta.env.VITE_ENABLE_ANALYTICS === 'true',
293 debugMode: import.meta.env.VITE_DEBUG_MODE === 'true',
294}
295β
296// Usage in components
297export function Dashboard() {
298 if (featureFlags.enableNewDashboard) {
299 return <NewDashboard />
300 }
301β
302 return <LegacyDashboard />
303}
304```
305β
306## Type Safety
307β
308### TypeScript Declarations
309β
310Create `src/env.d.ts` to add type safety:
311β
312<!-- ::start:tabs variant="bundler" -->
313β
314# Vite
315β
316```typescript
317/// <reference types="vite/client" />
318β
319interface ImportMetaEnv {
320 // Client-side environment variables
321 readonly VITE_APP_NAME: string
322 readonly VITE_API_URL: string
323 readonly VITE_AUTH0_DOMAIN: string
324 readonly VITE_AUTH0_CLIENT_ID: string
325 readonly VITE_SENTRY_DSN?: string
326 readonly VITE_ENABLE_NEW_DASHBOARD?: string
327}
328β
329interface ImportMeta {
330 readonly env: ImportMetaEnv
331}
332β
333// Server-side environment variables
334declare global {
335 namespace NodeJS {
336 interface ProcessEnv {
337 readonly DATABASE_URL: string
338 readonly REDIS_URL: string
339 readonly JWT_SECRET: string
340 readonly AUTH0_CLIENT_SECRET: string
341 readonly STRIPE_SECRET_KEY: string
342 readonly NODE_ENV: 'development' | 'production' | 'test'
343 }
344 }
345}
346β
347export {}
348```
349β
350# Rsbuild
351β
352```typescript
353/// <reference types="@rsbuild/core/types" />
354β
355interface ImportMetaEnv {
356 // Client-side environment variables
357 readonly PUBLIC_APP_NAME: string
358 readonly PUBLIC_API_URL: string
359 readonly PUBLIC_AUTH0_DOMAIN: string
360 readonly PUBLIC_AUTH0_CLIENT_ID: string
361 readonly PUBLIC_SENTRY_DSN?: string
362 readonly PUBLIC_ENABLE_NEW_DASHBOARD?: string
363}
364β
365interface ImportMeta {
366 readonly env: ImportMetaEnv
367}
368β
369// Server-side environment variables
370declare global {
371 namespace NodeJS {
372 interface ProcessEnv {
373 readonly DATABASE_URL: string
374 readonly REDIS_URL: string
375 readonly JWT_SECRET: string
376 readonly AUTH0_CLIENT_SECRET: string
377 readonly STRIPE_SECRET_KEY: string
378 readonly NODE_ENV: 'development' | 'production' | 'test'
379 }
380 }
381}
382β
383export {}
384```
385β
386<!-- ::end:tabs -->
387β
388### Runtime Validation
389β
390Use Zod for runtime validation of environment variables:
391β
392```typescript
393// src/config/env.ts
394import { z } from 'zod'
395β
396const envSchema = z.object({
397 DATABASE_URL: z.url(),
398 JWT_SECRET: z.string().min(32),
399 NODE_ENV: z.enum(['development', 'production', 'test']),
400})
401β
402const clientEnvSchema = z.object({
403 VITE_APP_NAME: z.string(),
404 VITE_API_URL: z.url(),
405 VITE_AUTH0_DOMAIN: z.string(),
406 VITE_AUTH0_CLIENT_ID: z.string(),
407})
408β
409// Validate server environment
410// NOTE: Module-level parse runs at module load. Fine for Node.js;
411// on Cloudflare Workers (and other edge runtimes) `process.env` is
412// empty at module load, so wrap this in a function and call it
413// inside `.handler()` instead:
414//
415// export const getServerEnv = () => envSchema.parse(process.env)
416//
417// Then read `getServerEnv()` per-request from server functions/middleware.
418export const serverEnv = envSchema.parse(process.env)
419β
420// Validate client environment (build-time, always safe)
421export const clientEnv = clientEnvSchema.parse(import.meta.env)
422```
423β
424## Security Best Practices
425β
426### 1. Never Expose Secrets to Client
427β
428```typescript
429// β WRONG - Secret exposed to client bundle
430const config = {
431 apiKey: import.meta.env.VITE_SECRET_API_KEY, // This will be in your JS bundle!
432}
433β
434// β
CORRECT - Keep secrets on server
435const getApiData = createServerFn().handler(async () => {
436 const response = await fetch(apiUrl, {
437 headers: { Authorization: `Bearer ${process.env.SECRET_API_KEY}` },
438 })
439 return response.json()
440})
441```
442β
443### 2. Use Appropriate Prefixes
444β
445```bash
446# β
Server-only (no prefix)
447DATABASE_URL=postgresql://...
448JWT_SECRET=super-secret-key
449STRIPE_SECRET_KEY=sk_live_...
450β
451# β
Client-safe (Vite uses VITE_; Rsbuild uses PUBLIC_ by default)
452VITE_APP_NAME=My App
453VITE_API_URL=https://api.example.com
454VITE_SENTRY_DSN=https://...
455PUBLIC_APP_NAME=My App
456PUBLIC_API_URL=https://api.example.com
457PUBLIC_SENTRY_DSN=https://...
458```
459β
460### 3. Validate Required Variables
461β
462```typescript
463// src/config/validation.ts
464const requiredServerEnv = ['DATABASE_URL', 'JWT_SECRET'] as const
465β
466const requiredClientEnv = ['VITE_APP_NAME', 'VITE_API_URL'] as const // Use PUBLIC_ names for Rsbuild
467β
468// Validate on server startup
469for (const key of requiredServerEnv) {
470 if (!process.env[key]) {
471 throw new Error(`Missing required environment variable: ${key}`)
472 }
473}
474β
475// Validate client environment at build time
476for (const key of requiredClientEnv) {
477 if (!import.meta.env[key]) {
478 throw new Error(`Missing required environment variable: ${key}`)
479 }
480}
481```
482β
483## Production Checklist
484β
485- [ ] All sensitive variables are server-only (no `VITE_` or `PUBLIC_` prefix)
486- [ ] Client variables use your build tool's public prefix (`VITE_` for Vite, `PUBLIC_` for Rsbuild)
487- [ ] `.env.local` is in `.gitignore`
488- [ ] Production environment variables are configured on hosting platform
489- [ ] Required environment variables are validated at startup
490- [ ] No hardcoded secrets in source code
491- [ ] Database URLs use connection pooling in production
492- [ ] API keys are rotated regularly
493β
494## Common Problems
495β
496### Environment Variable is Undefined
497β
498**Problem**: `import.meta.env.MY_VARIABLE` returns `undefined`
499β
500**Solutions**:
501β
5021. **Add correct prefix**: Use your build tool's public prefix (e.g. `VITE_MY_VARIABLE` for Vite or `PUBLIC_MY_VARIABLE` for Rsbuild)
5032. **Restart development server** after adding new variables
5043. **Check file location**: `.env` file must be in project root
5054. **Verify build tool configuration**: Ensure variables are properly injected
506β
507**Example**:
508β
509```bash
510# β Won't work in client code
511API_KEY=abc123
512β
513# β
Works in client code
514VITE_API_KEY=abc123
515β
516# β Won't bundle the variable (assuming it is not set in the environment of the build)
517npm run build
518β
519# β
Works in client code and will bundle the variable for production
520VITE_API_KEY=abc123 npm run build
521```
522β
523### Runtime Client Environment Variables in Production
524β
525**Problem**: If public client variables are replaced at bundle time only, how to make runtime variables available on the client?
526β
527**Solutions**:
528β
529Pass variables from the server down to the client:
530β
531```tsx
532const getRuntimeVar = createServerFn({ method: 'GET' }).handler(() => {
533 return process.env.MY_RUNTIME_VAR // notice `process.env` on the server, and no public prefix
534})
535β
536export const Route = createFileRoute('/')({
537 loader: async () => {
538 const foo = await getRuntimeVar()
539 return { foo }
540 },
541 component: RouteComponent,
542})
543β
544function RouteComponent() {
545 const { foo } = Route.useLoaderData()
546 // ... use your variable however you want
547}
548```
549β
550### Variable Not Updating
551β
552**Problem**: Environment variable changes aren't reflected
553β
554**Solutions**:
555β
5561. Restart development server
5572. Check if you're modifying the correct `.env` file
5583. Verify file hierarchy (`.env.local` overrides `.env`)
559β
560### TypeScript Errors
561β
562**Problem**: `Property 'VITE_MY_VAR' does not exist on type 'ImportMetaEnv'` or `Property 'PUBLIC_MY_VAR' does not exist on type 'ImportMetaEnv'`
563β
564**Solution**: Add to `src/env.d.ts`:
565β
566```typescript
567interface ImportMetaEnv {
568 readonly VITE_MY_VAR: string
569 readonly PUBLIC_MY_VAR: string
570}
571```
572β
573### Security: Secret Exposed to Client
574β
575**Problem**: Sensitive data appearing in client bundle
576β
577**Solutions**:
578β
5791. Remove `VITE_` or `PUBLIC_` prefix from sensitive variables
5802. Move sensitive operations to server functions
5813. Use build tools to verify no secrets in client bundle
582β
583### Build Errors in Production
584β
585**Problem**: Missing environment variables in production build
586β
587**Solutions**:
588β
5891. Configure variables on hosting platform
5902. Validate required variables at build time
5913. Use deployment-specific `.env` files
592β
593## Server Build Configuration
594β
595### Static `NODE_ENV` Replacement
596β
597By default, TanStack Start statically replaces `process.env.NODE_ENV` in **server builds** at build time. This enables dead code elimination (tree-shaking) for development-only code paths in your server bundle.
598β
599**Why this matters:** Vite automatically replaces `process.env.NODE_ENV` in client builds, but server builds run in Node.js where `process.env` is a real runtime object. Without static replacement, code like this would remain in your production server bundle:
600β
601```typescript
602if (process.env.NODE_ENV === 'development') {
603 // This code would NOT be eliminated without static replacement
604 enableDevTools()
605 logDebugInfo()
606}
607```
608β
609With static replacement enabled (the default), the build tool sees `"production" === 'development'` and eliminates the entire block.
610β
611### Configuring Static Replacement
612β
613The replacement is controlled by the `server.build.staticNodeEnv` option:
614β
615<!-- ::start:tabs variant="bundler" -->
616β
617# Vite
618β
619```ts title="vite.config.ts"
620import { defineConfig } from 'vite'
621import { tanstackStart } from '@tanstack/react-start/plugin/vite'
622import viteReact from '@vitejs/plugin-react'
623β
624export default defineConfig({
625 plugins: [
626 tanstackStart({
627 server: {
628 build: {
629 // Replace process.env.NODE_ENV at build time (default: true)
630 staticNodeEnv: true,
631 },
632 },
633 }),
634 viteReact(),
635 ],
636})
637```
638β
639# Rsbuild
640β
641```ts title="rsbuild.config.ts"
642import { defineConfig } from '@rsbuild/core'
643import { pluginReact } from '@rsbuild/plugin-react'
644import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
645β
646export default defineConfig({
647 plugins: [
648 pluginReact(),
649 tanstackStart({
650 server: {
651 build: {
652 // Replace process.env.NODE_ENV at build time (default: true)
653 staticNodeEnv: true,
654 },
655 },
656 }),
657 ],
658})
659```
660β
661<!-- ::end:tabs -->
662β
663The replacement value is determined in this order:
664β
6651. `process.env.NODE_ENV` at build time (if set)
6662. The build tool's `mode` (e.g., from `--mode staging`)
6673. `"production"` (fallback)
668β
669### When to Disable Static Replacement
670β
671Set `staticNodeEnv: false` if you need `NODE_ENV` to remain dynamic at runtime:
672β
673```ts
674tanstackStart({
675 server: {
676 build: {
677 staticNodeEnv: false, // Keep NODE_ENV dynamic at runtime
678 },
679 },
680})
681```
682β
683Common reasons to disable:
684β
685- **Same build, multiple environments**: Deploying one build artifact to staging and production
686- **Runtime environment detection**: Code that must check the actual runtime environment
687- **Testing production builds locally**: Running production builds with `NODE_ENV=development`
688β
689> **Note:** Disabling static replacement means development-only code paths will remain in your production bundle and be evaluated at runtime.
690β
691> **Important:** If you disable `staticNodeEnv`, you **must** set `NODE_ENV=production` at runtime when running your server in production. Without this, React (and possibly other libraries) will run in development mode, which is significantly slower and includes extra warnings and checks not intended for production use.
692β
693## Related Resources
694β
695- [Code Execution Patterns](./code-execution-patterns.md) - Learn about server vs client code execution
696- [Server Functions](./server-functions.md) - Learn more about server-side code
697- [Hosting](./hosting.md) - Platform-specific environment variable configuration
698- [Vite Environment Variables](https://vitejs.dev/guide/env-and-mode.html) - Official Vite documentation
699- [Rsbuild Environment Variables](https://rsbuild.dev/guide/advanced/env-vars) - Official Rsbuild documentation