The Stripe API key invalid error occurs when your secret key (sk_) or publishable key (pk_) is revoked, expired, or from the wrong environment. Fix it by verifying your key in the Stripe Dashboard, ensuring test keys are used in development and live keys in production, storing keys in environment variables, and rotating compromised keys immediately.
Why Your Stripe API Key Is Invalid
Stripe returns an 'Invalid API Key provided' error when the key you send doesn't match any active key in your Stripe account. This usually happens because the key was revoked, you mixed up test and live keys, the key has leading/trailing whitespace, or the environment variable isn't loaded correctly. This error blocks all API calls, so fixing it is urgent.
Prerequisites
- A Stripe account with access to the Developers section
- Node.js 18+ installed
- The dotenv package for environment variable management
Step-by-step guide
Check your key in the Stripe Dashboard
Check your key in the Stripe Dashboard
Go to Stripe Dashboard → Developers → API keys. Verify that the key you're using matches an active key. Toggle between 'Test mode' and 'Live mode' using the switch at the top. The key prefix tells you which environment it belongs to: sk_test_ for test mode, sk_live_ for live mode.
Expected result: You can see your active API keys and confirm whether your key is valid and matches the correct environment.
Verify test vs. live mode keys
Verify test vs. live mode keys
The most common cause of this error is using a test key (sk_test_) against the live API or vice versa. Ensure your server uses sk_test_ during development and sk_live_ in production. The publishable key follows the same pattern: pk_test_ and pk_live_.
1// Check which key is loaded2console.log('Key prefix:', process.env.STRIPE_SECRET_KEY?.substring(0, 8));3// Should output: sk_test_ (development) or sk_live_ (production)Expected result: The logged prefix confirms you're using the correct key type for your environment.
Store keys in environment variables properly
Store keys in environment variables properly
Never hard-code Stripe keys in your source code. Use a .env file locally and environment variables in production. Make sure there are no leading or trailing spaces around the key value.
1# .env file2STRIPE_SECRET_KEY=sk_test_51ABC123...3STRIPE_PUBLISHABLE_KEY=pk_test_51ABC123...45# Do NOT add quotes around values — they become part of the string6# WRONG: STRIPE_SECRET_KEY="sk_test_51ABC123..."7# RIGHT: STRIPE_SECRET_KEY=sk_test_51ABC123...Expected result: Environment variables load cleanly without extra whitespace or quotes.
Load environment variables before initializing Stripe
Load environment variables before initializing Stripe
Ensure dotenv.config() runs before you create the Stripe client. If Stripe initializes before env vars load, it receives undefined instead of your key.
1// CORRECT order2require('dotenv').config();3const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);45// WRONG order — Stripe gets undefined6// const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);7// require('dotenv').config();Expected result: Stripe initializes with the correct API key. API calls succeed without the invalid key error.
Rotate a compromised key
Rotate a compromised key
If your key was exposed (e.g., committed to a public repo), rotate it immediately. Go to Dashboard → Developers → API keys → Roll key. Stripe generates a new key and gives you a grace period where both old and new keys work. Update your environment variables with the new key.
Expected result: A new API key is generated. After updating all services, the old key is safely revoked.
Complete working example
1require('dotenv').config();23// Validate key before initializing4const secretKey = process.env.STRIPE_SECRET_KEY;56if (!secretKey) {7 throw new Error('STRIPE_SECRET_KEY environment variable is not set');8}910if (!secretKey.startsWith('sk_test_') && !secretKey.startsWith('sk_live_')) {11 throw new Error(12 `Invalid STRIPE_SECRET_KEY format. Expected sk_test_ or sk_live_ prefix, got: ${secretKey.substring(0, 8)}`13 );14}1516if (secretKey !== secretKey.trim()) {17 throw new Error('STRIPE_SECRET_KEY contains leading or trailing whitespace');18}1920const stripe = require('stripe')(secretKey);2122// Quick validation — make a lightweight API call23async function validateStripeKey() {24 try {25 await stripe.balance.retrieve();26 console.log('Stripe API key is valid');27 return true;28 } catch (err) {29 if (err.type === 'StripeAuthenticationError') {30 console.error('Stripe API key is invalid:', err.message);31 return false;32 }33 throw err;34 }35}3637module.exports = { stripe, validateStripeKey };Common mistakes when fixing Stripe API key invalid error
Why it's a problem: Mixing test and live API keys in the same request
How to avoid: Ensure sk_test_ keys are used only in development and sk_live_ keys only in production. Never mix them — a customer created with a test key doesn't exist in live mode.
Why it's a problem: Hard-coding the API key in source code
How to avoid: Store keys in environment variables. Use dotenv for local development and your hosting provider's secrets management for production.
Why it's a problem: Including quotes around the value in the .env file
How to avoid: Write STRIPE_SECRET_KEY=sk_test_... without quotes. Some .env parsers include the quotes as literal characters, corrupting the key.
Why it's a problem: Loading dotenv after initializing Stripe
How to avoid: Call require('dotenv').config() at the very top of your entry file, before any other imports that use environment variables.
Best practices
- Always use environment variables for API keys — never commit them to version control
- Add .env to your .gitignore file immediately when starting a project
- Validate the key format (prefix check) at startup to catch misconfiguration early
- Use separate Stripe accounts or restricted keys for staging environments
- Rotate keys immediately if they're ever exposed in a commit, log, or error message
- Use Stripe restricted keys with minimal permissions instead of the full secret key where possible
- If you work with a development partner like RapidDev, use restricted keys with scoped permissions rather than sharing your full secret key
Still stuck?
Copy one of these prompts to get a personalized, step-by-step explanation.
Write a Node.js module that initializes the Stripe SDK with proper environment variable validation. Check that the STRIPE_SECRET_KEY exists, has the correct prefix (sk_test_ or sk_live_), has no whitespace, and make a test API call to validate the key is active.
Create a Stripe initialization module in Node.js that validates the API key format and tests connectivity before the app starts. Include checks for missing key, wrong prefix, whitespace, and make a balance.retrieve() call to confirm the key works.
Frequently asked questions
What does 'Invalid API Key provided' mean in Stripe?
It means the API key you sent doesn't match any active key in your Stripe account. The key may be revoked, from the wrong environment (test vs. live), contain extra whitespace, or not be loaded from your environment variables correctly.
How do I find my Stripe API key?
Go to Stripe Dashboard → Developers → API keys. You'll see your publishable key (pk_) and secret key (sk_). Toggle between test and live mode to see the keys for each environment.
Can I use a test key for live transactions?
No. Test keys (sk_test_) only work with test mode data. Live keys (sk_live_) are required for real transactions. Using the wrong key type returns an invalid key or resource not found error.
How do I rotate my Stripe API key?
Go to Dashboard → Developers → API keys → click 'Roll key' next to the key you want to rotate. Stripe creates a new key and optionally keeps the old key active for a grace period so you can update your services without downtime.
My .env file has the correct key but Stripe still says invalid. Why?
Check three things: 1) dotenv.config() is called before Stripe is initialized, 2) the value has no surrounding quotes in the .env file, 3) there's no trailing whitespace. Print the key length and prefix to debug.
Should I use the publishable key or secret key on my server?
Always use the secret key (sk_) on your server. The publishable key (pk_) is for client-side/frontend use only (e.g., Stripe.js, Stripe Elements). Never expose your secret key to the browser.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation