I'm working on project that use Stripe for payments, framework this project uses is SvelteKit and for convenience I also use TS.
I implemented Stripe payments, tested locally, everything worked fine, then I deployed project to Firebase cloud functions and then 1st error showed up. Endpoint for creating payment intents failed every time I called it (but only in FB cloud function, it never failed locally).
So I decided (not just because of this bug) to move function for generating payment intents to one of my __layout.svelte, where it can be called from front-end and executed on back-end without need to make HTTP request to endpoint that is exposed to whole internet.
import Stripe from "stripe";
console.log('secret defined:', import.meta.env.VITE_STRIPE_SECRET_KEY);
const stripe = new Stripe(import.meta.env.VITE_STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27',
});
console.log('after stripe conf');
export default stripe;
I moved that function to desired __layout.svelte and got error EventEmitter is not a constructor
.
Then I found this question, and did what answer advised. Then I got different error:
http.Agent is not a constructor
.
Well, this is quite difficult problem, it is related to Vite. Stripe API for back-end is written in CJS and Vite has problems with processing CJS code when using SSR. According to docs I should include stripe for optimization, but that didn't work. These Github issues better describe this problem: Svelte issue Vite issue.
I'm lucky enough that I use Firebase, so I fixed this by moving function for generating payment intents to Cloud Functions. So this is solution for me, and not for everyone, but I hope this will help someone.