Skip to Content
Environment Variables

Last Updated: 3/7/2026


Environment Variables

Manage environment variables in your E2B sandboxes.

Overview

Environment variables allow you to configure sandbox behavior and pass configuration to your code without hardcoding values.

Setting Environment Variables

At Creation Time

import { Sandbox } from 'e2b' const sandbox = await Sandbox.create({ envVars: { DATABASE_URL: 'postgresql://localhost/mydb', API_KEY: 'secret-key', DEBUG: 'true', PORT: '3000' } })

After Creation

// Set single variable await sandbox.setEnvVar('NEW_VAR', 'value') // Set multiple variables await sandbox.setEnvVars({ VAR1: 'value1', VAR2: 'value2' })

Reading Environment Variables

In Your Code

// Python const pythonCode = ` import os api_key = os.getenv('API_KEY') print(f'API Key: {api_key}') ` await sandbox.files.write('/home/user/script.py', pythonCode) const result = await sandbox.commands.run('python script.py')
// Node.js const nodeCode = ` const apiKey = process.env.API_KEY console.log('API Key:', apiKey) ` await sandbox.files.write('/home/user/script.js', nodeCode) const result = await sandbox.commands.run('node script.js')

From SDK

// Get single variable const value = await sandbox.getEnvVar('API_KEY') // Get all variables const allVars = await sandbox.getEnvVars() console.log(allVars)

Common Use Cases

API Keys and Secrets

const sandbox = await Sandbox.create({ envVars: { OPENAI_API_KEY: process.env.OPENAI_API_KEY, AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY } })

Configuration

const sandbox = await Sandbox.create({ envVars: { NODE_ENV: 'production', LOG_LEVEL: 'debug', MAX_RETRIES: '3', TIMEOUT: '30000' } })

Database Connections

const sandbox = await Sandbox.create({ envVars: { DATABASE_URL: 'postgresql://user:pass@host:5432/db', REDIS_URL: 'redis://localhost:6379', MONGODB_URI: 'mongodb://localhost:27017/mydb' } })

Security Best Practices

1. Never Hardcode Secrets

Bad:

const sandbox = await Sandbox.create({ envVars: { API_KEY: 'sk-1234567890abcdef' // Don't hardcode! } })

Good:

const sandbox = await Sandbox.create({ envVars: { API_KEY: process.env.API_KEY // Use environment variables } })

2. Use Separate Keys for Development and Production

const sandbox = await Sandbox.create({ envVars: { API_KEY: process.env.NODE_ENV === 'production' ? process.env.PROD_API_KEY : process.env.DEV_API_KEY } })

3. Limit Variable Exposure

Only pass the environment variables that are actually needed:

// Only pass required vars const requiredVars = ['DATABASE_URL', 'API_KEY'] const envVars = Object.fromEntries( requiredVars.map(key => [key, process.env[key]]) ) const sandbox = await Sandbox.create({ envVars })

4. Clean Up Sensitive Data

try { const sandbox = await Sandbox.create({ envVars: { SECRET_KEY: 'sensitive' } }) // Use sandbox } finally { await sandbox.close() // Destroys all data including env vars }

Template-Level Environment Variables

Define in Template

Set default environment variables in your template:

# e2b.Dockerfile FROM ubuntu:22.04 ENV NODE_ENV=production ENV PORT=3000 ENV LOG_LEVEL=info

Override at Runtime

// Template has NODE_ENV=production const sandbox = await Sandbox.create({ template: 'my-template', envVars: { NODE_ENV: 'development' // Override template default } })

Dynamic Environment Variables

Update During Execution

const sandbox = await Sandbox.create() // Initial setup await sandbox.setEnvVar('STAGE', 'setup') await sandbox.commands.run('python setup.py') // Change stage await sandbox.setEnvVar('STAGE', 'processing') await sandbox.commands.run('python process.py') // Final stage await sandbox.setEnvVar('STAGE', 'cleanup') await sandbox.commands.run('python cleanup.py')

Computed Values

const sandbox = await Sandbox.create({ envVars: { SANDBOX_ID: sandbox.id, CREATED_AT: new Date().toISOString(), USER_ID: userId, SESSION_ID: sessionId } })

Common Patterns

Environment Variable Validation

function validateEnvVars(required) { const missing = required.filter(key => !process.env[key]) if (missing.length > 0) { throw new Error(`Missing required env vars: ${missing.join(', ')}`) } } validateEnvVars(['DATABASE_URL', 'API_KEY']) const sandbox = await Sandbox.create({ envVars: { DATABASE_URL: process.env.DATABASE_URL, API_KEY: process.env.API_KEY } })

Configuration Object

const config = { database: { url: process.env.DATABASE_URL, pool: { min: 2, max: 10 } }, api: { key: process.env.API_KEY, timeout: 30000 } } const sandbox = await Sandbox.create({ envVars: { CONFIG: JSON.stringify(config) } }) // In sandbox code: // const config = JSON.parse(process.env.CONFIG)

Environment-Specific Configs

const envConfigs = { development: { DEBUG: 'true', LOG_LEVEL: 'debug', API_URL: 'http://localhost:3000' }, production: { DEBUG: 'false', LOG_LEVEL: 'error', API_URL: 'https://api.production.com' } } const env = process.env.NODE_ENV || 'development' const sandbox = await Sandbox.create({ envVars: envConfigs[env] })

Troubleshooting

Variable Not Available

If environment variables aren’t accessible in your code:

  1. Check timing: Set variables before running code
  2. Verify syntax: Use correct syntax for your language
  3. Check scope: Some shells require export
// Ensure export for shell commands await sandbox.commands.run('export MY_VAR=value && echo $MY_VAR')

Special Characters

Escape special characters properly:

const sandbox = await Sandbox.create({ envVars: { PASSWORD: 'pass"word', // Quotes in value PATH_VAR: '/path/with spaces' // Spaces in value } })