Security

How to Secure API Keys: Complete Guide for Developers

Learn the best practices for securing API keys in Node.js, Python, and Go. Prevent API key leaks and protect your production infrastructure.

OM Salunke
March 1, 2026
8 min read
Keywords:
how to secure api keysapi key securityapi key managementsecure api key storageprevent api key leaks

How to Secure API Keys: Complete Guide for Developers

API keys are the crown jewels of your application. They provide access to critical services like payment processors, cloud platforms, and third-party APIs. Yet many developers store them carelessly—in code repositories, environment files, or worse, hardcoded in production builds.

The Problem with Unsecured API Keys

Every day, hackers scan GitHub for exposed API keys. When they find one, they can:

  • Access your cloud infrastructure
  • Make unauthorized API calls
  • Drain your database
  • Access customer data

This costs companies thousands in minutes.

Best Practices for Securing API Keys

1. Never Commit API Keys to Git

The first rule: never commit secrets to your repository.

✅ Bad Example:

const apiKey = "sk-12345678901234567890"; // 🚨 DO NOT DO THIS

✅ Good Example:

const apiKey = process.env.API_KEY;

2. Use Environment Variables

Store secrets in environment variables that are loaded at runtime:

# .env.local (add to .gitignore)
API_KEY=sk_prod_123456789
DATABASE_PASSWORD=secret_password_here
STRIPE_KEY=sk_live_abc123

3. Use a Secrets Manager

For production, use a dedicated secrets manager like XtraSecurity, AWS Secrets Manager, or HashiCorp Vault:

// With XtraSecurity
const xtra = require('@xtrasecurity/sdk');
const apiKey = await xtra.getSecret('api-key-prod');

4. Rotate Keys Regularly

Never use the same API key forever. Rotate keys every:

  • 30 days for production
  • 7 days for high-risk services

5. Restrict Key Permissions

Create API keys with minimal permissions:

  • Only read access if write isn't needed
  • Restrict to specific IP addresses
  • Set expiration dates

6. Monitor Key Usage

Log all API key access and alert on unusual patterns.

How to Implement in Your Stack

Node.js with dotenv

require('dotenv').config();

const stripe = require('stripe')(process.env.STRIPE_API_KEY);

Python

import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.getenv('API_KEY')

Go

package main

import (
  "os"
)

func main() {
  apiKey := os.Getenv("API_KEY")
}

What to Do If You've Exposed a Key

  1. Immediately revoke the exposed key
  2. Generate a new key
  3. Update all services using the old key
  4. Check logs for unauthorized access
  5. If in public repository, contact the service provider

Conclusion

Securing API keys isn't optional—it's critical infrastructure security.

About the Author

OM Salunke is a security engineer with expertise in DevOps, cloud infrastructure, and secrets management. He has helped enterprise teams secure their infrastructure on AWS, Google Cloud, and Azure.