# Secrets & API keys

> Keep third-party API keys strictly server-side, separate Preview and Live credentials cleanly, and rotate exposed keys safely without breaking live customer flows.

- Canonical: https://exaspark.ai/docs/secrets-and-env-vars/

## Why secrets must stay server-side

Every web app runs across two zones: frontend code in a visitor's browser and backend code on your server. Anything shipped to browser JavaScript, HTML, or CSS is completely public — any visitor can open DevTools and copy hardcoded strings in seconds.

Third-party API keys carry direct billing and security authority. An exposed Stripe secret key can issue unauthorized refunds, a leaked email key can send domain spam, and a stolen AI key lets attackers drain your balance overnight.

ExaSpark keeps sensitive credentials inside encrypted server-side project settings. Secrets load strictly into backend routes at runtime and never enter browser bundles or GitHub exports.

## Public config vs server secrets vs database rows

Deciding where each value belongs prevents accidental leaks and brittle hardcoding. Use this boundary table whenever you integrate an external service.

| Configuration type | Examples | Where it belongs | Safe in browser? |
| --- | --- | --- | --- |
| **Server-side secret** | Stripe secret key (`sk_live_...`), webhook secret (`whsec_...`), AI keys, SMS tokens | Encrypted environment variables read only in backend routes | Never |
| **Public client key** | Stripe publishable key (`pk_live_...`), Maps browser key, analytics ID | Public client config or non-secret frontend settings | Yes, domain-restricted |
| **Environment flag** | App base URL, feature toggle, support email, default currency | Non-secret environment config or constants | Yes |
| **Editable business setting** | Store hours, tax rate, active coupon percent, announcement text | Managed relational table in **Cloud** | Read via API |

> **Note:** Treat every third-party key as a server-side secret unless the provider explicitly marks it safe for public browsers and supports domain restrictions.

## Preview vs Live secret separation

ExaSpark isolates **Preview** from **Live** across databases, user accounts, file storage, and environment secrets. Reviewing how [Preview vs Live isolation](https://exaspark.ai/docs/preview-vs-live/) separates credentials keeps test runs away from real buyers.

### Mapping sandbox keys to Preview and real keys to Live

Most external APIs provide separate sandbox and production credentials. Always bind sandbox tokens to Preview and production keys strictly to Live.

| Provider category | Preview value | Live value | Risk if mixed |
| --- | --- | --- | --- |
| **Stripe payments** | Test keys (`sk_test_...`, `whsec_test_...`) | Live keys (`sk_live_...`, `whsec_live_...`) | Test clicks charge real cards or Live fails |
| **Email or SMS** | Sandbox key or test sender token | Verified production domain sender key | Tests email real buyers or burn quotas |
| **AI providers** | Low-cap development key | Production key with monthly spend cap | Dev loops exhaust production rate limits |
| **Shipping or CRM** | Staging workspace token | Production workspace token | Fake orders buy labels or pollute CRMs |

### What happens to secrets on Publish

Clicking **Publish** promotes verified frontend code, backend routes, and additive schema updates from Preview to Live. It never overwrites Live secrets with Preview test keys and never bundles secrets into client files.

When you introduce a new variable name in Preview (such as `SHIPPO_API_KEY`), add its production counterpart in **Live** settings before clicking **Publish** so the new route authenticates immediately.

## Adding a third-party secret safely

1. **Generate a narrow key at the provider** — Mint an API key limited strictly to the scopes your app requires rather than full account admin access.
2. **Pick descriptive uppercase names** — Use clear provider-scoped names such as `OPENAI_API_KEY`, `SLACK_WEBHOOK_URL`, or `TWILIO_AUTH_TOKEN`.
3. **Save Preview and Live values separately** — Put the sandbox token in **Preview** settings and the production credential separately in **Live** settings.
4. **Read the variable only inside backend routes** — Build a server route that validates the caller's session, reads the secret server-side, calls the provider, and returns minimal JSON.
5. **Confirm zero browser exposure** — Test in **Preview**, check browser DevTools Network responses, and confirm the key never appears in URLs, payloads, or client files.

Maintain a clean `.env.example` template listing variable names without real values whenever exporting code through [Inspect code & GitHub App](https://exaspark.ai/docs/code-and-github/):

```bash
# Required server-side environment variables (never commit real values)
OPENAI_API_KEY=replace_with_server_key
RESEND_API_KEY=replace_with_email_key
WEBHOOK_SIGNING_SECRET=replace_with_provider_webhook_secret

# Public non-secret configuration
PUBLIC_APP_URL=https://yourdomain.com
```

## Preventing accidental browser and chat leaks

Most credential leaks come from everyday habits rather than sophisticated attacks. Guard these five leak paths across every project:

- **Never paste real secrets into UI copy or fixtures.** Keep credentials strictly inside encrypted environment settings, never hardcoded in source files or sample JSON.
- **Sanitize upstream errors before responding.** Log detailed provider errors server-side and return minimal messages (such as `"Carrier rate lookup unavailable"`) to browsers.
- **Avoid secrets in query strings.** Never put tokens inside redirect URLs or image links where browser history and proxy logs capture them.
- **Guard client bundler prefixes.** Frontend prefixes like `VITE_` or `NEXT_PUBLIC_` expose values directly to browsers — never prefix private secrets that way.
- **Mask screenshots and support captures.** Redact authorization headers and webhook secrets before sharing Network captures or logs.

> **Example prompt (App):** Create a server-side endpoint POST /api/shipping/rates requiring a signed-in user session. Validate destination postal code and weight, read process.env.SHIPPING_API_KEY strictly on the server, call the carrier API with a 6-second timeout, and return only carrier name, service level, and price in cents. Never reference SHIPPING_API_KEY in frontend code.

## Rotating secrets cleanly and handling a leak

### Zero-downtime planned rotation

Most providers let two production keys remain active briefly during rotation so active customers never see errors.

1. **Mint a replacement key** — Create a second production key at the provider while keeping the current key active temporarily.
2. **Update Live project settings** — Replace the stored value in ExaSpark **Live** settings with the new credential.
3. **Verify live requests succeed** — Trigger one real request and inspect Analytics to confirm the backend authenticates cleanly.
4. **Revoke the retired key** — Delete the old credential at the provider once live traffic succeeds on the new key.

### Emergency steps after accidental exposure

If a real key lands in a source file, public screenshot, or Git commit, assume scanners already saw it.

- **Revoke first, edit code second.** Roll or delete the compromised key in the provider dashboard before touching repository history.
- **Strip literal strings from source files.** Move every secret read back to environment variables and inspect the **Code** tab to verify zero literals remain.
- **Review provider billing and audit logs.** Check recent API calls for unauthorized usage spikes or unfamiliar destinations.

> **Example prompt (App):** Audit all frontend and backend files in this project for hardcoded API keys, bearer tokens, webhook signing secrets, or private credentials exposed via client prefixes. Report any findings, move every secret strictly to server-side environment reads, and update .env.example with placeholder names only.

## Common mistakes and troubleshooting

| Symptom | Root cause | Exact fix |
| --- | --- | --- |
| **Works in Preview, fails with 500 on Live** | Secret exists in Preview settings but was never added to Live | Add the production value in **Live** settings with the exact matching variable name |
| **External API returns 401 Unauthorized** | Trailing whitespace copied with key, wrong environment key, or revoked token | Re-copy without spaces and verify sandbox vs live endpoint URLs match the key |
| **Key appears in browser DevTools** | Variable used a public client prefix or ran inside a frontend component | Revoke the key immediately, move the call server-side, and remove client references |
| **GitHub Secret Scanning blocks export** | Literal provider token exists in code or a local `.env` commit | Revoke the key, delete hardcoded strings, verify `.env*` is gitignored, and re-export |
| **Server reads `undefined` for secret** | Spelling or case mismatch between settings and backend route | Match exact uppercase names across environment settings and server code |

## Next steps

- [External APIs & webhooks](https://exaspark.ai/docs/external-apis-and-webhooks/) — Call third-party REST APIs cleanly and verify incoming webhook signatures.
- [Preview vs Live isolation](https://exaspark.ai/docs/preview-vs-live/) — Keep test keys, databases, and user sessions walled off from Live.
- [Security & data ownership](https://exaspark.ai/docs/security-and-ownership/) — Review platform security layers, RBAC enforcement, and code ownership.

## From the blog

- [App security checklist](https://exaspark.ai/blog/app-security-checklist/) — Practical security checks before launching any AI-built web app.
- [What is an API?](https://exaspark.ai/blog/what-is-an-api/) — Plain-English introduction to how servers exchange authenticated data.
- [Frontend vs backend](https://exaspark.ai/blog/frontend-vs-backend/) — Understand why sensitive credentials belong strictly on the server.
