fix: lazy-initialize Stripe client to prevent build-time errors
Stripe SDK was being initialized at module load time, which failed during Next.js build when STRIPE_SECRET_KEY wasn't set in the build environment. Changed to lazy initialization pattern with proxy object that creates the client on first access. Fixes: Error: Neither apiKey nor config.authenticator provided
This commit is contained in:
@@ -3,10 +3,33 @@
|
|||||||
|
|
||||||
import Stripe from "stripe";
|
import Stripe from "stripe";
|
||||||
|
|
||||||
// Initialize Stripe
|
// Lazy-initialize Stripe client to avoid build-time errors when env vars aren't set
|
||||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
|
let _stripe: Stripe | null = null;
|
||||||
apiVersion: "2026-05-27.dahlia",
|
|
||||||
});
|
function getStripeClient(): Stripe {
|
||||||
|
if (!_stripe) {
|
||||||
|
if (!process.env.STRIPE_SECRET_KEY) {
|
||||||
|
throw new Error("STRIPE_SECRET_KEY environment variable is not set");
|
||||||
|
}
|
||||||
|
_stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
|
||||||
|
apiVersion: "2026-05-27.dahlia",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return _stripe;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export stripe proxy that lazily initializes
|
||||||
|
export const stripe = {
|
||||||
|
get customers() { return getStripeClient().customers; },
|
||||||
|
get subscriptions() { return getStripeClient().subscriptions; },
|
||||||
|
get invoices() { return getStripeClient().invoices; },
|
||||||
|
get checkout() { return getStripeClient().checkout; },
|
||||||
|
get billingPortal() { return getStripeClient().billingPortal; },
|
||||||
|
get paymentMethods() { return getStripeClient().paymentMethods; },
|
||||||
|
get paymentIntents() { return getStripeClient().paymentIntents; },
|
||||||
|
get refunds() { return getStripeClient().refunds; },
|
||||||
|
get webhooks() { return getStripeClient().webhooks; },
|
||||||
|
};
|
||||||
|
|
||||||
// Plan tier configurations
|
// Plan tier configurations
|
||||||
export const PLANS = {
|
export const PLANS = {
|
||||||
@@ -667,8 +690,6 @@ export async function getUsageSummary(subscriptionItemId: string) {
|
|||||||
// EXPORT STRIPE INSTANCE AND HELPERS
|
// EXPORT STRIPE INSTANCE AND HELPERS
|
||||||
// ============================================
|
// ============================================
|
||||||
|
|
||||||
export { stripe };
|
|
||||||
|
|
||||||
export async function getSubscription(subscriptionId: string) {
|
export async function getSubscription(subscriptionId: string) {
|
||||||
return await stripe.subscriptions.retrieve(subscriptionId);
|
return await stripe.subscriptions.retrieve(subscriptionId);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user