> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Clearing

> Remove environment variables from sandboxes. Clear all environment variables to reset configuration, remove sensitive data, or start with a clean environment. Learn how to clear variables using Python and JavaScript SDKs or REST API. Includes examples for cleanup and security best practices.

Remove environment variables from your sandbox. You can delete individual variables or clear all custom variables at once.

## Overview

Clearing environment variables is useful for:

* Removing sensitive data
* Resetting configuration
* Cleaning up temporary variables
* Preparing sandbox for reuse

<Note>
  Deleting individual variables preserves other variables. System variables (like `PATH`, `HOME`) are typically preserved and cannot be deleted.
</Note>

## Delete Single Variable

Delete a specific environment variable:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set some variables
    sandbox.env.set_all({
        "API_KEY": "sk-123",
        "DEBUG": "true",
        "TEMP_TOKEN": "temp-xyz"
    })

    # Delete a single variable
    sandbox.env.delete("TEMP_TOKEN")
    print("TEMP_TOKEN deleted")

    # Verify deletion
    env = sandbox.env.get_all()
    print(f"TEMP_TOKEN exists: {'TEMP_TOKEN' in env}")
    print(f"API_KEY still exists: {'API_KEY' in env}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set some variables
    await sandbox.env.setAll({
      API_KEY: 'sk-123',
      DEBUG: 'true',
      TEMP_TOKEN: 'temp-xyz'
    });

    // Delete a single variable
    await sandbox.env.delete('TEMP_TOKEN');
    console.log('TEMP_TOKEN deleted');

    // Verify deletion
    const env = await sandbox.env.getAll();
    console.log(`TEMP_TOKEN exists: ${'TEMP_TOKEN' in env}`);
    console.log(`API_KEY still exists: ${'API_KEY' in env}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Delete Multiple Variables

Delete multiple variables one by one:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set multiple variables
    sandbox.env.set_all({
        "API_KEY": "sk-123",
        "DATABASE_URL": "postgres://localhost/db",
        "DEBUG": "true",
        "TEMP_TOKEN": "temp-xyz",
        "OLD_CONFIG": "deprecated"
    })

    # Delete multiple variables
    variables_to_delete = ["TEMP_TOKEN", "OLD_CONFIG", "DEBUG"]
    for var in variables_to_delete:
        sandbox.env.delete(var)
        print(f"Deleted: {var}")

    # Verify remaining variables
    env = sandbox.env.get_all()
    print(f"\nRemaining variables: {list(env.keys())}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set multiple variables
    await sandbox.env.setAll({
      API_KEY: 'sk-123',
      DATABASE_URL: 'postgres://localhost/db',
      DEBUG: 'true',
      TEMP_TOKEN: 'temp-xyz',
      OLD_CONFIG: 'deprecated'
    });

    // Delete multiple variables
    const variablesToDelete = ['TEMP_TOKEN', 'OLD_CONFIG', 'DEBUG'];
    for (const varName of variablesToDelete) {
      await sandbox.env.delete(varName);
      console.log(`Deleted: ${varName}`);
    }

    // Verify remaining variables
    const env = await sandbox.env.getAll();
    console.log(`\nRemaining variables: ${Object.keys(env)}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Clear All Custom Variables

Clear all custom environment variables:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set custom variables
    sandbox.env.set_all({
        "API_KEY": "sk-123",
        "DATABASE_URL": "postgres://localhost/db",
        "DEBUG": "true"
    })

    # Get current variables
    before = sandbox.env.get_all()
    print(f"Variables before: {len(before)}")

    # Clear all custom variables (set empty dict)
    sandbox.env.set_all({})

    # Get variables after clearing
    after = sandbox.env.get_all()
    print(f"Variables after: {len(after)}")

    # System variables may still exist
    system_vars = ['PATH', 'HOME', 'USER', 'SHELL']
    remaining = [v for v in after.keys() if v in system_vars]
    print(f"System variables preserved: {remaining}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set custom variables
    await sandbox.env.setAll({
      API_KEY: 'sk-123',
      DATABASE_URL: 'postgres://localhost/db',
      DEBUG: 'true'
    });

    // Get current variables
    const before = await sandbox.env.getAll();
    console.log(`Variables before: ${Object.keys(before).length}`);

    // Clear all custom variables (set empty dict)
    await sandbox.env.setAll({});

    // Get variables after clearing
    const after = await sandbox.env.getAll();
    console.log(`Variables after: ${Object.keys(after).length}`);

    // System variables may still exist
    const systemVars = ['PATH', 'HOME', 'USER', 'SHELL'];
    const remaining = Object.keys(after).filter(v => systemVars.includes(v));
    console.log(`System variables preserved: ${remaining}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Clean Up Temporary Variables

Remove temporary or sensitive variables:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set up environment with temporary variables
    sandbox.env.set_all({
        "API_KEY": "sk-prod-xyz",
        "DATABASE_URL": "postgres://localhost/db",
        "TEMP_TOKEN": "temp-abc123",
        "SESSION_ID": "session-xyz",
        "DEBUG": "true"
    })

    # Clean up temporary variables
    temp_vars = ["TEMP_TOKEN", "SESSION_ID"]
    for var in temp_vars:
        sandbox.env.delete(var)
        print(f"Cleaned up: {var}")

    # Verify cleanup
    env = sandbox.env.get_all()
    print(f"\nRemaining variables: {list(env.keys())}")

    # Production variables should still exist
    print(f"API_KEY exists: {'API_KEY' in env}")
    print(f"DATABASE_URL exists: {'DATABASE_URL' in env}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set up environment with temporary variables
    await sandbox.env.setAll({
      API_KEY: 'sk-prod-xyz',
      DATABASE_URL: 'postgres://localhost/db',
      TEMP_TOKEN: 'temp-abc123',
      SESSION_ID: 'session-xyz',
      DEBUG: 'true'
    });

    // Clean up temporary variables
    const tempVars = ['TEMP_TOKEN', 'SESSION_ID'];
    for (const varName of tempVars) {
      await sandbox.env.delete(varName);
      console.log(`Cleaned up: ${varName}`);
    }

    // Verify cleanup
    const env = await sandbox.env.getAll();
    console.log(`\nRemaining variables: ${Object.keys(env)}`);

    // Production variables should still exist
    console.log(`API_KEY exists: ${'API_KEY' in env}`);
    console.log(`DATABASE_URL exists: ${'DATABASE_URL' in env}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a complete example showing environment variable cleanup:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set up complete environment
    print("🔧 Setting up environment...")
    sandbox.env.set_all({
        "API_KEY": "sk-prod-xyz",
        "DATABASE_URL": "postgres://localhost/prod",
        "REDIS_URL": "redis://localhost:6379",
        "TEMP_TOKEN": "temp-abc123",
        "SESSION_ID": "session-xyz",
        "DEBUG": "true",
        "LOG_LEVEL": "info"
    })

    env = sandbox.env.get_all()
    print(f"✅ Environment set up with {len(env)} variables\n")

    # Use environment in code
    print("💻 Using environment in code...")
    result = sandbox.run_code('''
    import os
    print(f"API key: {os.getenv('API_KEY', 'not set')[:10]}...")
    print(f"Database: {os.getenv('DATABASE_URL', 'not set')}")
    print(f"Temp Token: {os.getenv('TEMP_TOKEN', 'not set')}")
    ''')
    print(result.stdout)

    # Clean up temporary variables
    print("\n🧹 Cleaning up temporary variables...")
    temp_vars = ["TEMP_TOKEN", "SESSION_ID"]
    for var in temp_vars:
        sandbox.env.delete(var)
        print(f"  ✅ Deleted: {var}")

    # Verify cleanup
    print("\n📋 Final environment:")
    final_env = sandbox.env.get_all()
    for key in sorted(final_env.keys()):
        if key not in ['PATH', 'HOME', 'USER', 'SHELL', 'PWD']:
            if any(sensitive in key.upper() for sensitive in ['KEY', 'SECRET', 'PASSWORD']):
                print(f"  {key}=***MASKED***")
            else:
                print(f"  {key}={final_env[key]}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set up complete environment
    console.log('🔧 Setting up environment...');
    await sandbox.env.setAll({
      API_KEY: 'sk-prod-xyz',
      DATABASE_URL: 'postgres://localhost/prod',
      REDIS_URL: 'redis://localhost:6379',
      TEMP_TOKEN: 'temp-abc123',
      SESSION_ID: 'session-xyz',
      DEBUG: 'true',
      LOG_LEVEL: 'info'
    });

    const env = await sandbox.env.getAll();
    console.log(`✅ Environment set up with ${Object.keys(env).length} variables\n`);

    // Use environment in code
    console.log('💻 Using environment in code...');
    const result = await sandbox.runCode(`
    import os
    print(f"API key: {os.getenv('API_KEY', 'not set')[:10]}...")
    print(f"Database: {os.getenv('DATABASE_URL', 'not set')}")
    print(f"Temp Token: {os.getenv('TEMP_TOKEN', 'not set')}")
    `);
    console.log(result.stdout);

    // Clean up temporary variables
    console.log('\n🧹 Cleaning up temporary variables...');
    const tempVars = ['TEMP_TOKEN', 'SESSION_ID'];
    for (const varName of tempVars) {
      await sandbox.env.delete(varName);
      console.log(`  ✅ Deleted: ${varName}`);
    }

    // Verify cleanup
    console.log('\n📋 Final environment:');
    const finalEnv = await sandbox.env.getAll();
    for (const key of Object.keys(finalEnv).sort()) {
      if (!['PATH', 'HOME', 'USER', 'SHELL', 'PWD'].includes(key)) {
        const isSensitive = ['KEY', 'SECRET', 'PASSWORD'].some(
          s => key.toUpperCase().includes(s)
        );
        if (isSensitive) {
          console.log(`  ${key}=***MASKED***`);
        } else {
          console.log(`  ${key}=${finalEnv[key]}`);
        }
      }
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Best Practices

<Steps>
  <Step title="1. Delete Individual Variables">
    Use `delete(key)` to remove specific variables while preserving others.
  </Step>

  <Step title="2. Clean Up Temporaries">
    Regularly delete temporary variables (tokens, session IDs) to reduce security risk.
  </Step>

  <Step title="3. Clear Before Reuse">
    Clear all custom variables before reusing a sandbox for a different purpose.
  </Step>

  <Step title="4. Verify Deletion">
    Always verify variables are deleted using `get_all()` or `get()` after deletion.
  </Step>

  <Step title="5. Preserve System Variables">
    System variables (PATH, HOME, etc.) are typically preserved and cannot be deleted.
  </Step>
</Steps>

## Related

* **[Getting Environment Variables](/core-concepts/environment/getting)** - Retrieve environment variables
* **[Setting Environment Variables](/core-concepts/environment/setting)** - Set or replace variables
* **[Updating Environment Variables](/core-concepts/environment/updating)** - Update variables without replacing
* **SDK**: [sandbox.env.clear()](/sdk/python/environment-variables#clear) - Python SDK method
* **API**: [DELETE /env](/api/vm-agent/clear-env) - VM Agent API endpoint
* [CLI Environment Variables](/cli/commands/env) - Environment variables from CLI

## Next Steps

* Learn about [Getting Environment Variables](/core-concepts/environment/getting) to retrieve variables
* Explore [Setting Environment Variables](/core-concepts/environment/setting) to configure your sandbox
* Review [Updating Environment Variables](/core-concepts/environment/updating) to modify existing variables
