Guide
secret_key_required: Stripe says you used a publishable key
How this guide was made: Written with AI assistance and checked against the sources linked on this page.
Updated
Short answer
Stripe returns secret_key_required ("The API key provided is a publishable key, but a secret key is required.") when a server-only call, such as creating a Checkout Session, arrives with a pk_ key. Make that call from your server or an edge function with an sk_ or rk_ key stored as a server-only secret.
What it means
Stripe gives every account two kinds of keys, each with a test and a live version:
- Publishable key (
pk_test_...,pk_live_...). Safe to put in front-end code. It can identify your account and create tokens or PaymentMethods from card details, but it can't create charges or read account data. - Secret key (
sk_...) or restricted key (rk_...). Stripe's docs say only publishable keys are safe to expose, so these belong on a server. They do the real work: creating Checkout Sessions, PaymentIntents, subscriptions, refunds, and so on.
The error means one of those server-only actions was sent to Stripe with a pk_ key. Stripe's error-codes page describes it as "The API key provided is a publishable key, but a secret key is required." The code can be fine while the wrong key is in the wrong place, or the call itself runs in the browser, where only the publishable key is available.
Causes
| Cause | How to tell | Fix |
|---|---|---|
| The publishable key was pasted into the secret key variable | Your server secret (for example STRIPE_SECRET_KEY) holds a value that starts with pk_ | Replace it with the sk_ or rk_ key from the Stripe Dashboard API keys page |
| The two keys are swapped | The front-end variable starts with sk_ and the server variable starts with pk_ | Swap them back. Then rotate the secret key, because it was in browser code |
| The browser calls the Stripe API directly | Front-end code has fetch("https://api.stripe.com/...") or new Stripe(...) from the stripe Node package inside a React component, using a VITE_ or NEXT_PUBLIC_ key | Move that call into a server route or edge function and have the browser call your function |
| The server code reads the wrong variable | The server does new Stripe(process.env.VITE_STRIPE_PUBLISHABLE_KEY) or falls back to the publishable key when the secret one is empty | Read only the secret variable on the server and fail loudly if it is missing |
| The secret is set locally but not where the code runs | Works on your machine, fails after deploy; the hosting or function secrets list has no secret key, or has the pk_ value | Add the sk_ or rk_ key to the deployed environment's secrets |
How to fix it
1. Find the key Stripe received
Open Workbench in the Stripe Dashboard (https://dashboard.stripe.com/workbench) and open the request logs. Find the failed request with secret_key_required. Note the endpoint (for example POST /v1/checkout/sessions). That endpoint must be called from a server.
Then search your project for every Stripe key:
grep -rnE "(pk|sk|rk)_(test|live)_|STRIPE" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=.next .
Write down which variable holds which prefix. Server variables must hold sk_ or rk_. Browser variables must hold pk_ only.
2. Get the right key
In the Dashboard, open the API keys page (https://dashboard.stripe.com/apikeys). Check the sandbox/live toggle first: test keys only work with test prices and products, live keys with live ones.
- Sandbox: you can reveal the secret key.
- Live mode: you can reveal the default secret key Stripe created for you. A key you created yourself is shown only once. If you don't have it saved, create a new one. Stripe recommends a restricted key that has only the permissions your server code needs.
3. Store the secret key on the server only
Never give it a VITE_ or NEXT_PUBLIC_ prefix. Both tools copy those values into the JavaScript sent to every visitor.
Supabase Edge Functions:
supabase secrets set STRIPE_SECRET_KEY=sk_test_xxx
Or open Edge Function Secrets in the Supabase Dashboard, add STRIPE_SECRET_KEY, and save. Functions read new secrets right away, with no redeploy.
Next.js or a Node server: add it to .env.local (and to your host's environment settings for production):
STRIPE_SECRET_KEY=sk_test_xxx
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx
4. Move the Stripe call to the server
Option A: Supabase Edge Function (supabase/functions/create-checkout/index.ts):
import Stripe from "npm:stripe";
const secretKey = Deno.env.get("STRIPE_SECRET_KEY");
if (!secretKey || !/^(sk|rk)_/.test(secretKey)) {
throw new Error("STRIPE_SECRET_KEY is missing or is not a secret/restricted key");
}
const stripe = new Stripe(secretKey);
const cors = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
Deno.serve(async (req) => {
if (req.method === "OPTIONS") return new Response("ok", { headers: cors });
try {
const { priceId } = await req.json();
const origin = req.headers.get("origin") ?? "";
const session = await stripe.checkout.sessions.create({
mode: "payment", // use "subscription" for recurring prices
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${origin}/pricing`,
});
return new Response(JSON.stringify({ url: session.url }), {
headers: { ...cors, "Content-Type": "application/json" },
});
} catch (err) {
return new Response(JSON.stringify({ error: (err as Error).message }), {
status: 400,
headers: { ...cors, "Content-Type": "application/json" },
});
}
});
Deploy it:
supabase functions deploy create-checkout
Call it from the browser:
const { data, error } = await supabase.functions.invoke("create-checkout", {
body: { priceId: "price_xxx" },
});
if (error) throw error;
window.location.href = data.url;
Option B: Next.js route handler (app/api/checkout/route.ts):
import Stripe from "stripe";
export async function POST(req: Request) {
// Checked per request so a build without the secret doesn't fail.
const secretKey = process.env.STRIPE_SECRET_KEY;
if (!secretKey || !/^(sk|rk)_/.test(secretKey)) {
return Response.json(
{ error: "STRIPE_SECRET_KEY is missing or is not a secret/restricted key" },
{ status: 500 },
);
}
const stripe = new Stripe(secretKey);
const { priceId } = await req.json();
const origin = req.headers.get("origin") ?? "";
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${origin}/pricing`,
});
return Response.json({ url: session.url });
}
Browser side:
const res = await fetch("/api/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ priceId: "price_xxx" }),
});
const { url } = await res.json();
window.location.href = url;
5. Clean up the front end
- Delete any
fetch("https://api.stripe.com/...")calls and anyimport Stripe from "stripe"in browser components. - If the browser needs Stripe at all (for Elements), load it with the publishable key only:
loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY)orloadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY). - Remove any fallback such as
process.env.STRIPE_SECRET_KEY || process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY.
6. Rotate the secret key if it was ever in the browser
If an sk_ or rk_ key ever sat in a VITE_ or NEXT_PUBLIC_ variable, or in front-end code, treat it as exposed. On the API keys page, open the key's menu (⋯), choose Rotate key, and set Expiration to Now. Otherwise the old key keeps working for the grace period you pick (up to 7 days). Copy the new value into your server secret. Supabase functions pick it up right away; other hosts need a redeploy.
How to check it's fixed
- In sandbox mode, click your Buy or Subscribe button on the live site. You should land on the Stripe Checkout page.
- Pay with Stripe's test card
4242 4242 4242 4242, any future expiry date, any CVC. - In Workbench, the
POST /v1/checkout/sessionsrequest now shows status 200, with nosecret_key_required. - In your browser's DevTools, open Sources and search all files (Ctrl+Shift+F, or Cmd+Option+F on Mac) for
sk_live,sk_test,rk_liveandrk_test. You should find nothing. Onlypk_keys belong in the browser. - When you switch to live mode, repeat with live keys and live price IDs.
FAQ
Can I just put the secret key in the front end so it works?
No. Stripe's docs say only publishable keys are safe to expose. Anyone who opens your site can read a VITE_ or NEXT_PUBLIC_ value and use a secret key with full access to your Stripe account. Create the Checkout Session on a server or edge function instead.
I'm sure my server has the secret key. Why do I still get this error?
Check what the deployed code actually reads. Typical gaps: the secret is set locally but not in the hosting or function secrets; the variable name in code differs from the one you set; or a fallback picks up the publishable key when the secret is empty. Log the first 3 characters of the key on the server (never the whole key) to confirm it starts with sk_ or rk_.
Is this the same as a test/live mode mismatch?
No. Mode problems show up as livemode_mismatch or as a "No such price" error that says a similar object exists in the other mode. Stripe keeps test and live keys and objects apart. secret_key_required is about the type of key (publishable vs secret), not the mode. You can hit both, so check that the key type and the mode both match what you need.
Can VibeFix fix it for me?
Yes, for apps built in Lovable or any app whose code is on GitHub. The free check confirms the problem on your live app first. If you want it fixed, our AI agent finds the cause, fixes it in your code for $79 and tests your live app again. See pricing.
Sources
- <https://docs.stripe.com/error-codes>
- <https://docs.stripe.com/keys>
- <https://supabase.com/docs/guides/functions/secrets>
- <https://nextjs.org/docs/app/guides/environment-variables>
- <https://vite.dev/guide/env-and-mode>
Last checked: 16 November 2026.
VibeFix is independent. Supabase and Stripe are trademarks of their owners.
Want it fixed?
Our AI agent fixes it in your code for $79 and tests your live app again. If we can't complete your re-check, you get your money back.
It starts with a free check that confirms the problem on your live app, no account needed.
More guides · Shopify store accessibility · About · Your privacy choices