This is in the context of a web firebase app using Stripe with firebase functions.
"dependencies": {
"stripe": "^17.2.0",
"twitter-api-v2": "^1.18.0",
"firebase-admin": "^12.4.0",
"firebase-functions": "^6",
"moment-timezone": "^0.5.45"
},
npm -g => firebase-tools@13.22.0
All was working fine until I updated all packages to the version shown above. Since then, when I deploy firebase functions (how come this error is not just a runtime error ??), I get error message:
Error: Neither apiKey nor config.authenticator provided
at Stripe._setAuthenticator (C:\Users\webko\Documents\AppsAndWebsites\Node\robot\functions\node_modules\stripe\cjs\stripe.core.js:166:23)
at new Stripe (C:\Users\webko\Documents\AppsAndWebsites\Node\robot\functions\node_modules\stripe\cjs\stripe.core.js:102:14)
at Stripe (C:\Users\webko\Documents\AppsAndWebsites\Node\robot\functions\node_modules\stripe\cjs\stripe.core.js:58:20)
at Object.<anonymous> (C:\Users\webko\Documents\AppsAndWebsites\Node\robot\functions\index.js:37:33)
The line in question is this one:
const stripe = require('stripe')(process.env.STRIPE_SECRET);
Since the update, it refuses 'process.env.STRIPE_SECRET'. But works fine when I hardcode the test key as string.
The secret IS set in the environement, and when I run:
firebase functions:secrets:access STRIPE_SECRET
It correctly shows the secret.
So why passing the secret as 'process.env.STRIPE_SECRET' has now become a problem ?
I solved the issue by initializing Stripe inside the Firebase Cloud Function, rather than at the file's top level with other global imports:
exports.myFunction = functions.https.onCall(async (data, context) => {
const stripe = require('stripe')(process.env.STRIPE_SECRET); // Works
// Function code here
});
const stripe = require('stripe')(process.env.STRIPE_SECRET); // Does NOT Work
exports.myFunction = functions.https.onCall(async (data, context) => {
// Function code here
});
This approach seems necessary since Stripe version 17. While it used to work at the top level in earlier versions, this change actually aligns with best practices. It's more efficient to initialize Stripe only in functions that require it.
For those experiencing similar issues without Google Cloud Functions: check if the Stripe initialization is placed at the top level of your code. Moving it into the relevant function or method might resolve the problem.
Note: Always ensure your STRIPE_SECRET is securely stored in your environment variables.