0
# Environment Variables
1
2
Cross-platform environment variable access that works consistently across Node.js, Deno, Bun, and browser environments using a Proxy-based approach.
3
4
## Capabilities
5
6
### Environment Variable Proxy
7
8
The `env` proxy provides universal access to environment variables across different JavaScript runtimes.
9
10
```typescript { .api }
11
/**
12
* Cross-platform environment variable proxy that works across all JavaScript runtimes
13
* Supports Node.js process.env, Deno.env, import.meta.env, and browser globalThis.__env__
14
*/
15
const env: EnvObject;
16
17
type EnvObject = Record<string, string | undefined>;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import { env } from "std-env";
24
25
// Read environment variables
26
const apiKey = env.API_KEY;
27
const nodeEnv = env.NODE_ENV;
28
const port = env.PORT || "3000";
29
30
// Set environment variables (when possible)
31
env.DEBUG = "true";
32
33
// Check if environment variable exists
34
if ("DATABASE_URL" in env) {
35
console.log("Database URL is configured");
36
}
37
38
// Iterate over environment variables
39
for (const key of Object.getOwnPropertyNames(env)) {
40
console.log(`${key}: ${env[key]}`);
41
}
42
```
43
44
The `env` proxy automatically detects the runtime and uses the appropriate environment access method:
45
- **Node.js**: `process.env`
46
- **Deno**: `Deno.env.toObject()`
47
- **Vite/Rollup**: `import.meta.env`
48
- **Browser/Custom**: `globalThis.__env__`
49
50
### Node.js Environment Variable
51
52
Direct access to the NODE_ENV environment variable with fallback to empty string.
53
54
```typescript { .api }
55
/**
56
* Value of NODE_ENV environment variable or empty string if not set
57
* Specifically reads from process.env.NODE_ENV when available
58
*/
59
const nodeENV: string;
60
```
61
62
**Usage Examples:**
63
64
```typescript
65
import { nodeENV } from "std-env";
66
67
// Check specific Node.js environment
68
if (nodeENV === "production") {
69
console.log("Running in production mode");
70
} else if (nodeENV === "development") {
71
console.log("Running in development mode");
72
} else if (nodeENV === "test") {
73
console.log("Running in test mode");
74
}
75
76
// Use as fallback when env proxy might not be available
77
const environment = nodeENV || "development";
78
```
79
80
## Runtime Compatibility
81
82
The environment variable system works across all supported JavaScript runtimes:
83
84
- **Node.js**: Uses `process.env` directly
85
- **Deno**: Uses `Deno.env.toObject()` for read access
86
- **Bun**: Compatible with Node.js `process.env`
87
- **Browser**: Uses `import.meta.env` (Vite/bundlers) or `globalThis.__env__`
88
- **Edge Runtimes**: Falls back to available global environment objects