Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

environment-variables.md

699 lines19.2 KB

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
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
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 )
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 />
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 )
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 />
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 }
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 )
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 })
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',
295​
296// Usage in components
297export function Dashboard() {
298 if (featureFlags.enableNewDashboard) {
299 return <NewDashboard />
300 }
301​
302 return <LegacyDashboard />
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
328​
329interface ImportMeta {
330 readonly env: ImportMetaEnv
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 }
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
364​
365interface ImportMeta {
366 readonly env: ImportMetaEnv
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 }
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!
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 }
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 }
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
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
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()
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