> ## 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.

# Connecting

> Learn how to connect to running HopX sandboxes and establish communication channels. Connect to existing sandboxes by ID, retrieve sandbox information, and resume work with previously created sandboxes. Essential for managing long-running sandboxes and resuming interrupted sessions. Includes Python and JavaScript SDK examples and REST API endpoints.

Connect to sandboxes that are already running. This is useful when you need to reconnect to a sandbox after your application restarts, or when working with sandboxes created by other processes.

## Prerequisites

Before you begin, make sure you have:

* **Existing sandbox** - A sandbox that was previously created (see [Creating Sandboxes](https://docs.hopx.ai/core-concepts/sandboxes/creating.md))
* **Sandbox ID** - The ID of the sandbox you want to connect to
* **API key** - Your HopX API key configured

## Overview

The `connect()` method allows you to reconnect to an existing sandbox by its ID. When connecting:

* **If sandbox is paused** → Automatically resumes it and refreshes JWT token
* **If sandbox is stopped** → Raises an error (cannot connect to stopped sandbox)
* **If sandbox is running** → Refreshes JWT token for agent authentication
* **JWT token** → Automatically refreshed and stored for agent operations

> [!WARNING]
>
> You cannot connect to a stopped sandbox. Use `sandbox.start()` first, or create a new sandbox.

## Basic Connection

Connect to an existing sandbox by ID:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Connect to existing sandbox
> sandbox = Sandbox.connect("1763309903rt5vs4lm")
>
> # Get current information
> info = sandbox.get_info()
> print(f"Status: {info.status}")
> print(f"URL: {info.public_host}")
> ```
>
> **Expected Output:**
>
> ```
> Status: running
> URL: https://1763309903rt5vs4lm.hopx.dev
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Connect to existing sandbox
> const sandbox = await Sandbox.connect('1763309903rt5vs4lm');
>
> // Get current information
> const info = await sandbox.getInfo();
> console.log(`Status: ${info.status}`);
> console.log(`URL: ${info.publicHost}`);
> ```
>
> **Expected Output:**
>
> ```
> Status: running
> URL: https://1763309903rt5vs4lm.hopx.dev
> ```

## Finding Sandbox IDs

You can find sandbox IDs by listing your sandboxes:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # List sandboxes to find IDs
> sandboxes = Sandbox.list(status="running")
> for sandbox in sandboxes:
>     info = sandbox.get_info()
>     print(f"ID: {sandbox.sandbox_id}, Status: {info.status}")
>
> # Connect to the first one
> if sandboxes:
>     sandbox = Sandbox.connect(sandboxes[0].sandbox_id)
>     print(f"Connected to: {sandbox.sandbox_id}")
> ```
>
> **Expected Output:**
>
> ```
> ID: 1763309903rt5vs4lm, Status: running
> ID: 1763309904rt5vs4ln, Status: running
> Connected to: 1763309903rt5vs4lm
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // List sandboxes to find IDs
> const sandboxes = await Sandbox.list({ status: 'running' });
> for (const sandbox of sandboxes) {
>   const info = await sandbox.getInfo();
>   console.log(`ID: ${sandbox.sandboxId}, Status: ${info.status}`);
> }
>
> // Connect to the first one
> if (sandboxes.length > 0) {
>   const sandbox = await Sandbox.connect(sandboxes[0].sandboxId);
>   console.log(`Connected to: ${sandbox.sandboxId}`);
> }
> ```

## Handling Different States

The `connect()` method handles different sandbox states automatically:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
> from hopx_ai.errors import HopxError
>
> try:
>     sandbox = Sandbox.connect("sandbox_id")
>     info = sandbox.get_info()
>
>     if info.status == "paused":
>         print("Sandbox was paused - automatically resumed")
>     elif info.status == "running":
>         print("Sandbox is running - ready to use")
>
> except HopxError as e:
>     if "stopped" in str(e).lower():
>         print("Cannot connect to stopped sandbox")
>         print("Use sandbox.start() first, or create a new sandbox")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> try {
>   const sandbox = await Sandbox.connect('sandbox_id');
>   const info = await sandbox.getInfo();
>
>   if (info.status === 'paused') {
>     console.log('Sandbox was paused - automatically resumed');
>   } else if (info.status === 'running') {
>     console.log('Sandbox is running - ready to use');
>   }
> } catch (error) {
>   if (error.message.includes('stopped')) {
>     console.error('Cannot connect to stopped sandbox');
>     console.error('Use sandbox.start() first, or create a new sandbox');
>   }
> }
> ```

## Complete Workflow Example

Here's a complete example showing the connect workflow:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Step 1: List running sandboxes
> sandboxes = Sandbox.list(status="running")
> print(f"Found {len(sandboxes)} running sandboxes")
>
> # Step 2: Connect to a specific sandbox
> if sandboxes:
>     sandbox_id = sandboxes[0].sandbox_id
>     print(f"\nConnecting to: {sandbox_id}")
>
>     sandbox = Sandbox.connect(sandbox_id)
>     info = sandbox.get_info()
>
>     print(f"✅ Connected successfully")
>     print(f"   Status: {info.status}")
>     print(f"   Template: {info.template_name}")
>     print(f"   URL: {info.public_host}")
>
>     # Step 3: Use the sandbox
>     result = sandbox.run_code('print("Reconnected!")')
>     print(f"   Output: {result.stdout}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Step 1: List running sandboxes
> const sandboxes = await Sandbox.list({ status: 'running' });
> console.log(`Found ${sandboxes.length} running sandboxes`);
>
> // Step 2: Connect to a specific sandbox
> if (sandboxes.length > 0) {
>   const sandboxId = sandboxes[0].sandboxId;
>   console.log(`\nConnecting to: ${sandboxId}`);
>
>   const sandbox = await Sandbox.connect(sandboxId);
>   const info = await sandbox.getInfo();
>
>   console.log('✅ Connected successfully');
>   console.log(`   Status: ${info.status}`);
>   console.log(`   Template: ${info.templateName}`);
>   console.log(`   URL: ${info.publicHost}`);
>
>   // Step 3: Use the sandbox
>   const result = await sandbox.runCode('print("Reconnected!")');
>   console.log(`   Output: ${result.stdout}`);
> }
> ```

## Error Handling

Handle connection errors appropriately:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
> from hopx_ai.errors import NotFoundError, HopxError
>
> try:
>     sandbox = Sandbox.connect("invalid_id")
> except NotFoundError:
>     print("Sandbox not found")
> except HopxError as e:
>     if "stopped" in str(e).lower():
>         print("Sandbox is stopped - cannot connect")
>         print("Start it first: sandbox.start()")
>     else:
>         print(f"Connection error: {e}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
> import { NotFoundError, HopxError } from '@hopx-ai/sdk';
>
> try {
>   const sandbox = await Sandbox.connect('invalid_id');
> } catch (error) {
>   if (error instanceof NotFoundError) {
>     console.error('Sandbox not found');
>   } else if (error instanceof HopxError) {
>     if (error.message.includes('stopped')) {
>       console.error('Sandbox is stopped - cannot connect');
>       console.error('Start it first: sandbox.start()');
>     } else {
>       console.error(`Connection error: ${error.message}`);
>     }
>   }
> }
> ```

## Use Cases

### Reconnecting After Application Restart

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
> import os
>
> # Store sandbox ID (e.g., in environment variable or database)
> sandbox_id = os.getenv("SANDBOX_ID")
>
> if sandbox_id:
>     # Reconnect to existing sandbox
>     sandbox = Sandbox.connect(sandbox_id)
>     print(f"Reconnected to: {sandbox.sandbox_id}")
> else:
>     # Create new sandbox
>     sandbox = Sandbox.create(template="code-interpreter")
>     print(f"Created new: {sandbox.sandbox_id}")
>     # Store ID for later
>     os.environ["SANDBOX_ID"] = sandbox.sandbox_id
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Store sandbox ID (e.g., in environment variable or database)
> const sandboxId = process.env.SANDBOX_ID;
>
> if (sandboxId) {
>   // Reconnect to existing sandbox
>   const sandbox = await Sandbox.connect(sandboxId);
>   console.log(`Reconnected to: ${sandbox.sandboxId}`);
> } else {
>   // Create new sandbox
>   const sandbox = await Sandbox.create({ template: 'code-interpreter' });
>   console.log(`Created new: ${sandbox.sandboxId}`);
>   // Store ID for later
>   process.env.SANDBOX_ID = sandbox.sandboxId;
> }
> ```

### Working with Shared Sandboxes

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Multiple processes can connect to the same sandbox
> # Process 1: Creates sandbox
> sandbox1 = Sandbox.create(template="code-interpreter")
> sandbox_id = sandbox1.sandbox_id
> print(f"Created: {sandbox_id}")
>
> # Process 2: Connects to same sandbox
> sandbox2 = Sandbox.connect(sandbox_id)
> print(f"Connected: {sandbox2.sandbox_id}")
>
> # Both can use the same sandbox
> result1 = sandbox1.run_code('x = 1')
> result2 = sandbox2.run_code('print(x)')  # Can access shared state
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Multiple processes can connect to the same sandbox
> // Process 1: Creates sandbox
> const sandbox1 = await Sandbox.create({ template: 'code-interpreter' });
> const sandboxId = sandbox1.sandboxId;
> console.log(`Created: ${sandboxId}`);
>
> // Process 2: Connects to same sandbox
> const sandbox2 = await Sandbox.connect(sandboxId);
> console.log(`Connected: ${sandbox2.sandboxId}`);
>
> // Both can use the same sandbox
> await sandbox1.runCode('x = 1');
> await sandbox2.runCode('print(x)');  // Can access shared state
> ```

## JWT Token Management

When you connect to a sandbox, the SDK automatically:

1. **Refreshes the JWT token** for agent authentication
2. **Stores the token** for subsequent agent operations
3. **Handles token expiration** automatically

You don't need to manage tokens manually - the SDK handles this for you.

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Connect - token is automatically refreshed
> sandbox = Sandbox.connect("sandbox_id")
>
> # Token is stored and used automatically for agent calls
> result = sandbox.run_code('print("Hello")')  # Uses stored token
>
> # Manually refresh if needed
> sandbox.refresh_token()
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Connect - token is automatically refreshed
> const sandbox = await Sandbox.connect('sandbox_id');
>
> // Token is stored and used automatically for agent calls
> const result = await sandbox.runCode('print("Hello")');  // Uses stored token
>
> // Manually refresh if needed
> await sandbox.refreshToken();
> ```

## Implementation

* **SDK**: [Sandbox.connect()](https://docs.hopx.ai/sdk/python/sandbox.md#connect) - Python SDK method
* **[CLI](https://docs.hopx.ai/cli/introduction.md)** - Command-line interface
* **SDK**: [sandbox.get\_info()](https://docs.hopx.ai/sdk/python/sandbox.md#get_info) - Python SDK method
* **API**: [GET /v1/sandboxes/:id](https://docs.hopx.ai/api/control-plane/get-sandbox.md) - Control Plane API endpoint

## Related

* **[Listing Sandboxes](https://docs.hopx.ai/core-concepts/sandboxes/listing.md)** - Find sandboxes to connect to
* **[Creating Sandboxes](https://docs.hopx.ai/core-concepts/sandboxes/creating.md)** - Create new sandboxes
* **[Managing Sandbox State](https://docs.hopx.ai/core-concepts/sandboxes/managing-state.md)** - Control sandbox lifecycle

## Next Steps

* Learn about [Managing State](https://docs.hopx.ai/core-concepts/sandboxes/managing-state.md) to start/stop/pause/resume sandboxes
* Explore [Timeout Management](https://docs.hopx.ai/core-concepts/sandboxes/timeout.md) for connected sandboxes
* Review [Creating Sandboxes](https://docs.hopx.ai/core-concepts/sandboxes/creating.md) for creating new sandboxes


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.