Skip to content

Backend Secrets Management — Securing API Keys and Secrets in Backend Apps

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Backend Secrets Management. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Secrets management ensures API keys, database credentials, and certificates are stored and accessed securely.

// Secrets manager abstraction
class SecretsManager {
  constructor() {
    this.provider = this.detectProvider();
    this.cache = new Map();
  }

  detectProvider() {
    if (process.env.VAULT_ADDR) return new VaultProvider();
    if (process.env.AWS_REGION) return new AWSSecretsProvider();
    return new EnvProvider();  // Fallback to env vars
  }

  async getSecret(key) {
    if (this.cache.has(key)) {
      const cached = this.cache.get(key);
      if (cached.expiresAt > Date.now()) return cached.value;
    }

    const value = await this.provider.getSecret(key);
    this.cache.set(key, { value, expiresAt: Date.now() + 300000 });
    return value;
  }

  async rotateSecret(key, newValue) {
    const oldValue = await this.getSecret(key);
    await this.provider.setSecret(key, newValue);
    this.cache.delete(key);
    return oldValue;
  }
}

// HashiCorp Vault provider
class VaultProvider {
  constructor() {
    this.client = new VaultClient({
      apiAddress: process.env.VAULT_ADDR,
      token: process.env.VAULT_TOKEN
    });
  }

  async getSecret(key) {
    const result = await this.client.read(`secret/data/scanapp/${key}`);
    return result.data.data[key];
  }
}

// Encrypted environment config
function loadSecureConfig() {
  const encrypted = process.env.ENCRYPTED_CONFIG;
  if (!encrypted) return {};

  const decipher = crypto.createDecipheriv(
    'aes-256-gcm',
    Buffer.from(process.env.CONFIG_ENCRYPTION_KEY, 'hex'),
    Buffer.from(encrypted.slice(0, 32), 'hex')
  );

  const decrypted = Buffer.concat([
    decipher.update(Buffer.from(encrypted.slice(32), 'hex')),
    decipher.final()
  ]);

  return JSON.parse(decrypted.toString());
}

Centralized secrets management prevents credential leakage through code, logs, or configuration files.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro