@@ -7,185 +7,165 @@ sidebar:
77
88Pass configuration, secrets, and runtime settings to your sandboxes using environment variables.
99
10- ### Command and process variables
10+ ## Three ways to set environment variables
1111
12- Pass environment variables when executing commands or starting processes:
12+ The Sandbox SDK provides three methods for setting environment variables, each suited for different use cases:
13+
14+ ### 1. Sandbox-level with setEnvVars()
15+
16+ Set environment variables globally for all commands in the sandbox:
17+
18+ ``` typescript
19+ const sandbox = getSandbox (env .Sandbox , " my-sandbox" );
20+
21+ // Set once, available for all subsequent commands
22+ await sandbox .setEnvVars ({
23+ DATABASE_URL: env .DATABASE_URL ,
24+ API_KEY: env .API_KEY ,
25+ });
26+
27+ await sandbox .exec (" python migrate.py" ); // Has DATABASE_URL and API_KEY
28+ await sandbox .exec (" python seed.py" ); // Has DATABASE_URL and API_KEY
29+ ```
30+
31+ ** Use when:** You need the same environment variables for multiple commands.
32+
33+ ### 2. Per-command with exec() options
34+
35+ Pass environment variables for a specific command:
1336
1437``` typescript
15- // Commands
1638await sandbox .exec (" node app.js" , {
1739 env: {
1840 NODE_ENV: " production" ,
19- API_KEY: env .API_KEY , // Pass from Worker env
2041 PORT: " 3000" ,
2142 },
2243});
2344
24- // Background processes (same syntax )
45+ // Also works with startProcess( )
2546await sandbox .startProcess (" python server.py" , {
2647 env: {
2748 DATABASE_URL: env .DATABASE_URL ,
28- SECRET_KEY: env .SECRET_KEY ,
2949 },
3050});
3151```
3252
33- ### Session -level variables
53+ ** Use when: ** You need different environment variables for different commands, or want to override sandbox -level variables.
3454
35- Set environment variables for all commands in a session:
55+ ### 3. Session-level with createSession()
3656
37- ``` typescript
38- const session = await sandbox .createSession ();
57+ Create an isolated session with its own environment variables:
3958
40- await session .setEnvVars ({
41- DATABASE_URL: env .DATABASE_URL ,
42- SECRET_KEY: env .SECRET_KEY ,
59+ ``` typescript
60+ const session = await sandbox .createSession ({
61+ env: {
62+ DATABASE_URL: env .DATABASE_URL ,
63+ SECRET_KEY: env .SECRET_KEY ,
64+ },
4365});
4466
4567// All commands in this session have these vars
4668await session .exec (" python migrate.py" );
4769await session .exec (" python seed.py" );
4870```
4971
72+ ** Use when:** You need isolated execution contexts with different environment variables running concurrently.
73+
5074## Common patterns
5175
5276### Pass Worker secrets to sandbox
5377
54- Securely pass secrets from Worker environment:
78+ Securely pass secrets from your Worker to the sandbox. First, set secrets using Wrangler:
79+
80+ ``` bash
81+ wrangler secret put OPENAI_API_KEY
82+ wrangler secret put DATABASE_URL
83+ ```
84+
85+ Then pass them to your sandbox:
5586
5687``` typescript
5788interface Env {
5889 Sandbox: DurableObjectNamespace ;
59- OPENAI_API_KEY: string ; // Set with `wrangler secret put`
90+ OPENAI_API_KEY: string ;
6091 DATABASE_URL: string ;
6192}
6293
6394export default {
6495 async fetch(request : Request , env : Env ): Promise <Response > {
6596 const sandbox = getSandbox (env .Sandbox , " user-sandbox" );
6697
67- const result = await sandbox .exec (" python analyze.py" , {
98+ // Option 1: Set globally for all commands
99+ await sandbox .setEnvVars ({
100+ OPENAI_API_KEY: env .OPENAI_API_KEY ,
101+ DATABASE_URL: env .DATABASE_URL ,
102+ });
103+ await sandbox .exec (" python analyze.py" );
104+
105+ // Option 2: Pass per-command
106+ await sandbox .exec (" python analyze.py" , {
68107 env: {
69108 OPENAI_API_KEY: env .OPENAI_API_KEY ,
70- DATABASE_URL: env .DATABASE_URL ,
71109 },
72110 });
73111
74- return Response .json ({ result });
112+ return Response .json ({ success: true });
75113 },
76114};
77115```
78116
79- ### Default values with spreading
80-
81- Combine default and command-specific variables:
117+ ### Combine default and specific variables
82118
83119``` typescript
84- const defaults = {
85- NODE_ENV: env .ENVIRONMENT || " production" ,
86- LOG_LEVEL: " info" ,
87- TZ: " UTC" ,
88- };
120+ const defaults = { NODE_ENV: " production" , LOG_LEVEL: " info" };
89121
90122await sandbox .exec (" npm start" , {
91- env: {
92- ... defaults ,
93- PORT: " 3000" , // Command-specific override
94- API_KEY: env .API_KEY ,
95- },
96- });
97- ```
98-
99- ## Environment variable precedence
100-
101- When the same variable is set at multiple levels:
102-
103- 1 . ** Command-level** (highest) - Passed to ` exec() ` or ` startProcess() `
104- 2 . ** Session-level** - Set with ` setEnvVars() `
105- 3 . ** Container default** - Built into the Docker image
106- 4 . ** System default** (lowest) - Operating system defaults
107-
108- Example:
109-
110- ``` typescript
111- // In Dockerfile: ENV NODE_ENV=development
112- // In session: await sandbox.setEnvVars({ NODE_ENV: 'staging' });
113-
114- // In command (overrides all):
115- await sandbox .exec (" node app.js" , {
116- env: { NODE_ENV: " production" }, // This wins
123+ env: { ... defaults , PORT: " 3000" , API_KEY: env .API_KEY },
117124});
118125```
119126
120- ## Security best practices
127+ ### Multiple isolated sessions
121128
122- ### Never hardcode secrets
123-
124- ** Bad** - Secrets in code:
129+ Run different tasks with different environment variables concurrently:
125130
126131``` typescript
127- await sandbox .exec (" python app.py" , {
128- env: {
129- API_KEY: " sk-1234567890abcdef" , // NEVER DO THIS
130- },
132+ // Production database session
133+ const prodSession = await sandbox .createSession ({
134+ env: { DATABASE_URL: env .PROD_DATABASE_URL },
131135});
132- ```
133-
134- ** Good** - Secrets from Worker environment:
135136
136- ``` typescript
137- await sandbox .exec (" python app.py" , {
138- env: {
139- API_KEY: env .API_KEY , // From Wrangler secret
140- },
137+ // Staging database session
138+ const stagingSession = await sandbox .createSession ({
139+ env: { DATABASE_URL: env .STAGING_DATABASE_URL },
141140});
142- ```
143-
144- Set secrets with Wrangler:
145-
146- ``` bash
147- wrangler secret put API_KEY
148- ```
149-
150- ## Debugging
151141
152- List all environment variables:
153-
154- ``` typescript
155- const result = await sandbox .exec (" env " );
156- console . log ( result . stdout );
142+ // Run migrations on both concurrently
143+ await Promise . all ([
144+ prodSession . exec ( " python migrate.py " ),
145+ stagingSession .exec (" python migrate.py " ),
146+ ] );
157147```
158148
159- Check specific variable:
160-
161- ``` typescript
162- const result = await sandbox .exec (" echo $NODE_ENV" );
163- console .log (" NODE_ENV:" , result .stdout .trim ());
164- ```
149+ ## Environment variable precedence
165150
166- ## Troubleshooting
151+ When the same variable is set at multiple levels, the most specific level takes precedence:
167152
168- ### Variable not set
153+ 1 . ** Command-level** (highest) - Passed to ` exec() ` or ` startProcess() ` options
154+ 2 . ** Sandbox or session-level** - Set with ` setEnvVars() `
155+ 3 . ** Container default** - Built into the Docker image with ` ENV `
156+ 4 . ** System default** (lowest) - Operating system defaults
169157
170- Verify the variable is being passed :
158+ Example :
171159
172160``` typescript
173- console .log (" Worker env:" , env .API_KEY ? " Set" : " Missing" );
174-
175- const result = await sandbox .exec (" env | grep API_KEY" , {
176- env: { API_KEY: env .API_KEY },
177- });
178- console .log (" Sandbox:" , result .stdout );
179- ```
180-
181- ### Shell expansion issues
161+ // In Dockerfile: ENV NODE_ENV=development
182162
183- Use runtime-specific access instead of shell variables:
163+ // Sandbox-level
164+ await sandbox .setEnvVars ({ NODE_ENV: " staging" });
184165
185- ``` typescript
186- // Instead of: await sandbox.exec('echo $NODE_ENV')
187- await sandbox .exec (' node -e "console.log(process.env.NODE_ENV)"' , {
188- env: { NODE_ENV: " production" },
166+ // Command-level overrides all
167+ await sandbox .exec (" node app.js" , {
168+ env: { NODE_ENV: " production" }, // This wins
189169});
190170```
191171
0 commit comments