Tutorials

Securing CaptchaAI Credentials in Environment Variables

Hardcoding API keys in source code means anyone with repository access — or anyone who finds your code on a public repo — has your key. Environment variables keep credentials out of code, version control, and logs.


.env file (local development)

Create a .env file in your project root:

CAPTCHAAI_API_KEY=your_actual_api_key_here

Add it to .gitignore immediately:

# .gitignore
.env
.env.local
.env.production

Python (python-dotenv)

pip install python-dotenv
import os
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.environ["CAPTCHAAI_API_KEY"]

# Use in API calls
import requests
resp = requests.post("https://ocr.captchaai.com/in.php", data={
    "key": API_KEY,
    "method": "userrecaptcha",
    "googlekey": "6Le-SITEKEY",
    "pageurl": "https://example.com",
    "json": "1",
})
print(resp.json())

JavaScript (dotenv)

npm install dotenv
require('dotenv').config();

const API_KEY = process.env.CAPTCHAAI_API_KEY;

if (!API_KEY) {
  console.error('CAPTCHAAI_API_KEY not set');
  process.exit(1);
}

// Use in API calls
const axios = require('axios');
const resp = await axios.post('https://ocr.captchaai.com/in.php', null, {
  params: {
    key: API_KEY,
    method: 'userrecaptcha',
    googlekey: '6Le-SITEKEY',
    pageurl: 'https://example.com',
    json: 1,
  },
});
console.log(resp.data);

System environment variables

Set variables at the OS level instead of using .env files:

Linux / macOS

export CAPTCHAAI_API_KEY="your_actual_api_key_here"

# Persist across sessions — add to ~/.bashrc or ~/.zshrc
echo 'export CAPTCHAAI_API_KEY="your_actual_api_key_here"' >> ~/.bashrc

Windows (PowerShell)

$env:CAPTCHAAI_API_KEY = "your_actual_api_key_here"

# Persist permanently
[System.Environment]::SetEnvironmentVariable("CAPTCHAAI_API_KEY", "your_actual_api_key_here", "User")

Docker

Environment variable in docker run

docker run -e CAPTCHAAI_API_KEY="your_key" my-scraper

Docker Compose

# docker-compose.yml
services:
  scraper:
    image: my-scraper
    environment:

      - CAPTCHAAI_API_KEY=${CAPTCHAAI_API_KEY}

The ${CAPTCHAAI_API_KEY} references the host's environment variable — the key never appears in the compose file.

Docker secrets (Swarm)

echo "your_actual_api_key_here" | docker secret create captchaai_key -
# docker-compose.yml (Swarm mode)
services:
  scraper:
    image: my-scraper
    secrets:

      - captchaai_key
secrets:
  captchaai_key:
    external: true

Read in code:

with open("/run/secrets/captchaai_key") as f:
    API_KEY = f.read().strip()

CI/CD pipelines

GitHub Actions

# .github/workflows/scrape.yml
jobs:
  scrape:
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v4
      - run: python scraper.py
        env:
          CAPTCHAAI_API_KEY: ${{ secrets.CAPTCHAAI_API_KEY }}

Add the secret in Settings → Secrets and variables → Actions → New repository secret.

GitLab CI

# .gitlab-ci.yml
scrape:
  script:

    - python scraper.py
  variables:
    CAPTCHAAI_API_KEY: $CAPTCHAAI_API_KEY

Add the variable in Settings → CI/CD → Variables with the "Masked" option enabled.


Validation at startup

Always validate that the key exists and works before running your pipeline:

import os
import sys
import requests

API_KEY = os.environ.get("CAPTCHAAI_API_KEY")
if not API_KEY:
    print("ERROR: CAPTCHAAI_API_KEY environment variable not set")
    sys.exit(1)

# Verify key works
resp = requests.get("https://ocr.captchaai.com/res.php", params={
    "key": API_KEY, "action": "getbalance", "json": "1"
}).json()

if resp["status"] != 1:
    print(f"ERROR: Invalid API key — {resp['request']}")
    sys.exit(1)

print(f"API key valid — balance: ${float(resp['request']):.2f}")

Common mistakes

Mistake Risk Fix
Committing .env to Git Key exposed in repo history Add .env to .gitignore before first commit
Printing API key in logs Key visible in log aggregators Never log full keys — mask or omit them
Hardcoding in Dockerfile Key baked into image layers Use ENV at runtime, not in build stages
Sharing keys via chat/email Key intercepted or leaked Use a secrets manager or share via secure channel

FAQ

Should I encrypt the .env file?

For local development, .gitignore is sufficient. For production, use a cloud secret manager (AWS Secrets Manager, Google Secret Manager, Azure Key Vault) instead of .env files.

What if my key is already committed to Git?

Rotate the key immediately in your CaptchaAI dashboard. The old key in Git history remains accessible even after deleting the file.

Can I use multiple keys in one .env file?

Yes. Use comma-separated values or numbered keys:

CAPTCHAAI_KEYS=key1,key2,key3
keys = os.environ["CAPTCHAAI_KEYS"].split(",")

Secure your CaptchaAI integration from day one

Get your API key at captchaai.com.


Full Working Code

Complete runnable examples for this article in Python, Node.js, PHP, Go, Java, C#, Ruby, Rust, Kotlin & Bash.

View on GitHub →

Discussions (0)

No comments yet.