/stripe-guides

How to securely store Stripe secret keys?

Learn how to securely store Stripe secret keys with best practices: use environment variables, secret managers, access controls, key rotation, and monitoring to protect your data.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to securely store Stripe secret keys?

How to Securely Store Stripe Secret Keys: A Comprehensive Guide

 

Step 1: Understand the Importance of Secret Key Security

 

Stripe secret keys grant complete access to your account, including the ability to make charges, refunds, and access sensitive customer data. Protecting these keys should be a top priority. A compromised secret key can lead to:

  • Unauthorized charges and refunds
  • Customer data breaches
  • Financial losses
  • Damage to your business reputation
  • Potential legal consequences

 

Step 2: Separate Development and Production Keys

 

Always use separate keys for development and production environments:

  • Test keys (prefixed with "sk_test_") for development
  • Live keys (prefixed with "sk_live_") only for production

 

Step 3: Use Environment Variables

 

Never hardcode your Stripe secret keys in your application code. Instead, store them as environment variables:

For Node.js (using dotenv):

// Install dotenv
npm install dotenv

// In your .env file
STRIPE_SECRET_KEY=sk_live_1234567890abcdefghijklmn
STRIPE_PUBLISHABLE_KEY=pk_live_1234567890abcdefghijklmn

// In your application code
require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

For Python:

# Install python-dotenv
pip install python-dotenv

# In your .env file
STRIPE_SECRET_KEY=sk_live_1234567890abcdefghijklmn
STRIPE_PUBLISHABLE_KEY=pk_live_1234567890abcdefghijklmn

# In your application code
import os
from dotenv import load\_dotenv
import stripe

load\_dotenv()
stripe.api_key = os.getenv('STRIPE_SECRET\_KEY')

For PHP:

// Install vlucas/phpdotenv
composer require vlucas/phpdotenv

// In your .env file
STRIPE_SECRET_KEY=sk_live_1234567890abcdefghijklmn
STRIPE_PUBLISHABLE_KEY=pk_live_1234567890abcdefghijklmn

// In your application code
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(**DIR**);
$dotenv->load();

\Stripe\Stripe::setApiKey($_ENV['STRIPE_SECRET\_KEY']);

 

Step 4: Secure Your .env Files

 

  • Add .env files to your .gitignore to prevent them from being committed to your code repository
  • Create a template file (e.g., .env.example) with placeholder values for documentation
  • Restrict file permissions on your server (chmod 600 .env)

Example .gitignore entry:

# .gitignore
.env
.env.\*
!.env.example

 

Step 5: Use a Secret Management Service

 

For production environments, consider using a dedicated secret management service:

  • AWS Secrets Manager
  • Google Cloud Secret Manager
  • Azure Key Vault
  • HashiCorp Vault

Example using AWS Secrets Manager with Node.js:

// Install AWS SDK
npm install aws-sdk

// In your application code
const AWS = require('aws-sdk');
const secretsManager = new AWS.SecretsManager({
  region: 'us-east-1' // Your AWS region
});

async function getStripeKey() {
  try {
    const data = await secretsManager.getSecretValue({ SecretId: 'stripe/api-keys' }).promise();
    const secrets = JSON.parse(data.SecretString);
    return secrets.STRIPE_SECRET_KEY;
  } catch (error) {
    console.error('Error retrieving Stripe key:', error);
    throw error;
  }
}

async function initializeStripe() {
  const stripe = require('stripe')(await getStripeKey());
  // Your Stripe code here
}

initializeStripe();

 

Step 6: Implement Key Rotation

 

Regularly rotate your Stripe secret keys to minimize risk:

  • Create a new secret key in your Stripe Dashboard
  • Update your secret storage mechanism with the new key
  • Test that your application works with the new key
  • Revoke the old key in your Stripe Dashboard

 

Step 7: Use Restricted API Keys

 

Stripe allows you to create restricted API keys with limited permissions:

  1. Navigate to Stripe Dashboard → Developers → API keys
  2. Click "Create restricted key"
  3. Select only the necessary permissions for each service
  4. Use these restricted keys in your application instead of the full-access key

 

Step 8: Implement Server-Side Processing

 

Never expose secret keys to client-side code:

// INCORRECT (client-side exposure of secret key)
// Don't do this!
const stripeClient = new Stripe('sk_live_1234567890abcdefghijklmn');

// CORRECT (server-side API endpoint)
// Server-side code (Node.js/Express example)
app.post('/create-payment-intent', async (req, res) => {
  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount: req.body.amount,
      currency: 'usd',
      // Other payment details
    });
    
    // Return only the client secret to the frontend
    res.json({ clientSecret: paymentIntent.client\_secret });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

 

Step 9: Set Up Access Controls

 

Implement proper access controls for anyone who might access your secret keys:

  • Limit which team members have access to production keys
  • Implement multi-factor authentication for your Stripe account
  • Use role-based access control in your hosting environment
  • Audit access logs regularly

 

Step 10: Monitor for Key Exposure

 

Set up monitoring to detect potential key exposure:

  • Use tools like GitGuardian or TruffleHog to scan code repositories
  • Configure alerts for unusual activity in your Stripe account
  • Monitor access logs for your secret storage solutions

Example script to check for exposed Stripe keys in a repository:

#!/bin/bash
# Simple script to scan for Stripe keys in your codebase

echo "Scanning for potentially exposed Stripe keys..."

# Look for patterns that might be Stripe secret keys
grep -r --include="\*.{js,py,php,rb,java,html,jsx,ts,tsx}" "sk_live_" .
grep -r --include="\*.{js,py,php,rb,java,html,jsx,ts,tsx}" "sk_test_" .

echo "Scan complete. Any results above may indicate exposed keys."

 

Step 11: Implement a Key Breach Response Plan

 

Prepare for the worst by creating a response plan for key exposure:

  • Document steps to rotate keys immediately
  • Create a communication plan for affected stakeholders
  • Define responsibilities for security incident response
  • Regularly test your response procedure

 

Step 12: Use Configuration Validation

 

Implement validation to ensure keys are properly configured:

// Node.js example
function validateStripeConfiguration() {
  const secretKey = process.env.STRIPE_SECRET_KEY;
  
  if (!secretKey) {
    throw new Error('Stripe secret key is not configured');
  }
  
  if (process.env.NODE_ENV === 'production' && secretKey.startsWith('sk_test\_')) {
    throw new Error('Using test key in production environment');
  }
  
  if (process.env.NODE_ENV !== 'production' && secretKey.startsWith('sk_live\_')) {
    console.warn('WARNING: Using live key in non-production environment');
  }
  
  console.log('Stripe configuration validated successfully');
}

// Call this function during application startup
validateStripeConfiguration();

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022