> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/stormkit-io/stormkit-io/llms.txt
> Use this file to discover all available pages before exploring further.

# Status Checks

> Run automated tests and validation checks after successful deployments to ensure quality before publishing.

## Overview

Status checks allow you to automatically verify conditions after a successful deployment. Based on the results, you can choose to:

* **Publish** the deployment if checks pass
* **Withhold** the deployment if checks fail

Status checks run **after** the build succeeds but **before** the deployment is published to your environment.

## When to Use Status Checks

Status checks are ideal for:

* **E2E tests** - Verify critical user flows work correctly
* **Smoke tests** - Ensure the application starts and responds
* **Visual regression tests** - Catch unintended UI changes
* **Performance tests** - Validate page load times
* **Security scans** - Check for vulnerabilities
* **Accessibility tests** - Ensure WCAG compliance

## Configuring Status Checks

<Steps>
  <Step title="Navigate to Config">
    Go to **Environment Config** > **Deployment Settings** > **Status Checks**
  </Step>

  <Step title="Add Status Check">
    Click **Add Status Check**
  </Step>

  <Step title="Enter Command">
    Provide the command that will be executed to verify the deployment
  </Step>

  <Step title="Add Metadata (Optional)">
    Provide a name and description to help other developers understand the check
  </Step>

  <Step title="Save">
    Click **Save** to apply the status check
  </Step>
</Steps>

The command will execute with the same environment variables available during the build process, plus the deployment preview URL.

## Status Check Execution

When a deployment completes successfully:

<Steps>
  <Step title="Build Completes">
    Application is built and deployed to preview URL
  </Step>

  <Step title="Status Checks Run">
    Each configured status check command executes sequentially
  </Step>

  <Step title="Results Evaluated">
    If all checks pass (exit code 0), deployment is ready to publish
  </Step>

  <Step title="Deployment Locked">
    Deployment state is locked based on check results
  </Step>
</Steps>

### Exit Codes

* **Exit code 0**: Check passed ✅
* **Non-zero exit code**: Check failed ❌

If any status check fails, the deployment will **not** be automatically published.

## Environment Variables

Status checks have access to all standard system variables:

| Variable            | Description                   | Example                                    |
| ------------------- | ----------------------------- | ------------------------------------------ |
| `SK_DEPLOYMENT_URL` | Preview URL of the deployment | `my-app--591950.stormkit.dev`              |
| `SK_APP_ID`         | Application ID                | `40140`                                    |
| `SK_DEPLOYMENT_ID`  | Deployment ID                 | `591950`                                   |
| `SK_ENV`            | Environment name              | `production`                               |
| `SK_BRANCH_NAME`    | Branch name                   | `main`                                     |
| `SK_COMMIT_SHA`     | Commit SHA                    | `1d804406ca177329541ed1b6468d8da794aab109` |

See [System Variables](/deployments/system-variables) for the complete list.

## Example Status Checks

### Puppeteer E2E Test

Run end-to-end tests using Puppeteer to verify critical user flows.

#### Install Dependencies

```json package.json theme={null}
{
  "devDependencies": {
    "puppeteer": "^21.0.0",
    "typescript": "^5.0.0",
    "@types/node": "^20.0.0"
  },
  "scripts": {
    "test:e2e": "node scripts/puppeteer.js"
  }
}
```

#### Status Check Command

```bash theme={null}
npm run test:e2e
```

#### Example Script

```javascript scripts/puppeteer.js theme={null}
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  
  const page = await browser.newPage();
  const url = `https://${process.env.SK_DEPLOYMENT_URL}`;
  
  console.log(`Testing deployment: ${url}`);
  
  try {
    // Test 1: Homepage loads
    await page.goto(url, { waitUntil: 'networkidle0' });
    console.log('✓ Homepage loaded');
    
    // Test 2: Title is correct
    const title = await page.title();
    if (!title.includes('My App')) {
      throw new Error(`Invalid title: ${title}`);
    }
    console.log('✓ Title is correct');
    
    // Test 3: Login button exists
    const loginButton = await page.$('button[data-testid="login"]');
    if (!loginButton) {
      throw new Error('Login button not found');
    }
    console.log('✓ Login button exists');
    
    // Test 4: API responds
    const response = await page.goto(`${url}/api/health`);
    if (!response.ok()) {
      throw new Error('API health check failed');
    }
    console.log('✓ API is healthy');
    
    console.log('\n✅ All tests passed!');
    process.exit(0);
  } catch (error) {
    console.error('\n❌ Tests failed:', error.message);
    process.exit(1);
  } finally {
    await browser.close();
  }
})();
```

See the complete example in our [sample repository](https://github.com/stormkit-io/sample-project/blob/main/scripts/puppeteer.ts).

### Playwright Test

Run Playwright tests against the deployment.

#### Status Check Command

```bash theme={null}
npx playwright test --config=playwright.config.ts
```

#### Configuration

```typescript playwright.config.ts theme={null}
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    baseURL: `https://${process.env.SK_DEPLOYMENT_URL}`,
  },
  testDir: './tests',
  retries: 2,
  timeout: 30000,
});
```

### Lighthouse Performance Test

Verify performance metrics using Lighthouse.

#### Status Check Command

```bash theme={null}
node scripts/lighthouse.js
```

#### Example Script

```javascript scripts/lighthouse.js theme={null}
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');

(async () => {
  const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
  const url = `https://${process.env.SK_DEPLOYMENT_URL}`;
  
  const { lhr } = await lighthouse(url, {
    port: chrome.port,
    onlyCategories: ['performance'],
  });
  
  await chrome.kill();
  
  const score = lhr.categories.performance.score * 100;
  console.log(`Performance Score: ${score}`);
  
  if (score < 80) {
    console.error('Performance score below threshold!');
    process.exit(1);
  }
  
  console.log('✅ Performance check passed');
  process.exit(0);
})();
```

### cURL Smoke Test

Simple HTTP request to verify the deployment is accessible.

#### Status Check Command

```bash theme={null}
curl -f https://$SK_DEPLOYMENT_URL || exit 1
```

The `-f` flag makes curl fail with a non-zero exit code on HTTP errors.

### API Health Check

Verify API endpoints are responding correctly.

#### Status Check Command

```bash theme={null}
node scripts/health-check.js
```

#### Example Script

```javascript scripts/health-check.js theme={null}
const https = require('https');

const url = `https://${process.env.SK_DEPLOYMENT_URL}/api/health`;

https.get(url, (res) => {
  if (res.statusCode === 200) {
    console.log('✅ API health check passed');
    process.exit(0);
  } else {
    console.error(`❌ API returned status ${res.statusCode}`);
    process.exit(1);
  }
}).on('error', (err) => {
  console.error('❌ API health check failed:', err.message);
  process.exit(1);
});
```

### Jest Integration Tests

Run Jest tests against the deployed application.

#### Status Check Command

```bash theme={null}
JEST_ENV_URL=https://$SK_DEPLOYMENT_URL npm run test:integration
```

#### Example Test

```javascript tests/integration/api.test.js theme={null}
const baseURL = process.env.JEST_ENV_URL;

describe('API Integration Tests', () => {
  test('GET /api/users returns 200', async () => {
    const response = await fetch(`${baseURL}/api/users`);
    expect(response.status).toBe(200);
  });
  
  test('POST /api/users creates user', async () => {
    const response = await fetch(`${baseURL}/api/users`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: 'Test User' }),
    });
    expect(response.status).toBe(201);
  });
});
```

## Modifying Status Checks

<Steps>
  <Step title="Navigate to Config">
    Go to **Environment Config** > **Deployment Settings** > **Status Checks**
  </Step>

  <Step title="Open Menu">
    Click the menu button (**...**) next to the status check
  </Step>

  <Step title="Edit Fields">
    Update command, name, or description
  </Step>

  <Step title="Save">
    Click **Save** to apply changes
  </Step>
</Steps>

Changes apply to future deployments only.

## Deleting Status Checks

<Steps>
  <Step title="Navigate to Config">
    Go to **Environment Config** > **Deployment Settings** > **Status Checks**
  </Step>

  <Step title="Open Menu">
    Click the menu button (**...**) next to the status check
  </Step>

  <Step title="Delete">
    Click **Delete** and confirm
  </Step>
</Steps>

## Best Practices

### Keep Checks Fast

Status checks should complete quickly (\< 5 minutes). Long-running checks delay deployments and tie up runners.

### Test Critical Paths Only

Focus on essential functionality. Run comprehensive test suites in CI before deployment.

### Use Retries

Network issues can cause false failures. Add retry logic to your status check scripts:

```javascript theme={null}
const MAX_RETRIES = 3;
let attempt = 0;

while (attempt < MAX_RETRIES) {
  try {
    await runTest();
    process.exit(0);
  } catch (error) {
    attempt++;
    if (attempt >= MAX_RETRIES) {
      console.error('All retries failed');
      process.exit(1);
    }
    console.log(`Retry ${attempt}/${MAX_RETRIES}`);
    await sleep(2000);
  }
}
```

### Log Detailed Output

Provide clear logs to help debug failures:

```javascript theme={null}
console.log('Running test: Homepage loads');
console.log(`URL: ${url}`);
console.log(`Expected title: ${expectedTitle}`);
console.log(`Actual title: ${actualTitle}`);
```

### Combine with Auto Publish

Use status checks with auto publish to create a fully automated deployment pipeline:

1. Code is pushed to main branch
2. Auto deployment triggers
3. Build succeeds
4. Status checks run
5. If checks pass, deployment auto-publishes

## Troubleshooting

### Status Check Fails Unexpectedly

* Check status check logs in deployment details
* Verify the preview URL is accessible
* Ensure required dependencies are installed
* Check for race conditions (app not fully loaded)

### Timeout Issues

If status checks time out:

* Reduce test scope
* Optimize test execution
* Increase timeout in your test framework
* Check network connectivity

### Environment Variable Issues

If environment variables are missing:

* Verify variables are set in environment config
* Check variable names are correct
* Ensure variables are not obfuscated when needed

## Deployment Flow with Status Checks

```mermaid theme={null}
graph TD
    A[Deployment Triggered] --> B[Build Application]
    B --> C{Build Success?}
    C -->|No| D[Deployment Failed]
    C -->|Yes| E[Upload Artifacts]
    E --> F[Create Preview URL]
    F --> G[Run Status Checks]
    G --> H{All Checks Pass?}
    H -->|Yes| I[Lock Deployment - Success]
    H -->|No| J[Lock Deployment - Failed]
    I --> K{Auto Publish?}
    K -->|Yes| L[Publish to Environment]
    K -->|No| M[Ready to Publish]
```

## Related Documentation

<CardGroup cols={2}>
  <Card title="Auto Deployments" icon="rotate" href="/deployments/auto-deployments">
    Configure automatic deployments
  </Card>

  <Card title="Outbound Webhooks" icon="webhook" href="/deployments/outbound-webhooks">
    Trigger external services on deployment events
  </Card>

  <Card title="System Variables" icon="code" href="/deployments/system-variables">
    Available environment variables
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/deployments/troubleshooting">
    Fix common deployment issues
  </Card>
</CardGroup>
