# How to fix Stripe API key invalid error

- Tool: Stripe
- Difficulty: Intermediate
- Time required: 15 minutes
- Compatibility: Stripe API v2024-12+, Node.js 18+
- Last updated: March 2026

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

## Before you start

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

```
// Check which key is loaded
console.log('Key prefix:', process.env.STRIPE_SECRET_KEY?.substring(0, 8));
// 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.

```
# .env file
STRIPE_SECRET_KEY=sk_test_51ABC123...
STRIPE_PUBLISHABLE_KEY=pk_test_51ABC123...

# Do NOT add quotes around values — they become part of the string
# WRONG: STRIPE_SECRET_KEY="sk_test_51ABC123..."
# 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.

```
// CORRECT order
require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

// WRONG order — Stripe gets undefined
// const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
// 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 code example

File: `stripe-init.js`

```javascript
require('dotenv').config();

// Validate key before initializing
const secretKey = process.env.STRIPE_SECRET_KEY;

if (!secretKey) {
  throw new Error('STRIPE_SECRET_KEY environment variable is not set');
}

if (!secretKey.startsWith('sk_test_') && !secretKey.startsWith('sk_live_')) {
  throw new Error(
    `Invalid STRIPE_SECRET_KEY format. Expected sk_test_ or sk_live_ prefix, got: ${secretKey.substring(0, 8)}`
  );
}

if (secretKey !== secretKey.trim()) {
  throw new Error('STRIPE_SECRET_KEY contains leading or trailing whitespace');
}

const stripe = require('stripe')(secretKey);

// Quick validation — make a lightweight API call
async function validateStripeKey() {
  try {
    await stripe.balance.retrieve();
    console.log('Stripe API key is valid');
    return true;
  } catch (err) {
    if (err.type === 'StripeAuthenticationError') {
      console.error('Stripe API key is invalid:', err.message);
      return false;
    }
    throw err;
  }
}

module.exports = { stripe, validateStripeKey };
```

## Common mistakes

- **Mixing test and live API keys in the same request** — undefined Fix: 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.
- **Hard-coding the API key in source code** — undefined Fix: Store keys in environment variables. Use dotenv for local development and your hosting provider's secrets management for production.
- **Including quotes around the value in the .env file** — undefined Fix: Write STRIPE_SECRET_KEY=sk_test_... without quotes. Some .env parsers include the quotes as literal characters, corrupting the key.
- **Loading dotenv after initializing Stripe** — undefined Fix: 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

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

---

Source: https://www.rapidevelopers.com/stripe-guide/how-to-fix-stripe-api-key-invalid-error
© RapidDev — https://www.rapidevelopers.com/stripe-guide/how-to-fix-stripe-api-key-invalid-error
