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

# Hooks

> Set the state of the app before, during, and after your flows run via scripts, API calls, and app launch configurations

Hooks serve as a bridge between your backend or server-side scripts and the BugRadar testing environment. They allow you to communicate data, set the state of the app, set the state of a user, etc.

They are short programs that run in sandboxed environments during the testing process. They can be added to suites and flows, and any output from them (print statements, console.log, echo) is visible to the agent.

A few common examples:

1. Resetting a user's onboarding in the backend via JS code
2. Generating a random email to be used by the BugRadar agent via Python code
3. Returning a magic link or OTP code from your server for BugRadar to use in the flow via a cURL request
4. Mocking audio or video input by hitting an endpoint on your server via TypeScript code

Possibilities are endless and usually the more hooks the better, as it adds a level of determinism to the state of the test!

**Execution Positions**

There are three hook execution positions:

1. **Setup Hooks**: Run before suites or flows start. Great for providing context.
2. **Runtime Hooks**: Run as an action during the flow — added directly into flow instructions, allows real-time backend interaction during testing
3. **Teardown Hooks**: Run at the very end of suites and flows. Helpful to clean up testing states

## Hook Types

Hooks allow you to configure your test environment in three ways:

1. **Scripts**: Python, JavaScript, TypeScript, or Bash scripts that run server-side
2. **cURL Requests**: Backend API calls for simple HTTP requests
3. **App Launch Configuration**: Configure how your mobile app launches (feature flags, environment settings) - *mobile only*

### Scripts

Server-side scripts that execute in a secure sandbox environment. Choose from Python, JavaScript, TypeScript, or Bash depending on your needs.

> [!NOTE]
>
> If your hook calls a firewalled API, see [Network allowlist](/docs/network-allowlist.md) for the IPs to allow.

> [!WARNING]
>
> Scripts run in a sandboxed environment and **cannot use external libraries**. Use only built-in/standard libraries (e.g., `urllib` instead of `requests` for Python, built-in `fetch` for JavaScript/TypeScript).

**Common use cases:**

* Complex multi-step API operations
* Data processing and transformation
* Conditional logic based on API responses
* Generating dynamic test data
* Chaining multiple API calls with error handling

#### Generating Random Values

Use cryptographically secure randomness from the language standard library when generating unique test data.

**JavaScript / TypeScript:**

```javascript theme={null}
const crypto = require('crypto');

const suffix = crypto.randomInt(1, 100000001);
const email = `test-${suffix}@example.com`;
const uniqueId = crypto.randomUUID();

console.log(email);
```

**Python:**

```python theme={null}
import secrets
import string
import uuid

suffix = ''.join(secrets.choice(string.ascii_lowercase) for _ in range(8))
email = f"test-{suffix}@example.com"
unique_id = str(uuid.uuid4())

print(email)
```

> [!TIP]
>
> If your flow types, taps or checks a printed value that changes every run, each run executes live. Export the value instead so cached runs can use it. See [Hooks and Run Caching](#hooks-and-run-caching).

### cURL Requests

Backend API calls that execute before (setup) or after (teardown) a flow runs. Best for simple, single HTTP requests.

**Common use cases:**

* Create test user accounts via your API
* Reset database state between flows
* Generate auth tokens or session data
* Configure backend feature flags
* Clean up test data after flows complete

### App Launch Configuration (Mobile Only)

Configure values that are passed to your mobile app when it launches. These values are available to your app code as environment variables (iOS) or intent extras (Android).

> [!NOTE]
>
> App Launch Configuration is only available for mobile apps (iOS and Android). For web testing, use Scripts or cURL Requests to configure your test environment.

**Common use cases:**

* Override feature flag values for specific test scenarios
* Set test environment parameters (staging vs. production mode)
* Configure API timeouts or retry behavior
* Enable debug modes or verbose logging
* Set experiment variants for A/B testing

## Creating a Hook

1. Navigate to **[Hooks](https://usebugradar.com/hooks)** in the sidebar
2. Click **Create Hook**
3. Type a hook name at the top of the dialog (e.g., "Create Test User" or "Generate Auth Token") and, optionally, a description under it
4. Pick the hook type from the **Language** menu above the editor. New hooks start on **Auto-detect**, which picks the language from your script as you type or paste. If it can't tell, or the script is in a language hooks don't run (such as Rust or Go), it asks you to pick a language before you can create the hook. Choosing a language yourself turns Auto-detect off:
   * **Python**: For complex logic and data processing
   * **JavaScript**: For Node.js-based operations
   * **TypeScript**: For type-safe Node.js operations
   * **Bash**: For shell script operations
   * **cURL Request**: For simple HTTP API calls
   * **App Launch Configuration**: For mobile app settings (mobile only)
5. Enter your script or configuration:

### For Python:

```python theme={null}
import urllib.request
import json
import os

data = json.dumps({
    "email": os.environ.get('TEST_EMAIL'),
    "password": os.environ.get('TEST_PASSWORD')
}).encode('utf-8')

req = urllib.request.Request(
    f"{os.environ.get('API_URL')}/auth/login",
    data=data,
    headers={'Content-Type': 'application/json'}
)

with urllib.request.urlopen(req) as response:
    result = json.loads(response.read().decode('utf-8'))

print(f"Logged in as user: {result['userId']}")

# Export token for subsequent hooks
with open('/tmp/BugRadar.env', 'w') as f:
    f.write(f"AUTH_TOKEN={result['token']}\n")
```

### For JavaScript:

```javascript theme={null}
const response = await fetch(`${process.env.API_URL}/auth/login`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    email: process.env.TEST_EMAIL,
    password: process.env.TEST_PASSWORD
  })
});

const data = await response.json();
console.log(`Logged in as user: ${data.userId}`);

// Export token for subsequent hooks
const fs = require('fs');
fs.writeFileSync('/tmp/BugRadar.env', `AUTH_TOKEN=${data.token}\n`);
```

### For TypeScript:

```typescript theme={null}
const response = await fetch(`${process.env.API_URL}/auth/login`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    email: process.env.TEST_EMAIL,
    password: process.env.TEST_PASSWORD
  })
});

interface LoginResponse {
  token: string;
  userId: string;
}

const data: LoginResponse = await response.json();
console.log(`Logged in as user: ${data.userId}`);

// Export token for subsequent hooks
const fs = require('fs');
fs.writeFileSync('/tmp/BugRadar.env', `AUTH_TOKEN=${data.token}\n`);
```

### For Bash:

```bash theme={null}
RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"${TEST_EMAIL}\",\"password\":\"${TEST_PASSWORD}\"}")

TOKEN=$(echo $RESPONSE | jq -r '.token')
USER_ID=$(echo $RESPONSE | jq -r '.userId')

echo "Logged in as user: $USER_ID"

# Export token for subsequent hooks (append with >>)
echo "AUTH_TOKEN=$TOKEN" >> /tmp/BugRadar.env
```

### For cURL Requests:

```bash theme={null}
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com","password":"TestPass123"}'
```

### For App Launch Configuration:

```json theme={null}
{
  "testEnvironment": "staging",
  "featureFlags": {
    "newCheckoutFlow": "enabled",
    "darkMode": true
  },
  "apiTimeout": 30
}
```

6. Click **Create hook**

> [!TIP]
>
> Any output from your hooks (print statements, console.log, echo) is passed to the agent as additional context. Use this to provide helpful information about what the hook did!

## Testing Hooks

Before attaching hooks to flows, you can test them to verify they work correctly.

Dashboard tests use your signed-in session. You do not need to create or paste an BugRadar API key.

1. Open the hook you want to test
2. Click the **Test Hook** button
3. The hook will execute with a **1-minute timeout**
4. View the output to verify success or debug issues

You can also test changes before saving them: while editing a hook, click **Run** (or press ⌘↵). It runs the script as currently written and shows the output under the editor, and nothing is saved until you click **Save changes**. Run uses the hook's saved language, so if you switch the language, save first. A new hook has to be created before you can run it.

**What to check:**

* Script executes without errors
* API calls return expected responses
* Environment variables are being read correctly
* Exported values (if any) are formatted correctly

> [!TIP]
>
> Always test hooks independently before attaching them to flows. This helps isolate issues and speeds up debugging.

## Using Hooks

[Adding Hooks to Flows](https://www.veed.io/embed/720a1987-f583-42c1-99df-1dd04b9f13d7?watermark=0\&color=default\&sharing=0\&title=1)

### Setup & Teardown Hooks

**Attaching Setup & Teardown Hooks**

1. Create a new suite or flow or click **Edit** on an existing one
2. Expand the **Advanced** section
3. Expand the **Setup Hooks** or **Teardown Hooks** section
4. Click the **Add a setup hook...** or **Add a teardown hook...** button
5. Select the hook you want to attach

Hooks attached to a suite are also shown read-only when you expand the suite on the Flows page, so you can see what runs before and after the suite without opening the editor.

### Runtime Hooks

You can execute hooks as actions during flow execution by using the syntax `${hooks:Hook Name}` in the flow instructions.

**Example:**

```
Tap the login button, then ${hooks:Create Test User}, then verify the user appears
```

When the agent encounters `${hooks:Hook Name}`, it will:

1. Look up the hook by name (an exact match, including case and spaces)
2. Execute the hook script
3. Continue with the rest of the action

On a run pinned to a commit — an API run that passes `ref` and `repo_full_name`, `BugRadar run --ref`, or BugRadar's own pull-request test runs — tests stored in your repo use the hook file at that commit whose [display name](/docs/code-managed-files.md#hooks-as-files) matches, then a hook stored in BugRadar. A name that doesn't resolve never stops the run, wherever it's called from: the run starts, and the call fails with the reason only if the test makes it. That includes a name that matches no hook, matches more than one hook file, or matches a file that can't be read; BugRadar doesn't fall back to the stored copy of a broken file. Runs from your working copy (`BugRadar run --local` or `--cloud`) use the hook files in it. A `--local` run uploads only the hook files your tests or suites call, so a name called only from your app's instructions uses the stored hook. A CI run that sends a branch build's `app_build_id` without `ref` [runs at the build's commit](/docs/api-runs.md#branch-builds-run-at-their-commit) and uses its hook files, except in the cases listed there. Other runs use hooks stored in BugRadar.

This is useful for:

* Creating data mid-flow (e.g., "add 5 items to cart, then `${hooks:Create Dummy Discount Code}`")
* Triggering backend events at specific points
* Resetting state between actions

> [!TIP]
>
> **Runtime Hooks** execute synchronously - the flow waits for the hook to complete before continuing.

### Execution Order

1. Setup Hooks execute (if configured)
2. Flow runs on app start
3. Agent runs actions and any Runtime Hooks (if configured)
4. Flow run stops
5. Teardown Hooks execute (if configured)

Steps 1 and 2 overlap when a setup hook is an [App Launch Configuration](#when-it-runs) — the app starts at that hook's position.

## Environment Variables in Hooks

### For cURL Requests

Reference environment variables using `${env:VARIABLE_NAME}` syntax:

```bash theme={null}
curl -X POST ${env:API_URL}/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"${env:TEST_EMAIL}","password":"${env:TEST_PASSWORD}"}'
```

**Environment variables (in Settings → Environments):**

* `API_URL` = `https://staging-api.example.com`
* `TEST_EMAIL` = `test@staging.com`
* `TEST_PASSWORD` = `SecurePass123`

**Executed command:**

```bash theme={null}
curl -X POST https://staging-api.example.com/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"test@staging.com","password":"SecurePass123"}'
```

### For Scripts (Python, JavaScript, TypeScript, Bash)

Environment variables are automatically injected into the script environment. Access them using your language's standard method:

**Python:**

```python theme={null}
import os

api_url = os.environ.get('API_URL')
test_email = os.getenv('TEST_EMAIL')
```

**JavaScript / TypeScript:**

```javascript theme={null}
const apiUrl = process.env.API_URL;
const testEmail = process.env.TEST_EMAIL;
```

**Bash:**

```bash theme={null}
echo $API_URL
echo ${TEST_EMAIL}
```

[Learn more about environment variables →](/docs/environments.md)

> [!TIP]
>
> Click **Insert Environment Variable** when creating/editing a hook to browse and select from your available environment variables.

### Run Metadata

Every hook in a run can read details about that run. This is useful for linking your own logs or error reports back to the BugRadar run.

| Variable | Value | Available in |
| - | - | - |
| `BugRadar_FLOW_RUN_ID` | ID of the flow run | Flow hooks |
| `BugRadar_FLOW_ID` | ID of the flow | Flow hooks |
| `BugRadar_RUN_GROUP_ID` | ID of the run group, also set when a flow runs on its own | Flow and suite hooks |
| `BugRadar_RUN_URL` | Link to the flow run, or to the run group in suite hooks | Flow and suite hooks |
| `BugRadar_RUN_GROUP_URL` | Link to the run group | Flow and suite hooks |
| `BugRadar_BATCH_ID` | ID of the batch the run was started in | Flow and suite hooks |
| `BugRadar_BATCH_URL` | Link to the batch | Flow and suite hooks |

Read them like any other environment variable, or use `${env:BugRadar_FLOW_RUN_ID}` in cURL and App Launch Configuration hooks. They can't be overwritten and aren't set in **Test Hook**.

#### Example: Tagging Errors in Your App

Add an App Launch Configuration setup hook to the flow:

```json theme={null}
{
  "BugRadarRunId": "${env:BugRadar_FLOW_RUN_ID}",
  "BugRadarRunUrl": "${env:BugRadar_RUN_URL}"
}
```

Read `BugRadarRunId` when your app starts and add it as a tag in your error tracker, for example `Sentry.setTag("BugRadar_run_id", BugRadarRunId)`.

### Time Zone

Scripts run with `TZ=America/Los_Angeles`, the same zone BugRadar's browsers, emulators and simulators use on a run without a location. On a run with a [location](/docs/run-location.md), the device uses the exit IP's zone, but scripts still use US Pacific time. To use another zone, add an environment variable named `TZ`; your value replaces the default.

## Sharing Data Between Hooks

Hooks can pass data to subsequent hooks in the same suite. This is useful for scenarios like:

* Generating an auth token in a setup hook and using it in a runtime hook
* Creating a test user and passing the user ID to a teardown hook for cleanup
* Sharing credentials across multiple flows in a suite

### How It Works

1. In your hook, write values to `/tmp/BugRadar.env` in `KEY=VALUE` format
2. Subsequent hooks can access these values as environment variables
3. Values persist for all subsequent hooks in the suite (across all flows)

### Key Naming Rules

When exporting values, keys must follow these rules:

| Rule | Valid | Invalid |
| - | - | - |
| Alphanumeric + underscore only | `AUTH_TOKEN`, `API_KEY`, `user_id` | `API-KEY`, `user.id` |
| Cannot start with a number | `TOKEN_123`, `_INTERNAL` | `123_TOKEN`, `1ST_KEY` |

### Example: Passing a Token Between Hooks

**Setup Hook (Python) - Creates token:**

```python theme={null}
import urllib.request
import json
import os

data = json.dumps({
    "email": "test@example.com",
    "password": "secret"
}).encode('utf-8')

req = urllib.request.Request(
    f"{os.environ.get('API_URL')}/auth/login",
    data=data,
    headers={'Content-Type': 'application/json'}
)

with urllib.request.urlopen(req) as response:
    result = json.loads(response.read().decode('utf-8'))

token = result['token']
user_id = result['userId']

# Export for subsequent hooks
with open('/tmp/BugRadar.env', 'w') as f:
    f.write(f"AUTH_TOKEN={token}\n")
    f.write(f"TEST_USER_ID={user_id}\n")

print(f"Created session for user {user_id}")
```

**Runtime Hook (cURL) - Uses the token:**

```bash theme={null}
curl -X POST ${env:API_URL}/cart/add \
  -H "Authorization: Bearer ${env:AUTH_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"productId": "12345", "quantity": 1}'
```

**Teardown Hook (Python) - Cleans up:**

```python theme={null}
import urllib.request
import os

# Access values exported by setup hook
token = os.environ.get('AUTH_TOKEN')
user_id = os.environ.get('TEST_USER_ID')

# Clean up test user
req = urllib.request.Request(
    f"{os.environ.get('API_URL')}/users/{user_id}",
    method='DELETE',
    headers={'Authorization': f'Bearer {token}'}
)

with urllib.request.urlopen(req) as response:
    pass  # Just need to execute the request

print(f"Cleaned up user {user_id}")
```

### Important Notes

* **Scripts can read and write** exported values
* **cURL hooks can only read** exported values (they cannot write to `/tmp/BugRadar.env`)
* If multiple hooks export the same key, the **latest value wins**
* Exported values are available to all subsequent hooks in the suite (across all flows)
* Exported values are also available to **subsequent flows** in the suite via `${env:KEY}`
* The agent can also retrieve exported values directly by name using **Get Variable**

> [!TIP]
>
> Hook exports are part of BugRadar's runtime variable system. For a complete overview of how variables work across hooks, flows, and suites, see [Variables](/docs/variables.md).

## Hooks and Run Caching

[Run Caching](/docs/flows.md#run-caching) speeds up a flow by replaying what a previous passing run did, instead of working it out again. Whether that replay is possible depends on how your hook passes values to the flow.

If your hook exports a new value every run — a phone number, a test account, a booking reference — BugRadar has to learn that the value is meant to change. Until it does, those runs skip the cache. They still pass or fail correctly; they are just slower.

### Export the Values Your Flow Uses

**Do this.** Write the value to `/tmp/BugRadar.env` under a name, so each run can be given its own:

```python theme={null}
number = generate_phone_number()

with open('/tmp/BugRadar.env', 'w') as f:
    f.write(f"TEST_PHONE={number}\n")
```

Then reference it in your flow instructions as `${env:TEST_PHONE}`, or have the agent fetch it with **Get Variable**.

**Not this.** Printing it is the only record, and there is no name to look it up by:

```python theme={null}
print(f"Generated phone number: {generate_phone_number()}")
```

> [!WARNING]
>
> What a setup hook prints is not part of the cache key. If a recorded run typed, tapped or checked a printed value, a later run replays only when your hook prints the same value; otherwise that run executes live and records again. The exception is a printed copy of an export BugRadar already treats as changing (see the Tip below): replay fills in the new value instead. A printed value the flow never uses, such as an ID or timestamp, does not stop runs from replaying, though a short one that happens to match text in a step can occasionally send a run live. Values shorter than 4 characters are not checked, so a recording that used one can replay after it changes.

> [!TIP]
>
> Use hook output to explain what the hook did. Printing an export's value is fine once BugRadar treats that export as changing under the [rules below](#which-values-BugRadar-treats-as-changing). A printed value your flow uses that is not covered by those rules — such as a short code (a 6-digit OTP) or a differently formatted copy — still makes each run with a new value execute live.

### Which Values BugRadar Treats as Changing

For web runs, exported `BASE_URL` and `API_BASE_URL` origins qualify automatically without a changing-value learning period. See [preview-deployment caching](/docs/flows.md#run-caching) for the required origin format and navigation limits.

For other custom exports, BugRadar compares each value against what the same hook exported last time — same flow version, same environment — and treats it as changing only if it actually changed.

| What your hook does with the value | What happens |
| - | - |
| Exports it, it is at least 8 characters, and it differs each run | Each run gets its own value |
| Exports it, and it stays the same (e.g. `API_URL`) | Treated as fixed; caching works normally |
| Exports it, but it is under 8 characters | Left alone — something as short as `4821` would match text that has nothing to do with it |
| Only prints it | If the flow uses it, each run with a new value runs live; if not, caching is unaffected |

The built-in lease hooks automatically recognize `BugRadar_EMAIL_ADDRESS`, `BugRadar_PHONE_NUMBER`, and `BugRadar_PHONE_NUMBER_NATIONAL`, including both exported phone formats. See [OTP testing](/docs/guides-otp-testing.md) for these hooks. For other custom exports, it takes **three passing runs** to settle: the first records the value, the second notices it changed and rebuilds the cache, the third can use it. Failed runs do not count. This is tracked per flow version and environment, so editing the flow's instructions starts the count over.

### When Only Some Steps Can Be Cached

A setup hook does not automatically turn caching off. For built-in leased identities and custom exports that meet the rules above, cached typing steps and descriptions can use the current run's value.

If a step contains a changed value that BugRadar cannot replace reliably — for example, an encoded copy, a phone format other than either exported form, or the exact same value shared by two exports — the agent handles that step live. Earlier independent steps can still use the cache. BugRadar resumes caching afterward only when it can confirm the required live action ran and the app matches a later checkpoint; otherwise the remaining steps run live. These partly cached runs still receive a fresh review.

Other printed values work differently: if the recording used a printed value and this run's hook prints a different one, the whole run executes live. A printed copy of an export that meets the rules above is the exception and is handled like the export.

### Runtime Hooks and Caching

A cached run executes each runtime hook again at the same step, so its side effects happen on every run.

* **Exit with a non-zero code to fail a check.** A cached run reads only the exit code, not the output. If the hook fails, the agent finishes the rest of the run live.
* **Values that change each run end the cached part.** If a runtime hook returns a new value each run — such as a sign-in code or order number — and a later step types or taps it, the agent finishes the run live from that hook onward.

### Flows That Save Variables

Flows that use the **Set Variable** action can be cached. The save itself always runs live, so the agent gets this run's value the way your instructions describe.

* **Same value as last time:** the cached steps after the save continue.
* **New value:** cached steps that type the value, open it in a URL or deep link, or copy it to the clipboard use the new value. The cached part ends at the first step that holds the value in any other form, and the agent runs the rest of the flow live.
* **New value under 8 characters:** the agent runs every step after the save live.

## Hook Examples

### cURL Examples

#### Create User Account

```bash theme={null}
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${env:ADMIN_TOKEN}" \
  -d '{
    "email": "${env:TEST_EMAIL}",
    "password": "${env:TEST_PASSWORD}",
    "role": "tester"
  }'
```

#### Reset Database

```bash theme={null}
curl -X POST https://api.example.com/test/reset \
  -H "Authorization: Bearer ${env:ADMIN_TOKEN}" \
  -d '{"scope": "test_data"}'
```

#### Generate Auth Token

```bash theme={null}
curl -X POST https://api.example.com/auth/token \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "${env:CLIENT_ID}",
    "client_secret": "${env:CLIENT_SECRET}"
  }'
```

#### Delete Test Data (Teardown)

```bash theme={null}
curl -X DELETE https://api.example.com/users/${env:TEST_USER_ID} \
  -H "Authorization: Bearer ${env:ADMIN_TOKEN}"
```

### Script Examples

#### Python: Create User and Export Credentials

```python theme={null}
import urllib.request
import urllib.error
import json
import os
import secrets
import string

# Generate random email for test user
random_suffix = ''.join(secrets.choice(string.ascii_lowercase) for _ in range(8))
test_email = f"test_{random_suffix}@example.com"

data = json.dumps({
    "email": test_email,
    "password": "TestPass123",
    "role": "tester"
}).encode('utf-8')

req = urllib.request.Request(
    f"{os.environ.get('API_URL')}/users",
    data=data,
    headers={
        'Content-Type': 'application/json',
        'Authorization': f"Bearer {os.environ.get('ADMIN_TOKEN')}"
    }
)

try:
    with urllib.request.urlopen(req) as response:
        user_data = json.loads(response.read().decode('utf-8'))
        print(f"Created test user: {test_email}")

        # Export for use in flow and teardown
        with open('/tmp/BugRadar.env', 'w') as f:
            f.write(f"TEST_USER_EMAIL={test_email}\n")
            f.write(f"TEST_USER_ID={user_data['id']}\n")
except urllib.error.HTTPError as e:
    raise Exception(f"Failed to create user: {e.read().decode('utf-8')}")
```

#### JavaScript: Fetch and Process Data

```javascript theme={null}
const response = await fetch(`${process.env.API_URL}/products`, {
  headers: { 'Authorization': `Bearer ${process.env.API_TOKEN}` }
});

const products = await response.json();

// Find a product that's in stock
const availableProduct = products.find(p => p.inStock && p.price < 100);

if (availableProduct) {
  console.log(`Found product: ${availableProduct.name} ($${availableProduct.price})`);

  // Export for use in flow
  const fs = require('fs');
  fs.writeFileSync('/tmp/BugRadar.env', `TEST_PRODUCT_ID=${availableProduct.id}\n`);
} else {
  throw new Error('No suitable test product found');
}
```

#### Bash: Quick API Check

```bash theme={null}
# Check if API is healthy before running tests
HEALTH=$(curl -s -o /dev/null -w "%{http_code}" "${API_URL}/health")

if [ "$HEALTH" != "200" ]; then
  echo "API health check failed with status: $HEALTH"
  exit 1
fi

echo "API is healthy, proceeding with tests"
```

## App Launch Configuration (Mobile Only)

### How It Works

App Launch Configuration hooks pass values to your mobile app when it launches. These values are set **at app startup** and are available throughout your test. This feature is only available for iOS and Android apps.

### When It Runs

Setup hooks all run before the app starts — unless one of them is a launch configuration, in which case the app starts **at that hook's position**. Put a hook that mints a token or seeds a user above it; hooks below it run against the already-running app.

**More than one.** Each applies at its own position, restarting the app if it is already running. Nested objects merge — setting `featureFlags.darkMode` keeps the other `featureFlags` keys — while lists and single values are replaced.

**A restart keeps device data, not screen state.** The app is not reinstalled or reset, so keychain, saved sessions and local databases survive, but the process restarts and the flow begins at your app's launch screen.

**In a suite,** flows share one session — opened by the suite's own launch configuration if it declares one. A flow's launch configuration restarts the app with its values merged over the suite's; a flow with none keeps what the session already has. With **Run flows in parallel**, each flow gets its own session and applies the suite's configuration from scratch.

### Dynamic Values (Environment & Build Variables)

Launch configuration JSON supports `${env:VARIABLE_NAME}` placeholders, resolved when the hook runs — so a placeholder sees values exported by setup hooks above it, as well as your [environment variables](/docs/environments.md) and **build variables** passed via CI (the `variables` input on the GitHub Action / upload API). This lets you drive launch configuration dynamically — for example, passing an Expo Updates channel from CI:

```json theme={null}
{
  "EXPO_CHANNEL": "${env:E2E_CHANNEL}"
}
```

The resolved value is delivered to your app as an iOS environment variable / Android intent extra (see below). Your app is responsible for acting on it — e.g. an Expo app must read the value and call `Updates.setUpdateURLAndRequestHeadersOverride(...)` followed by `Updates.reloadAsync()` to switch channels at runtime.

If a referenced variable is not set — or is set to an empty or whitespace-only value — the run stops with an error naming it, rather than starting your app with a literal `${env:...}` string.

### Accessing Values in Your App

**iOS (Swift):**

```swift theme={null}
// Access simple values (converted to strings)
let environment = ProcessInfo.processInfo.environment
let testEnv = environment["testEnvironment"] // "staging"
let apiTimeout = environment["apiTimeout"] // "30" (as string)

// Nested objects are JSON strings - parse them
if let flagsJSON = environment["featureFlags"],
   let flagsData = flagsJSON.data(using: .utf8) {
    do {
        if let flags = try JSONSerialization.jsonObject(with: flagsData) as? [String: Any] {
            let darkMode = flags["darkMode"] as? Bool // true
            let checkoutFlow = flags["newCheckoutFlow"] as? String // "enabled"
        }
    } catch {
        print("Failed to parse feature flags: \(error)")
    }
}
```

**Android (Kotlin):**

```kotlin theme={null}
import org.json.JSONObject

// Access simple values (type-aware)
val testEnv = intent.extras?.getString("testEnvironment") // "staging"
val apiTimeout = intent.extras?.getInt("apiTimeout") // 30 (as int)

// Nested objects are JSON strings - parse them
val flagsJSON = intent.extras?.getString("featureFlags")
if (flagsJSON != null) {
    try {
        val flags = JSONObject(flagsJSON)
        val darkMode = flags.getBoolean("darkMode") // true
        val checkoutFlow = flags.getString("newCheckoutFlow") // "enabled"
    } catch (e: Exception) {
        Log.e("LaunchArgs", "Failed to parse feature flags", e)
    }
}
```

**React Native:**

```javascript theme={null}
import { NativeModules, Platform } from "react-native";

// iOS: values are set as environment variables (available via native bridge)
// Android: values are passed as intent extras
const launchArgs = Platform.OS === "ios"
  ? NativeModules.ProcessInfo?.environment
  : NativeModules.IntentExtras?.getExtras();

// Simple values
console.log(launchArgs.testEnvironment); // "staging"
console.log(launchArgs.apiTimeout); // "30" (string on iOS, number on Android)

// Nested objects come as JSON strings - parse them
if (launchArgs.featureFlags) {
    const flags = JSON.parse(launchArgs.featureFlags);
    console.log(flags.darkMode); // true
    console.log(flags.newCheckoutFlow); // "enabled"
}
```

> [!NOTE]
>
> On iOS, launch configuration values are set as **environment variables** and accessed via `ProcessInfo.processInfo.environment`. On Android, they are passed as **intent extras** and accessed via `intent.extras`. See the platform-specific examples above for details.

### Launch Configuration Examples

#### Override Feature Flags

```json theme={null}
{
  "featureFlags": {
    "newCheckoutFlow": "treatment_a",
    "paymentMethodV2": "enabled",
    "showPromotion": false
  }
}
```

#### Set Environment and Timeouts

```json theme={null}
{
  "testEnvironment": "staging",
  "apiBaseUrl": "https://staging-api.example.com",
  "requestTimeout": 30,
  "retryAttempts": 3
}
```

#### A/B Testing Configuration

```json theme={null}
{
  "experiments": {
    "checkoutExperiment": "variant_b",
    "pricingExperiment": "control"
  },
  "userId": "test_user_123"
}
```

#### Debug Mode Settings

```json theme={null}
{
  "enableDebugMode": true,
  "logLevel": "verbose",
  "showPerformanceMetrics": true,
  "mockPaymentProvider": true
}
```

### When to Use Each Hook Type

| Use Case | Recommended Hook Type |
| - | - |
| Simple single API call | cURL |
| Multiple API calls with logic | Python, JavaScript, or TypeScript |
| Shell operations, piping commands | Bash |
| Configure app at startup | App Launch Configuration |
| Need error handling and retries | Python, JavaScript, or TypeScript |
| Parse and transform API responses | Python, JavaScript, or TypeScript |

## Setup Hooks & Agent Context

**Pro Tip:** When a hook produces output (via print statements, console.log, or echo), the agent automatically receives this data as additional context and can use it during flow execution.

**Example setup hook:**

```python theme={null}
import urllib.request
import json
import os

data = json.dumps({
    "email": os.environ.get('TEST_EMAIL'),
    "password": os.environ.get('TEST_PASSWORD')
}).encode('utf-8')

req = urllib.request.Request(
    f"{os.environ.get('API_URL')}/auth/login",
    data=data,
    headers={'Content-Type': 'application/json'}
)

with urllib.request.urlopen(req) as response:
    result = json.loads(response.read().decode('utf-8'))

# This output is passed to the agent
print(f"Logged in as: {result['email']}")
print(f"User role: {result['role']}")
print(f"Account created: {result['createdAt']}")
```

The agent receives this output and can reference it if needed during the flow execution.

> [!TIP]
>
> Printing a value that changes every run — a timestamp, a fresh ID — does not affect the run cache unless your flow uses that value. See [Hooks and Run Caching](#hooks-and-run-caching).

## Timeouts

Hooks have different timeout limits depending on the context:

| Context | Timeout |
| - | - |
| **Testing hooks** (via Test button) | 1 minute |
| **Flow execution** (setup, runtime, teardown) | 5 minutes |

If a hook exceeds its timeout, it will be terminated and marked as failed.

> [!TIP]
>
> Keep hooks focused and fast. If you have long-running operations, consider breaking them into multiple hooks or optimizing your API calls.

## Best Practices

> [!TIP]
>
> **Use Descriptive Names**
>
> Name hooks after what they do: "Create Premium Test User" instead of "Hook 1"

> [!TIP]
>
> **Store Secrets in Environment Variables**
>
> Never hardcode API keys or passwords in hooks. Use environment variables like `${env:API_KEY}`.

> [!TIP]
>
> **Test Hooks Independently**
>
> Use the Test button to verify your hooks work correctly before attaching them to flows.

> [!TIP]
>
> **Use Teardown Hooks for Cleanup**
>
> Always clean up test data created by setup hooks to avoid polluting your backend.
> For concurrent runs, follow [Making Suites, Parallelizable, Isolated, and
> Repeatable](/docs/guides-parallelizable-isolated-tests.md) so one session cannot change
> or delete another session's data.

> [!TIP]
>
> **Keep Hooks Simple**
>
> Each hook should do one thing. Create separate hooks for different setup tasks.

> [!TIP]
>
> **Use Scripts for Complex Logic**
>
> When you need conditionals, loops, error handling, or data processing, use Python/JavaScript instead of complex cURL commands.

> [!TIP]
>
> **Export Only What You Need**
>
> When sharing data between hooks, only export the values that subsequent hooks actually need.

> [!TIP]
>
> **Add Helpful Print Statements**
>
> Output from your hooks is passed to the agent. Add print statements to provide context about what happened.

## Hooks vs Suite Auth Instructions

| Feature | Hooks | Suite Auth Instructions |
| - | - | - |
| **Type** | Scripts, cURL, or Launch args | Natural language instructions |
| **Purpose** | Setup/cleanup backend state | Navigate app to starting point |
| **Execution** | Before/after each flow | Once at suite start |
| **Reusability** | Can be used across many flows | Specific to one suite |

**Use hooks when:** You need to configure backend state, create test data, or call APIs

**Use suite auth instructions when:** You need to start the suite from a specific state (e.g., logged in with a certain test account)

## Troubleshooting

### Script Issues

**Script times out**

* Hooks have a 5-minute timeout during flow execution (1 minute when testing)
* Break long operations into multiple hooks
* Check for infinite loops or slow API endpoints

**Environment variable not found**

* Verify the variable exists in Settings → Environments
* Check spelling and case (variable names are case-sensitive)
* For scripts, use the correct access method for your language

**Exported values not available in next hook**

* Verify you wrote to `/tmp/BugRadar.env` (exact path)
* Check key naming rules (alphanumeric + underscore, can't start with number)
* Ensure the format is `KEY=VALUE` with one per line

### cURL Request Issues

**Hook fails to execute**

* Verify the curl command works in your terminal first
* Check that environment variables are defined
* Ensure API endpoints are accessible from BugRadar's infrastructure

**Environment variables not replacing**

* Syntax must be `${env:VARIABLE_NAME}` (not `{{VARIABLE_NAME}}` or `$VARIABLE_NAME`)
* Variable names are case-sensitive
* Variables must exist in Settings → Environments

### App Launch Configuration Issues

**Configuration not appearing in app**

* Verify JSON is valid (use a JSON validator)
* Check you're accessing values correctly for your platform (ProcessInfo for iOS, intent.extras for Android)
* Ensure the hook is attached as a **setup hook** (launch configuration doesn't work in teardown)

**Values have wrong type**

* On iOS, all values become strings (including numbers and booleans)
* On Android, primitives keep their types (int, float, boolean, string)
* Nested objects are JSON-serialized as strings on both platforms
* Use the examples in this guide to parse nested structures correctly

### Data Sharing Issues

**Hook can't read value from previous hook**

* Ensure the previous hook successfully wrote to `/tmp/BugRadar.env`
* Check that the previous hook completed without errors
* Verify the key name matches exactly (case-sensitive)

**Invalid key name warning**

* Keys must contain only letters, numbers, and underscores
* Keys cannot start with a number
* Examples: `AUTH_TOKEN` ✓, `123_KEY` ✗, `API-KEY` ✗

## Managing Hooks via API

Hooks can be created, updated, and deleted programmatically via the [Hooks API](/docs/api-hooks.md). Useful for syncing hook definitions from your repo, bulk-importing from another system, or wiring up custom tooling.

Hooks can also live as script files in your repository and be referenced from code-managed flows — see [Hooks as files](/docs/code-managed-files.md#hooks-as-files).

## Next Steps

* [Learn about environment variables →](/docs/environments.md)
* [Organize flows with suites →](/docs/suites.md)
* [Create your first flow →](/docs/flows.md)
* [Manage hooks via API →](/docs/api-hooks.md)
* [Define hooks in your repo →](/docs/code-managed-files.md#hooks-as-files)


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