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

# System Environment Variables

> Predefined environment variables automatically injected during build and runtime for Stormkit deployments.

## Overview

Stormkit automatically injects several environment variables into your deployment environment. These variables are available during:

* **Build time** - When your application is being built
* **Runtime** - When serverless functions execute
* **Status checks** - When post-deployment tests run

Use these variables to customize behavior based on the deployment context.

## Available Variables

| Variable            | Description                                | Example                                    |
| ------------------- | ------------------------------------------ | ------------------------------------------ |
| `SK_APP_ID`         | The application ID being deployed          | `40140`                                    |
| `SK_BRANCH_NAME`    | The branch name being deployed             | `main`                                     |
| `SK_DEPLOYMENT_ID`  | The unique deployment ID                   | `591950`                                   |
| `SK_DEPLOYMENT_URL` | The preview URL of the deployment          | `my-app--591950.stormkit.dev`              |
| `SK_ENV`            | The environment name used as configuration | `staging`                                  |
| `SK_ENV_ID`         | The environment ID                         | `20510`                                    |
| `SK_ENV_URL`        | The URL of the environment                 | `my-app--staging.stormkit.dev`             |
| `SK_COMMIT_SHA`     | The long-format commit SHA                 | `1d804406ca177329541ed1b6468d8da794aab109` |
| `STORMKIT`          | Indicates running on Stormkit              | `true` (string)                            |

## Usage Examples

### Detecting Stormkit Environment

Check if your code is running on Stormkit:

<CodeGroup>
  ```javascript JavaScript theme={null}
  if (process.env.STORMKIT === 'true') {
    console.log('Running on Stormkit')
  }
  ```

  ```typescript TypeScript theme={null}
  const isStormkit = process.env.STORMKIT === 'true'

  if (isStormkit) {
    console.log('Running on Stormkit')
  }
  ```

  ```python Python theme={null}
  import os

  if os.getenv('STORMKIT') == 'true':
      print('Running on Stormkit')
  ```

  ```go Go theme={null}
  import "os"

  if os.Getenv("STORMKIT") == "true" {
      fmt.Println("Running on Stormkit")
  }
  ```
</CodeGroup>

### Environment-Specific Configuration

Use different settings per environment:

```javascript config.js theme={null}
const config = {
  production: {
    apiUrl: 'https://api.production.com',
    debug: false
  },
  staging: {
    apiUrl: 'https://api.staging.com',
    debug: true
  },
  development: {
    apiUrl: 'http://localhost:3000',
    debug: true
  }
}

const env = process.env.SK_ENV || 'development'

export default config[env]
```

### Preview URL in API Calls

Construct URLs dynamically based on deployment:

```javascript theme={null}
const baseUrl = process.env.SK_DEPLOYMENT_URL 
  ? `https://${process.env.SK_DEPLOYMENT_URL}`
  : 'http://localhost:3000'

fetch(`${baseUrl}/api/data`)
  .then(res => res.json())
  .then(data => console.log(data))
```

### Git Information in Application

Display deployment information to users:

```javascript theme={null}
const deploymentInfo = {
  version: process.env.SK_COMMIT_SHA?.substring(0, 7),
  branch: process.env.SK_BRANCH_NAME,
  deploymentId: process.env.SK_DEPLOYMENT_ID
}

console.log('Deployment Info:', deploymentInfo)
// Output: { version: '1d80440', branch: 'main', deploymentId: '591950' }
```

### Environment-Based Feature Flags

```javascript theme={null}
const features = {
  enableBetaFeatures: process.env.SK_ENV !== 'production',
  enableAnalytics: process.env.SK_ENV === 'production',
  debugMode: ['development', 'staging'].includes(process.env.SK_ENV)
}

if (features.debugMode) {
  console.log('Debug mode enabled')
}
```

## Build-Time Usage

Access variables during build in your build scripts:

### Next.js

```javascript next.config.js theme={null}
/** @type {import('next').NextConfig} */
const nextConfig = {
  env: {
    DEPLOYMENT_ID: process.env.SK_DEPLOYMENT_ID,
    COMMIT_SHA: process.env.SK_COMMIT_SHA,
  },
  publicRuntimeConfig: {
    environmentName: process.env.SK_ENV,
  }
}

module.exports = nextConfig
```

### Vite

```javascript vite.config.js theme={null}
import { defineConfig } from 'vite'

export default defineConfig({
  define: {
    __APP_VERSION__: JSON.stringify(process.env.SK_COMMIT_SHA?.substring(0, 7)),
    __ENVIRONMENT__: JSON.stringify(process.env.SK_ENV),
  }
})
```

### Create React App

Prefix with `REACT_APP_` to expose to browser:

```bash .env.production theme={null}
REACT_APP_COMMIT_SHA=$SK_COMMIT_SHA
REACT_APP_BRANCH=$SK_BRANCH_NAME
REACT_APP_ENV=$SK_ENV
```

```javascript theme={null}
const version = process.env.REACT_APP_COMMIT_SHA?.substring(0, 7)
console.log('Version:', version)
```

## Runtime Usage

Access variables in serverless functions:

### API Function Example

```javascript api/info.js theme={null}
export default async (req, res) => {
  const info = {
    environment: process.env.SK_ENV,
    deploymentId: process.env.SK_DEPLOYMENT_ID,
    branch: process.env.SK_BRANCH_NAME,
    commitSha: process.env.SK_COMMIT_SHA,
    deploymentUrl: process.env.SK_DEPLOYMENT_URL,
    timestamp: new Date().toISOString()
  }
  
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify(info, null, 2))
}
```

### Server-Side Rendering

```typescript server/index.ts theme={null}
import serverless from '@stormkit/serverless'

export const handler = serverless(async (req, res) => {
  const html = `
    <!DOCTYPE html>
    <html>
      <head><title>Deployment Info</title></head>
      <body>
        <h1>Deployment Information</h1>
        <ul>
          <li>Environment: ${process.env.SK_ENV}</li>
          <li>Branch: ${process.env.SK_BRANCH_NAME}</li>
          <li>Commit: ${process.env.SK_COMMIT_SHA?.substring(0, 7)}</li>
          <li>Deployment ID: ${process.env.SK_DEPLOYMENT_ID}</li>
        </ul>
      </body>
    </html>
  `
  
  res.writeHead(200, { 'Content-Type': 'text/html' })
  res.end(html)
})
```

## Status Check Usage

Use deployment URL in status checks:

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

;(async () => {
  const url = `https://${process.env.SK_DEPLOYMENT_URL}`
  console.log(`Testing deployment: ${url}`)
  
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  
  await page.goto(url)
  const title = await page.title()
  
  console.log(`Page title: ${title}`)
  
  await browser.close()
  process.exit(0)
})()
```

## TypeScript Types

Define types for system variables:

```typescript types/env.d.ts theme={null}
declare namespace NodeJS {
  interface ProcessEnv {
    // Stormkit system variables
    SK_APP_ID?: string
    SK_BRANCH_NAME?: string
    SK_DEPLOYMENT_ID?: string
    SK_DEPLOYMENT_URL?: string
    SK_ENV?: string
    SK_ENV_ID?: string
    SK_ENV_URL?: string
    SK_COMMIT_SHA?: string
    STORMKIT?: 'true' | 'false'
    
    // Your custom variables
    DATABASE_URL?: string
    API_KEY?: string
  }
}
```

Use with type safety:

```typescript theme={null}
const deploymentUrl: string = process.env.SK_DEPLOYMENT_URL || 'localhost:3000'
const isProduction: boolean = process.env.SK_ENV === 'production'
```

## Variable Precedence

When multiple variables have the same name:

1. **Manual deployment overrides** (highest priority)
2. **Environment configuration variables**
3. **System variables** (lowest priority)

System variables cannot be overridden by user-defined variables.

## Security Considerations

### Never Expose Secrets in Client

System variables are safe to use client-side, but don't expose secrets:

```javascript theme={null}
// ✅ Safe - System variables are public information
const deploymentId = process.env.SK_DEPLOYMENT_ID

// ❌ Dangerous - Don't expose secrets to client
const apiKey = process.env.SECRET_API_KEY // Never in client code!
```

### Server-Side Only Variables

Keep sensitive data server-side:

```javascript api/secure.js theme={null}
// Server-side only - not accessible to browser
const dbPassword = process.env.DATABASE_PASSWORD
const apiSecret = process.env.API_SECRET
```

## Best Practices

### Use Environment Detection

Instead of hardcoding environment checks:

```javascript theme={null}
// ❌ Bad - Hardcoded
if (window.location.hostname.includes('staging')) {
  enableDebugMode()
}

// ✅ Good - Use SK_ENV
if (process.env.SK_ENV === 'staging') {
  enableDebugMode()
}
```

### Version Display

Show version info to users:

```javascript theme={null}
const version = process.env.SK_COMMIT_SHA?.substring(0, 7) || 'dev'

console.log(`App version: ${version}`)
// Add to footer
document.getElementById('version').textContent = `v${version}`
```

### Debug Logging

Enable verbose logging in non-production:

```javascript theme={null}
const DEBUG = process.env.SK_ENV !== 'production'

function log(...args) {
  if (DEBUG) {
    console.log('[DEBUG]', ...args)
  }
}

log('User action:', action) // Only logs in dev/staging
```

### Analytics Environment Tagging

```javascript theme={null}
import analytics from './analytics'

analytics.identify({
  environment: process.env.SK_ENV,
  deploymentId: process.env.SK_DEPLOYMENT_ID,
  branch: process.env.SK_BRANCH_NAME
})
```

## Testing Locally

Simulate Stormkit environment locally:

```bash .env.local theme={null}
STORMKIT=true
SK_APP_ID=40140
SK_BRANCH_NAME=main
SK_DEPLOYMENT_ID=dev-local
SK_DEPLOYMENT_URL=localhost:3000
SK_ENV=development
SK_ENV_ID=1
SK_ENV_URL=localhost:3000
SK_COMMIT_SHA=0000000000000000000000000000000000000000
```

Load with dotenv:

```javascript theme={null}
require('dotenv').config({ path: '.env.local' })

console.log('Environment:', process.env.SK_ENV)
// Output: Environment: development
```

## Accessing in Different Frameworks

### Next.js App Router

```typescript app/api/info/route.ts theme={null}
import { NextResponse } from 'next/server'

export async function GET() {
  return NextResponse.json({
    env: process.env.SK_ENV,
    deploymentId: process.env.SK_DEPLOYMENT_ID,
  })
}
```

### SvelteKit

```javascript theme={null}
import { SK_ENV, SK_DEPLOYMENT_ID } from '$env/static/private'

export function load() {
  return {
    environment: SK_ENV,
    deploymentId: SK_DEPLOYMENT_ID
  }
}
```

### Remix

```typescript theme={null}
export async function loader() {
  return json({
    env: process.env.SK_ENV,
    deploymentId: process.env.SK_DEPLOYMENT_ID,
  })
}
```

### Nuxt 3

```typescript server/api/info.ts theme={null}
export default defineEventHandler(() => {
  return {
    env: process.env.SK_ENV,
    deploymentId: process.env.SK_DEPLOYMENT_ID,
  }
})
```

## Related Documentation

<CardGroup cols={2}>
  <Card title="Configuration" icon="gear" href="/deployments/configuration">
    Configure custom environment variables
  </Card>

  <Card title="Outbound Webhooks" icon="webhook" href="/deployments/outbound-webhooks">
    Use system variables in webhooks
  </Card>

  <Card title="Status Checks" icon="check-circle" href="/deployments/status-checks">
    Access variables in status checks
  </Card>

  <Card title="How We Deploy" icon="diagram-project" href="/deployments/how-we-deploy">
    Understand deployment process
  </Card>
</CardGroup>
