# How to Use Retool's Testing Environment

- Tool: Retool
- Difficulty: Advanced
- Time required: 25-30 min
- Compatibility: Retool Cloud and Self-hosted (Environments feature on Business+)
- Last updated: March 2026

## TL;DR

Retool has two environments: staging (for testing) and production (for live users). Configure resources with staging/production variants using Retool Environments (Settings → Environments). In staging, queries use staging database credentials. Test changes in the editor's Preview mode before deploying. Use {{ retoolContext.environment === 'staging' }} to show debug info only in staging.

## Testing Strategies for Retool Apps Before Production Release

Retool apps connect directly to production databases by default. Without a testing strategy, any mistake in a query can affect production data — a wrong UPDATE query can corrupt real customer records. Testing environments prevent this.

Retool provides two mechanisms: (1) Preview mode — view your app changes before deploying to live users, using the same resources as production but in the editor context. (2) Retool Environments — configure multiple resource variants (staging, production) and switch between them, so staging apps connect to staging databases.

This tutorial covers both mechanisms and provides a practical QA workflow for testing before release.

## Before you start

- A Retool app connected to at least one database or API resource
- A staging database or API endpoint to use for safe testing
- Retool Business plan or higher for Environments feature

## Step-by-step guide

### 1. Use Preview mode for quick pre-deployment testing

Before publishing changes, use Retool's Preview mode to test how your app looks and behaves without affecting live users. In the editor, click the eye icon or 'Preview' button (top-right) to switch from edit mode to preview mode. Preview mode simulates the app as it appears to end users — event handlers fire, queries run, and navigation works. Test your changes thoroughly in preview before clicking Deploy. Important: preview mode uses the same resources (database connections) as production — be careful with write operations.

**Expected result:** App changes tested in preview mode without affecting the deployed version visible to live users.

### 2. Configure staging and production environments

Navigate to Settings → Environments (Business+ feature). Create a 'Staging' environment alongside the existing 'Production' environment. For each database resource, configure environment-specific connection details: staging environment uses your staging database credentials, production environment uses your production credentials. The resource name stays the same — only the connection details differ per environment. This means the same app and queries work in both environments with no code changes.

**Expected result:** Staging environment configured with staging database credentials. Queries automatically use staging data when the staging environment is active.

### 3. Test with the staging environment active

In the Retool editor, find the environment switcher (usually in the top bar or app settings). Switch to 'Staging'. Now all queries that use resources configured with environment variants will connect to your staging database instead of production. Run your tests: submit forms, trigger queries, verify data operations. Any mistakes (wrong SQL, accidental deletes) only affect staging data, not production.

```
// In JS Queries, check which environment is active:
console.log('Current environment:', retoolContext.environment);
// Returns: 'staging' or 'production'

// Conditional behavior based on environment:
if (retoolContext.environment === 'staging') {
  // Extra debug logging in staging only
  console.log('Query params:', JSON.stringify(queryParams));
  console.log('Expected result:', JSON.stringify(updateQuery.data));
}

// Show staging banner to editors:
// Text component value:
{{ retoolContext.environment === 'staging' ? '⚠️ STAGING — Not production data' : '' }}
```

**Expected result:** Tests run against staging data. Production data is protected from test-related changes.

### 4. Use retoolContext.environment for conditional debug features

Add a staging-only debug banner at the top of your app using {{ retoolContext.environment }} to remind users they're in a test environment. Also use this to enable extra debug logging in JS Queries that is disabled in production. This pattern prevents debug code from running in production while still being testable.

```
// Staging banner component:
// Add a Container at the top of the app
// Hidden property: {{ retoolContext.environment !== 'staging' }}
// Background color: #fef3c7 (yellow)
// Content: ⚠️ STAGING ENVIRONMENT — Database changes will NOT affect production

// Conditional debug logging in JS Query:
if (retoolContext.environment === 'staging') {
  console.log('[DEBUG] saveRecord params:', {
    id: table1.selectedRow.data.id,
    values: {
      name: nameInput.value,
      status: statusSelect.value,
    },
  });
}
```

**Expected result:** Staging banner visible only in staging environment. Debug logging enabled only in staging.

### 5. Create a QA checklist for pre-deployment testing

Before deploying any significant change, run through a structured QA checklist. Build this checklist based on your app's critical functionality. Typical checklist items: load test data displays correctly, key user workflows complete without errors, error states display appropriate messages, permission restrictions work for each user group, mobile responsiveness (if applicable), and no console errors in DevTools.

```
// QA CHECKLIST TEMPLATE
// Run before every production deployment

/*
FUNCTIONALITY:
[ ] Page loads without JavaScript errors (check DevTools Console)
[ ] All queries return expected data (check Debug Panel Queries tab)
[ ] Search/filter functionality works
[ ] Sort functionality works
[ ] Pagination works (if applicable)

WRITE OPERATIONS:
[ ] Form submission creates/updates record correctly
[ ] Required field validation shows appropriate errors
[ ] Success notification appears after save
[ ] Data refreshes after save (table/list updates)
[ ] Delete confirmation appears before destructive actions

PERMISSIONS:
[ ] Admin-only features hidden for non-admin users
[ ] Test with a non-admin test account

EDGE CASES:
[ ] Empty table state shows appropriate message
[ ] Error state (disconnect resource temporarily) shows user-friendly message
[ ] Large dataset loads without performance issues
*/
```

**Expected result:** All QA checklist items pass in staging environment before deploying to production.

## Complete code example

File: `JS Query: environmentAwareLogger`

```javascript
// JS Query: environmentAwareLogger
// Utility for environment-aware logging and debugging
// Include this in JS Queries where detailed debug logging is needed

const IS_STAGING = retoolContext.environment === 'staging';

// Log only in staging
const debugLog = (label, data) => {
  if (IS_STAGING) {
    console.log(`[STAGING DEBUG] ${label}:`, JSON.stringify(data, null, 2));
  }
};

// Assertion that throws in staging, silent in production
const assert = (condition, message) => {
  if (!condition && IS_STAGING) {
    console.error(`[STAGING ASSERTION FAILED] ${message}`);
    utils.showNotification({
      title: 'Staging assertion failed',
      description: message,
      notificationType: 'error',
    });
  }
};

// Example usage in a save operation:
debugLog('Table selected row', table1.selectedRow.data);
debugLog('Form values', {
  title: titleInput.value,
  status: statusSelect.value,
});

assert(titleInput.value, 'Title should not be empty before save');
assert(table1.selectedRow.data.id, 'A row must be selected before save');

// ... rest of save logic
await updateRecord.trigger();

debugLog('Update result', updateRecord.data);
assert(updateRecord.data.length > 0, 'Update should affect at least 1 row');
```

## Common mistakes

- **Using Preview mode to test write operations (INSERT/UPDATE/DELETE) assuming they don't affect production** — undefined Fix: Preview mode uses the same resource connections as production. Write queries in preview mode execute against your real database. Use staging environment (with staging resource configuration) for testing writes safely.
- **Not testing with non-admin permissions before deploying** — undefined Fix: Admin users bypass many permission restrictions. Always test as a non-admin user to verify that permission-gated features work correctly. Create a dedicated test account in a non-admin group for this purpose.
- **Leaving retoolContext.environment conditional code out of cleanup, deploying debug logging to production** — undefined Fix: Always use {{ retoolContext.environment === 'staging' }} conditions to gate debug code. Review all console.log statements before deploying — use the environment check to ensure they only run in staging.

## Best practices

- Always have a staging environment with real-ish (anonymized) data that mirrors production structure
- Test with a non-admin test account before deploying — admin access can mask permission-related bugs
- Never use production data for testing write operations — always test against staging data
- Run the QA checklist from a fresh browser session (incognito) to test without cached state
- Schedule deployments during low-traffic periods to minimize impact if a rollback is needed

## Frequently asked questions

### Is Retool Preview mode the same as a staging environment?

No — Preview mode shows your unpublished app changes before deploying, but still uses your production resources. A staging environment uses separate resource connections (pointing to a staging database), so write operations in staging don't affect production data. Use Preview mode for UI/layout testing and staging environment for testing write operations safely.

### Can regular users (non-admins) access the staging environment in Retool?

Environments are an editor/admin feature — only users with edit access can switch environments. End users who access published apps always see the production environment. The staging environment is exclusively for development and testing purposes by your Retool editing team.

### What if I don't have a staging database? Can I still test safely?

Without a staging database, use read-only testing strategies: test read queries freely, but for write operations, use a 'test_' prefixed table in production, add a confirmation dialog that lets you review the SQL before executing, or temporarily add a WHERE 1=0 clause to write queries to make them no-ops during testing.

---

Source: https://www.rapidevelopers.com/retool-tutorial/how-to-use-retool-s-testing-environment
© RapidDev — https://www.rapidevelopers.com/retool-tutorial/how-to-use-retool-s-testing-environment
