№ 06
8 min read

Your API key is a password with a budget

The feature works. The page loads. The backend calls the external service and returns the right result.

The API key is in an environment variable. It is absent from the frontend code. The repository is private.

That feels like a reasonable place to finish.

Consider a routine release review of a Next.js application with a Django backend. A developer opens the browser, submits the form, and checks the result. Everything looks ready. Then the review takes a different turn: what happens when the external service does not answer?

For this walkthrough, replace the service with a local stub and use a dummy credential. Make the stub return an error. Open the failed request in the browser’s Network panel and read the response.

The page might show a polite message. The response underneath might tell a different story.

Now the review has a more useful question than whether the feature works:

What can leave this application when something goes wrong?

That question belongs in every release involving a secret API key. It applies to payment services, email providers, model APIs, and storage integrations. The provider changes. The responsibility stays with the application.

A key grants permission

A secret API key often works as a bearer credential: possession is enough to make requests within its permissions. For a paid service, those requests can also spend money.

It does not need to be cracked like a password hash. The practical problem is keeping the value private, limiting what it can do, and controlling the application that uses it.

Some services issue public or publishable keys specifically for browser use. Those have a different contract. Follow the provider’s documentation; this entry concerns credentials intended to remain secret.

An environment variable separates a credential from source code. It does not control every place the application can copy that value afterward.

Next.js: know what reaches the browser

In Next.js, a variable prefixed with NEXT_PUBLIC_ can be inlined into browser JavaScript at build time. A secret provider key never belongs behind that prefix. Changing the deployment variable afterward does not rewrite an existing bundle. Next.js environment-variable guidance

There is another trap: values declared through the env option in next.config.js are included in JavaScript bundles when referenced, regardless of the prefix. Keep secrets out of that option. Next.js configuration reference

For applications with a Next.js server, keep privileged integrations in server modules. Use import 'server-only' to make an accidental client import fail at build time. Return only the fields the browser needs. A Server Component can still disclose a secret if it renders the value or passes it to a Client Component. Next.js data-security guidance

For a statically exported Next.js frontend, the server does not remain running after the build. Put runtime provider calls behind Django or another backend. Server Components run during the build, and their output becomes downloadable HTML and navigation data. Inspect that output, too. Next.js static-export guidance

The intended flow is straightforward:

Browser → application backend → external service
Browser ← approved result    ← external service

The browser authenticates to your application. The backend uses its own credential with the external service. The provider key stays out of the browser’s requests and responses.

Django: production errors are part of the interface

Django’s development error pages are useful precisely because they show a lot: tracebacks, source excerpts, settings, and local variables. That information does not belong in a public response. Production must use DEBUG=False. Django deployment checklist

Debugging enabled does not mean every error contains every secret. The risk depends on the failure and the data captured in the report. That uncertainty is a reason to disable development diagnostics in production.

A small production-settings example:

import os
 
DEBUG = False
ALLOWED_HOSTS = ["api.example.com"]
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
PROVIDER_API_KEY = os.environ["PROVIDER_API_KEY"]

These are separate credentials. Django’s SECRET_KEY supports its signing mechanisms; a provider API key authorizes requests to that provider. Do not reuse one value for both purposes.

Required credentials should fail clearly at startup when missing. Avoid a working key hardcoded as a fallback. If other environments read DEBUG from a string, parse it explicitly: bool("False") is True in Python.

Run Django’s deployment checks using the actual production settings:

python manage.py check --deploy --settings=config.settings.production

Replace the module path with your own. These checks catch configuration problems; they cannot prove that your custom responses and logs are safe. Django deployment checks

For API failures, return a controlled message and a request identifier. Keep diagnostic detail in restricted, redacted reporting. Do not return str(exc) or forward an upstream error body without deciding what it contains. OWASP REST error-handling guidance

Django provides sensitive_variables and sensitive_post_parameters to help filter production error reports. Their default filtering depends on DEBUG=False; they do not sanitize arbitrary logging statements. Django also warns that filtering cannot guarantee a report contains no sensitive data. Restrict access to those reports. Django error-reporting guidance

Follow the request through the deployment

A frontend error handler can only sanitize responses that pass through it.

Suppose the deployment sends page requests to Next.js, but sends /api/ requests directly to Django. A Next.js handler cannot clean up an error on that second path. Review the reverse-proxy configuration alongside the application code. Nginx can pass upstream error responses through; replacing them requires deliberate configuration. Nginx proxy error handling

The backend should return safe errors itself. Proxy handling can add another layer of protection, but the application still needs a safe response contract.

Browser Developer Tools show what the server actually sent. A friendly message on the page does not change the response underneath it.

Logs can become another copy of the credential

Printing a key to confirm that configuration loaded is an easy debugging habit to acquire. So is dumping a request object when an integration fails.

Both can create copies in places with different access rules: terminal output, CI logs, monitoring tools, support exports, and backups.

Log selected fields instead: request identifier, operation, status, duration, and a safe failure category. Exclude authorization headers, secret values, and unreviewed request or response bodies. Apply redaction before data reaches the logging destination. Restrict access and retention there as well. OWASP logging guidance

When sharing an error for help, use the smallest relevant extract and dummy values. The same rule applies to a colleague, a support ticket, or an AI coding tool. The tool’s name does not make a live credential necessary context.

A private key can still fund a public endpoint

There is a separate failure worth planning for: the key remains private, but someone repeatedly calls an application endpoint that spends it.

Protect paid operations with authentication and authorization appropriate to the feature. Validate inputs, bound request sizes, and limit concurrency and work per request. For deliberately public features, define an explicit abuse budget and enforce tighter limits. OWASP REST security guidance

CORS controls browser access; it is not authentication and does not stop scripts from calling an endpoint. A hidden button is not an access control.

Django REST framework throttling helps implement usage policy, but its built-in throttles are not a guarantee against malicious traffic or a precise financial ceiling. The documentation describes concurrency limitations. Combine them with suitable gateway controls and application quotas. DRF throttling guidance

Monitor usage and spend. Check whether a provider’s budget setting actually stops requests or only sends an alert. An alert tells you to act; it does not necessarily stop the bill.

Make replacement routine

Give development, staging, and production separate credentials. Use distinct keys for distinct services where supported, and grant only the permissions each needs. Keep a record of the owner and deployments using each credential. OWASP secrets-management guidance

For local development, an ignored environment file is a practical starting point. Commit a placeholder-only example. For production, use a controlled secret store or protected deployment configuration. Keep environment files, logs, backups, and credentials out of public asset directories and images distributed to users.

Practise rotation: create a replacement, update every consumer, restart or redeploy where required, verify the new credential, and revoke the old one. Routine rotation can allow a short overlap. If compromise is suspected, prompt revocation may take priority over avoiding downtime. Deleting a value from a file does not invalidate the credential. OWASP secret lifecycle guidance

Return to the release review

The developer in the opening walkthrough has one more job before deployment: inspect how the feature fails.

Use dummy credentials and local stubs. Exercise malformed input, unauthorized requests, upstream errors, and timeouts under production-like settings. Inspect the complete HTTP response and the resulting logs. Search the generated frontend assets for the dummy credential, too.

A dummy value in an output identifies a path to fix. Its absence from one test does not prove every path is safe. Test the paths your application actually uses, including the routing in front of it.

A practical release review asks:

  • Does the secret stay out of browser bundles, rendered output, and responses?
  • Does Django run with production settings and return controlled errors?
  • Are logs and shared debugging extracts free of credentials?
  • Can callers use paid operations only within the intended permissions and limits?
  • Can the credential be replaced without a search through every deployment?

The successful request proves the integration works.

The failed request tells you whether it is ready to leave your laptop.