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.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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:
Step 2: Separate Development and Production Keys
Always use separate keys for development and production environments:
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
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:
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:
Step 7: Use Restricted API Keys
Stripe allows you to create restricted API keys with limited permissions:
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:
Step 10: Monitor for Key Exposure
Set up monitoring to detect potential key exposure:
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:
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();
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.