Keeping API Keys Out of Source Code: A Safer Configuration Workflow

An API key can be only a short string of characters, but it may grant access to private data, paid services, cloud resources, or administrative operations. If that key is copied into a source file and committed to a public repository, the exposure can be difficult to reverse.

Hardcoding credentials often begins as a shortcut. A developer wants to test an API, adds the key directly to a request, and moves on to the next task. Later, the same code is reused in a team project or deployed to production. The temporary shortcut becomes part of the application.

A safer approach separates application code from sensitive configuration and gives credentials a clear lifecycle. This makes development easier to maintain while reducing the chance that secrets appear in source control, logs, or build artifacts.

What Counts as a Secret?

A secret is information that should only be available to authorized users, applications, or services. Common examples include:

  • API keys and access tokens.
  • Database usernames and passwords.
  • Cloud provider credentials.
  • Private keys and certificates.
  • Signing keys and webhook secrets.
  • Service account credentials.

Not every configuration value is a secret. A public API endpoint, a display preference, or a non-sensitive feature flag may be safe to store with application code. The important distinction is whether disclosure could allow unauthorized access or expose protected information.

Separate Configuration From Application Code

Application code describes what a program does. Configuration describes values that may change between development, testing, and production environments.

For example, an application may connect to different database hosts in a local development environment and a production deployment. The connection details should not require editing the source code every time the application moves between environments.

The Twelve-Factor App methodology recommends storing deploy-specific configuration in the environment rather than embedding it in the codebase. This keeps credentials and other environment-specific values separate from the application’s logic.

Read the Twelve-Factor App configuration principle for a detailed explanation of this separation.

Use Environment Variables Carefully

Environment variables are a common way to provide configuration to an application at runtime. Instead of writing an API key directly into a source file, the application reads a named variable supplied by the deployment environment.

A simplified example in JavaScript might look like this:

const apiKey = process.env.SERVICE_API_KEY;

if (!apiKey) {
  throw new Error("Missing service API key");
}

The code references the variable name, not the actual secret. The deployment system or local development environment supplies the value when the application runs.

However, environment variables are not automatically secure. They may be visible to processes with sufficient access, included in diagnostic output, or exposed through poorly configured deployment tools. Avoid printing their values to logs, and do not place real secrets in Docker build arguments or hardcoded image definitions.

Keep Local Secret Files Out of Version Control

Some development projects use a local environment file to make testing easier. This can be convenient, but the file must not be committed to the repository if it contains real credentials.

Add local secret files to the project’s ignore rules, and provide a separate example file containing only placeholder names. For example, a repository might include a sample configuration file that lists required variables without including their actual values.

This helps new developers understand which settings are needed while keeping the credentials themselves outside the shared source tree.

Do not assume that a file is safe simply because it is hidden or has a name beginning with a dot. Version-control status and repository history should be checked before pushing changes.

Use a Secrets Manager for Production Systems

For production applications, a dedicated secrets manager or cloud platform secret store is often a better choice than manually maintaining credentials across multiple servers.

These systems can centralize storage, control which applications or people can retrieve a secret, record access activity, and support rotation. Some platforms can provide short-lived credentials rather than requiring an application to keep a long-lived key indefinitely.

The appropriate solution depends on the infrastructure. A small application may use a managed platform’s built-in secret storage, while a larger environment may require a dedicated service with access policies and auditing.

OWASP’s Secrets Management Cheat Sheet discusses centralized storage, access control, rotation, auditing, and the risks of exposing secrets through configuration and deployment systems.

Give Each Secret Only the Access It Needs

A credential should not have more permissions than the application requires. If a service only needs to read a particular set of records, its API key should not also be able to delete accounts or change billing settings.

Use separate credentials for development, testing, and production wherever the service supports it. This reduces the impact of a development key being exposed and makes it easier to revoke access without disrupting unrelated systems.

Review who and what can access each secret. A credential that is available to every developer, build job, and deployment environment has a larger exposure surface than one restricted to the service that needs it.

Plan for Rotation and Revocation

Secrets should have an understood lifecycle. A team should know how a credential is created, where it is stored, which applications use it, and how it can be replaced or revoked.

When rotating a key, create the replacement, update the application configuration, verify that the new credential works, and then revoke the old one according to the provider’s process. For services that support overlapping credentials, a short transition period can reduce downtime.

If a secret is exposed, do not rely on deleting the visible line from the latest version of the source file. The credential may remain in repository history, logs, build artifacts, or copied files. Revoke or rotate the exposed credential first, then investigate where it appeared and remove unnecessary copies.

Prevent Secrets From Reaching Logs

Debugging output is a common source of accidental exposure. A developer may log an entire request object to understand an API failure, not realizing that the object contains an authorization header.

Before logging request or configuration details, remove sensitive fields. Use redaction for tokens, passwords, authorization headers, and connection strings. Error reports should contain enough information to diagnose a problem without reproducing the secret itself.

Also check monitoring platforms, crash reports, CI/CD output, and support attachments. A secret can leak through systems that were never intended to store credentials.

Make Secure Configuration Part of the Project

A secure setup should be documented so that another developer can run the application without asking someone to send credentials through an informal channel. Explain which variables are required, where authorized developers obtain them, and which environments use separate credentials.

Include a safe example configuration, verify that secret files are ignored by version control, and add checks that fail clearly when required configuration is missing. Review the deployment pipeline to make sure secrets are injected at runtime rather than embedded in source code or container images.

Keeping API keys out of source code is not a one-time cleanup. It is a configuration practice that needs to be maintained as the application grows. When credentials have clear ownership, limited permissions, controlled storage, and a documented rotation process, accidental exposure becomes easier to prevent and easier to respond to.

← Back to Home