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.

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 typeExamplesWhere it belongsSafe in browser?
Server-side secretStripe secret key (sk_live_...), webhook secret (whsec_...), AI keys, SMS tokensEncrypted environment variables read only in backend routesNever
Public client keyStripe publishable key (pk_live_...), Maps browser key, analytics IDPublic client config or non-secret frontend settingsYes, domain-restricted
Environment flagApp base URL, feature toggle, support email, default currencyNon-secret environment config or constantsYes
Editable business settingStore hours, tax rate, active coupon percent, announcement textManaged relational table in CloudRead via API

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 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 categoryPreview valueLive valueRisk if mixed
Stripe paymentsTest keys (sk_test_..., whsec_test_...)Live keys (sk_live_..., whsec_live_...)Test clicks charge real cards or Live fails
Email or SMSSandbox key or test sender tokenVerified production domain sender keyTests email real buyers or burn quotas
AI providersLow-cap development keyProduction key with monthly spend capDev loops exhaust production rate limits
Shipping or CRMStaging workspace tokenProduction workspace tokenFake 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:

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

SymptomRoot causeExact fix
Works in Preview, fails with 500 on LiveSecret exists in Preview settings but was never added to LiveAdd the production value in Live settings with the exact matching variable name
External API returns 401 UnauthorizedTrailing whitespace copied with key, wrong environment key, or revoked tokenRe-copy without spaces and verify sandbox vs live endpoint URLs match the key
Key appears in browser DevToolsVariable used a public client prefix or ran inside a frontend componentRevoke the key immediately, move the call server-side, and remove client references
GitHub Secret Scanning blocks exportLiteral provider token exists in code or a local .env commitRevoke the key, delete hardcoded strings, verify .env* is gitignored, and re-export
Server reads `undefined` for secretSpelling or case mismatch between settings and backend routeMatch exact uppercase names across environment settings and server code

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog