Skip to main content
RapidDev - Software Development Agency
stripe-guide

How to fix Stripe API key invalid error

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.

What you'll learn

  • What causes Stripe API key invalid errors
  • How to find and verify your API keys in the Dashboard
  • How to properly store keys in environment variables
  • How to rotate keys without downtime
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate5 min read15 minutesStripe API v2024-12+, Node.js 18+March 2026RapidDev Engineering Team
TL;DR

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

1

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.

2

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_.

typescript
1// Check which key is loaded
2console.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.

3

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.

typescript
1# .env file
2STRIPE_SECRET_KEY=sk_test_51ABC123...
3STRIPE_PUBLISHABLE_KEY=pk_test_51ABC123...
4
5# Do NOT add quotes around values they become part of the string
6# 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.

4

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.

typescript
1// CORRECT order
2require('dotenv').config();
3const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
4
5// WRONG order — Stripe gets undefined
6// 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.

5

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

stripe-init.js
1require('dotenv').config();
2
3// Validate key before initializing
4const secretKey = process.env.STRIPE_SECRET_KEY;
5
6if (!secretKey) {
7 throw new Error('STRIPE_SECRET_KEY environment variable is not set');
8}
9
10if (!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}
15
16if (secretKey !== secretKey.trim()) {
17 throw new Error('STRIPE_SECRET_KEY contains leading or trailing whitespace');
18}
19
20const stripe = require('stripe')(secretKey);
21
22// Quick validation — make a lightweight API call
23async 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}
36
37module.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.

ChatGPT Prompt

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.

Stripe Prompt

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.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.