Skip to content

Commit 1c7f017

Browse files
hyperb1issclaude
andcommitted
docs: 📚 clarify env() works in all contexts including middleware
Fixes confusion about when to use env() vs process.env ## Changes - Update middleware example to use env() instead of process.env - Add clear note that env() works in all Next.js contexts - Improve "Server vs Client Environment Access" section with better clarity - Update security example to consistently use env() - Add recommendation to use env() everywhere for consistency ## Rationale The env() function is designed with proper error handling to work in: - Server components ✅ - Client components ✅ - API routes ✅ - Middleware ✅ (gracefully falls back when headers() unavailable) Using env() everywhere provides: - Consistent API across the application - Better error messages when accessing private vars in browser - Type-safe environment variable access - Future-proof code Users should not need to think about process.env vs env() - just use env() everywhere and it will work correctly! 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 2177927 commit 1c7f017

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

README.md

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -131,14 +131,20 @@ export default async function ServerComponent() {
131131

132132
```tsx
133133
// middleware.ts
134+
import { env } from '@hyperb1iss/next-runtime-env'
134135
import { NextResponse } from 'next/server'
135136
import type { NextRequest } from 'next/server'
136137

137138
export function middleware(request: NextRequest) {
138-
// Access environment variables in middleware
139-
const apiUrl = process.env.NEXT_PUBLIC_API_URL
139+
// env() works in middleware too!
140+
const apiUrl = env('NEXT_PUBLIC_API_URL')
141+
const featureFlag = env('NEXT_PUBLIC_ENABLE_FEATURE')
140142

141143
// Your middleware logic here
144+
if (featureFlag === 'true') {
145+
// Feature-specific logic
146+
}
147+
142148
return NextResponse.next()
143149
}
144150

@@ -147,6 +153,9 @@ export const config = {
147153
}
148154
```
149155

156+
> **Note:** The `env()` function works in all Next.js contexts - server components, client components, API routes, and
157+
> middleware. It's safe to use everywhere and provides a consistent API across your application.
158+
150159
## 🛠 Advanced Usage
151160

152161
### Exposing Non-Prefixed Variables
@@ -250,13 +259,14 @@ For static exports with runtime environment support:
250259
**Critical:** Only variables prefixed with `NEXT_PUBLIC_` are exposed to the browser. Never expose sensitive data:
251260

252261
```tsx
253-
// ❌ WRONG - Don't expose secrets
254-
const apiKey = env('SECRET_API_KEY') // Will be undefined in browser
262+
// ❌ WRONG - Don't try to access secrets in client components
263+
'use client'
264+
const apiKey = env('SECRET_API_KEY') // Throws error in browser!
255265

256266
// ✅ CORRECT - Use secrets only server-side
257267
export async function getData() {
258-
const apiKey = process.env.SECRET_API_KEY // Server-side only
259-
// ... fetch data
268+
const apiKey = env('SECRET_API_KEY') // Works in server components/API routes
269+
// ... fetch data securely
260270
}
261271
```
262272

@@ -362,9 +372,16 @@ const apiUrl = env('NEXT_PUBLIC_API_URL')!
362372

363373
**Key Differences:**
364374

365-
- **Server components/API routes:** Can access ALL environment variables via `process.env`
366-
- **Client components:** Can only access `NEXT_PUBLIC_*` variables via `env()`
367-
- **Middleware:** Uses standard `process.env` access
375+
- **Server-side contexts** (server components, API routes, middleware):
376+
- Can access ALL environment variables via `env()` or `process.env`
377+
- Both private and public (`NEXT_PUBLIC_*`) variables are available
378+
379+
- **Client-side contexts** (client components, browser):
380+
- Can only access `NEXT_PUBLIC_*` variables via `env()`
381+
- Private variables are not available for security reasons
382+
- Attempting to access private variables throws an error
383+
384+
**Recommendation:** Use `env()` everywhere for consistency. It works in all contexts and provides better error messages when misused
368385

369386
## 📚 Additional Resources
370387

0 commit comments

Comments
 (0)