Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Move Stripe client initialization into apps/web behind the billing feature flag (#2697)

Luke Vella19b41a3d0bac
diff --git a/apps/web/src/app/api/stripe/buy-license/route.ts b/apps/web/src/app/api/stripe/buy-license/route.ts
index e90c1b1b7..6e820a75d 100644
--- a/apps/web/src/app/api/stripe/buy-license/route.ts
+++ b/apps/web/src/app/api/stripe/buy-license/route.ts
@@ -1,5 +1,6 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
+import { getStripe } from "@/features/billing/service";
import { createLicenseCheckoutSession } from "@/features/licensing/mutations";
import { licenseCheckoutProductSchema } from "@/features/licensing/schema";
@@ -8,7 +9,10 @@ export async function GET(request: NextRequest) {
request.nextUrl.searchParams.get("product"),
);
- const result = await createLicenseCheckoutSession({ product });
+ const result = await createLicenseCheckoutSession({
+ product,
+ stripe: getStripe(),
+ });
if ("url" in result) {
return NextResponse.redirect(result.url, 303);
diff --git a/apps/web/src/app/api/stripe/portal/route.ts b/apps/web/src/app/api/stripe/portal/route.ts
index 175c9145b..bade34a81 100644
--- a/apps/web/src/app/api/stripe/portal/route.ts
+++ b/apps/web/src/app/api/stripe/portal/route.ts
@@ -1,9 +1,9 @@
-import { stripe } from "@rallly/billing";
import * as Sentry from "@sentry/nextjs";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { createStripePortalSession } from "@/features/billing/mutations";
+import { getStripe } from "@/features/billing/service";
/**
* Checkout return endpoint. Stripe redirects the browser here after payment
@@ -21,7 +21,7 @@ export async function GET(request: NextRequest) {
let customerId: string;
try {
- const session = await stripe.checkout.sessions.retrieve(sessionId);
+ const session = await getStripe().checkout.sessions.retrieve(sessionId);
if (typeof session.customer !== "string") {
Sentry.captureException(new Error("Invalid customer ID in session"));
return NextResponse.json(
diff --git a/apps/web/src/app/api/stripe/webhook/route.ts b/apps/web/src/app/api/stripe/webhook/route.ts
index d2e145867..af822526c 100644
--- a/apps/web/src/app/api/stripe/webhook/route.ts
+++ b/apps/web/src/app/api/stripe/webhook/route.ts
@@ -1,8 +1,8 @@
import type { Stripe } from "@rallly/billing";
-import { stripe } from "@rallly/billing";
import * as Sentry from "@sentry/nextjs";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
+import { getStripe } from "@/features/billing/service";
import { handleStripeWebhookEvent } from "@/features/billing/webhook/mutations";
import { isSelfHosted } from "@/lib/constants";
import { withPostHog } from "@/lib/posthog";
@@ -30,7 +30,7 @@ const handler = async (request: NextRequest) => {
let event: Stripe.Event;
try {
- event = stripe.webhooks.constructEvent(body, sig, stripeSigningSecret);
+ event = getStripe().webhooks.constructEvent(body, sig, stripeSigningSecret);
} catch (err) {
Sentry.captureException(err);
return NextResponse.json(
diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.ts
index 362c9c1bc..74de07487 100644
--- a/apps/web/src/features/billing/actions.ts
+++ b/apps/web/src/features/billing/actions.ts
@@ -1,6 +1,6 @@
"use server";
-import { getProPricing, stripe } from "@rallly/billing";
+import { getProPricing } from "@rallly/billing";
import { absoluteUrl } from "@rallly/utils/absolute-url";
import { redirect } from "next/navigation";
import * as z from "zod";
@@ -10,6 +10,7 @@ import type {
SubscriptionCheckoutMetadata,
SubscriptionMetadata,
} from "@/features/billing/schema";
+import { getStripe } from "@/features/billing/service";
import { getActiveSpaceForUser } from "@/features/space/data";
import { AppError } from "@/lib/errors/app-error";
import { authActionClient } from "@/lib/safe-action/server";
@@ -63,6 +64,8 @@ export const upgradeToProAction = authActionClient
const { period, returnPath } = parsedInput;
+ const stripe = getStripe();
+
let customerId = ctx.user.customerId;
if (!customerId) {
@@ -82,7 +85,7 @@ export const upgradeToProAction = authActionClient
customerId = customer.id;
}
- const proPricingData = await getProPricing();
+ const proPricingData = await getProPricing({ stripe });
const checkoutSession = await stripe.checkout.sessions.create({
success_url: absoluteUrl(
diff --git a/apps/web/src/features/billing/mutations.ts b/apps/web/src/features/billing/mutations.ts
index 2ce8d955b..26b576bb7 100644
--- a/apps/web/src/features/billing/mutations.ts
+++ b/apps/web/src/features/billing/mutations.ts
@@ -1,12 +1,13 @@
import "server-only";
-import { getProPricing, stripe } from "@rallly/billing";
+import { getProPricing } from "@rallly/billing";
import {
SEAT_UPDATE_PORTAL_HEADLINE,
SEAT_UPDATE_PORTAL_PURPOSE,
SEAT_UPDATE_PORTAL_VERSION,
} from "@rallly/billing/lib/portal";
import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { getStripe } from "@/features/billing/service";
export async function createStripePortalSession({
customerId,
@@ -15,7 +16,7 @@ export async function createStripePortalSession({
customerId: string;
returnPath?: string;
}) {
- const portalSession = await stripe.billingPortal.sessions.create({
+ const portalSession = await getStripe().billingPortal.sessions.create({
customer: customerId,
return_url: absoluteUrl(returnPath),
});
@@ -23,7 +24,8 @@ export async function createStripePortalSession({
}
async function createSeatUpdateBillingConfig() {
- const pricing = await getProPricing();
+ const stripe = getStripe();
+ const pricing = await getProPricing({ stripe });
// Both monthly and yearly prices share the same product.
const monthlyPrice = await stripe.prices.retrieve(pricing.monthly.id);
@@ -77,7 +79,7 @@ async function resolveConfigurationId(): Promise<string> {
// Auto-paginate so a match isn't missed when many stale configs still exist
// (pre-cleanup). The current-version config is the newest, so this returns on
// the first page in practice.
- const configs = stripe.billingPortal.configurations.list({
+ const configs = getStripe().billingPortal.configurations.list({
active: true,
limit: 100,
});
@@ -125,7 +127,7 @@ export async function createStripeSubscriptionUpdateConfirmation({
}) {
const configurationId = await getSeatUpdatePortalConfigurationId();
- const portalSession = await stripe.billingPortal.sessions.create({
+ const portalSession = await getStripe().billingPortal.sessions.create({
customer: customerId,
configuration: configurationId,
return_url: absoluteUrl("/settings/billing"),
diff --git a/apps/web/src/features/billing/service.ts b/apps/web/src/features/billing/service.ts
new file mode 100644
index 000000000..0b2309c60
--- /dev/null
+++ b/apps/web/src/features/billing/service.ts
@@ -0,0 +1,26 @@
+import "server-only";
+
+import type { Stripe } from "@rallly/billing";
+import { createStripeClient } from "@rallly/billing";
+
+import { isBillingEnabled } from "@/features/billing/constants";
+
+let stripeClient: Stripe | undefined;
+
+export function getStripe() {
+ if (!isBillingEnabled) {
+ throw new Error("Stripe is unavailable because billing is disabled");
+ }
+
+ if (!stripeClient) {
+ const secretKey = process.env.STRIPE_SECRET_KEY;
+
+ if (!secretKey) {
+ throw new Error("STRIPE_SECRET_KEY must be set when billing is enabled");
+ }
+
+ stripeClient = createStripeClient({ secretKey });
+ }
+
+ return stripeClient;
+}
diff --git a/apps/web/src/features/billing/webhook/mutations.ts b/apps/web/src/features/billing/webhook/mutations.ts
index 3de202ac7..9e8d7394a 100644
--- a/apps/web/src/features/billing/webhook/mutations.ts
+++ b/apps/web/src/features/billing/webhook/mutations.ts
@@ -1,7 +1,6 @@
import "server-only";
import type { Stripe } from "@rallly/billing";
-import { stripe } from "@rallly/billing";
import type { Prisma } from "@rallly/database";
import { prisma } from "@rallly/database";
import { sendRawEmail } from "@rallly/emails";
@@ -14,6 +13,7 @@ import {
customerMetadataSchema,
subscriptionMetadataSchema,
} from "@/features/billing/schema";
+import { getStripe } from "@/features/billing/service";
import {
getSubscriptionDetails,
isSubscriptionActive,
@@ -24,7 +24,7 @@ import { licenseCheckoutMetadataSchema } from "@/features/licensing/schema";
import { identifyGroup, posthog } from "@/lib/posthog";
async function getExpandedSubscription(subscriptionId: string) {
- return stripe.subscriptions.retrieve(subscriptionId, {
+ return getStripe().subscriptions.retrieve(subscriptionId, {
expand: ["items.data.price.currency_options"],
});
}
@@ -330,6 +330,7 @@ async function onCustomerSubscriptionCreated(event: Stripe.Event) {
}
async function onCustomerSubscriptionDeleted(event: Stripe.Event) {
+ const stripe = getStripe();
const subscription = await stripe.subscriptions.retrieve(
(event.data.object as Stripe.Subscription).id,
);
diff --git a/apps/web/src/features/licensing/mutations.ts b/apps/web/src/features/licensing/mutations.ts
index 1e70767ef..ae383053f 100644
--- a/apps/web/src/features/licensing/mutations.ts
+++ b/apps/web/src/features/licensing/mutations.ts
@@ -1,6 +1,6 @@
import "server-only";
-import { stripe } from "@rallly/billing";
+import type { Stripe } from "@rallly/billing";
import { prisma } from "@rallly/database";
import { createLogger } from "@rallly/logger";
import { env } from "@/env";
@@ -138,8 +138,10 @@ const licenseCheckoutProducts: Record<
export async function createLicenseCheckoutSession({
product,
+ stripe,
}: {
product: LicenseCheckoutProduct;
+ stripe: Stripe;
}): Promise<{ url: string } | { error: string }> {
const { lookupKey, type, seats } = licenseCheckoutProducts[product];
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index a4887a7c9..bd37cb542 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -1,4 +1,3 @@
-import { stripe } from "@rallly/billing";
import type { TimeFormat } from "@rallly/database";
import { prisma } from "@rallly/database";
import { sendChangeEmailEmail } from "@rallly/emails/templates/change-email";
@@ -27,6 +26,7 @@ import { getInstanceBranding } from "@/emails/branding";
import { env } from "@/env";
import { linkAnonymousUser } from "@/features/auth/mutations";
import { isEmailBlocked, isTemporaryEmail } from "@/features/auth/utils";
+import { getStripe } from "@/features/billing/service";
import { createSpace } from "@/features/space/mutations";
import type { UserDTO } from "@/features/user/schema";
import { getTranslation } from "@/i18n/server";
@@ -425,7 +425,7 @@ export const authLib = betterAuth({
if (user?.customerId) {
try {
- await stripe.customers.update(user.customerId, {
+ await getStripe().customers.update(user.customerId, {
email: newEmail,
});
} catch (error) {
diff --git a/packages/billing/src/lib/stripe.ts b/packages/billing/src/lib/stripe.ts
index b8fe2cb60..34658d1b0 100644
--- a/packages/billing/src/lib/stripe.ts
+++ b/packages/billing/src/lib/stripe.ts
@@ -2,12 +2,14 @@ import Stripe from "stripe";
export type { Stripe } from "stripe";
-export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, {
- apiVersion: "2023-08-16",
- typescript: true,
-});
+export function createStripeClient({ secretKey }: { secretKey: string }) {
+ return new Stripe(secretKey, {
+ apiVersion: "2023-08-16",
+ typescript: true,
+ });
+}
-export async function getProPricing() {
+export async function getProPricing({ stripe }: { stripe: Stripe }) {
const prices = await stripe.prices.list({
lookup_keys: ["pro-monthly", "pro-yearly"],
});
diff --git a/packages/billing/src/scripts/checkout-expiry.ts b/packages/billing/src/scripts/checkout-expiry.ts
index b7ca97172..02a795d83 100644
--- a/packages/billing/src/scripts/checkout-expiry.ts
+++ b/packages/billing/src/scripts/checkout-expiry.ts
@@ -1,7 +1,15 @@
-import { getProPricing, stripe } from "../lib/stripe";
+import { createStripeClient, getProPricing } from "../lib/stripe";
+
+const secretKey = process.env.STRIPE_SECRET_KEY;
+
+if (!secretKey) {
+ throw new Error("STRIPE_SECRET_KEY is not set");
+}
+
+const stripe = createStripeClient({ secretKey });
async function createAndExpireCheckout() {
- const pricingData = await getProPricing();
+ const pricingData = await getProPricing({ stripe });
console.info("📝 Creating checkout session...");
const session = await stripe.checkout.sessions.create({
success_url: "http://localhost:3000/success",
diff --git a/packages/billing/src/scripts/cleanup-portal-configurations.ts b/packages/billing/src/scripts/cleanup-portal-configurations.ts
index 6bb1bf32b..e60839370 100644
--- a/packages/billing/src/scripts/cleanup-portal-configurations.ts
+++ b/packages/billing/src/scripts/cleanup-portal-configurations.ts
@@ -2,7 +2,15 @@ import {
SEAT_UPDATE_PORTAL_HEADLINE,
SEAT_UPDATE_PORTAL_VERSION,
} from "../lib/portal";
-import { stripe } from "../lib/stripe";
+import { createStripeClient } from "../lib/stripe";
+
+const secretKey = process.env.STRIPE_SECRET_KEY;
+
+if (!secretKey) {
+ throw new Error("STRIPE_SECRET_KEY is not set");
+}
+
+const stripe = createStripeClient({ secretKey });
/**
* Before the seat-update flow reused a single billing portal configuration, it
diff --git a/packages/billing/src/scripts/invoice-pending-prorations.ts b/packages/billing/src/scripts/invoice-pending-prorations.ts
index 8ded0ca2e..1c5363f3b 100644
--- a/packages/billing/src/scripts/invoice-pending-prorations.ts
+++ b/packages/billing/src/scripts/invoice-pending-prorations.ts
@@ -1,5 +1,13 @@
import type { Stripe } from "../lib/stripe";
-import { stripe } from "../lib/stripe";
+import { createStripeClient } from "../lib/stripe";
+
+const secretKey = process.env.STRIPE_SECRET_KEY;
+
+if (!secretKey) {
+ throw new Error("STRIPE_SECRET_KEY is not set");
+}
+
+const stripe = createStripeClient({ secretKey });
/**
* Remediation for seat changes made while the billing portal was configured with
diff --git a/packages/billing/src/scripts/subscription-data-sync.ts b/packages/billing/src/scripts/subscription-data-sync.ts
index 10ea8976b..a2e4bfc7d 100644
--- a/packages/billing/src/scripts/subscription-data-sync.ts
+++ b/packages/billing/src/scripts/subscription-data-sync.ts
@@ -1,6 +1,14 @@
import { prisma } from "@rallly/database";
-import { stripe } from "../lib/stripe";
+import { createStripeClient } from "../lib/stripe";
+
+const secretKey = process.env.STRIPE_SECRET_KEY;
+
+if (!secretKey) {
+ throw new Error("STRIPE_SECRET_KEY is not set");
+}
+
+const stripe = createStripeClient({ secretKey });
(async function syncSubscriptionData() {
let processed = 0;
diff --git a/packages/billing/src/scripts/sync-payment-methods.ts b/packages/billing/src/scripts/sync-payment-methods.ts
index f15884e63..df4d0661d 100644
--- a/packages/billing/src/scripts/sync-payment-methods.ts
+++ b/packages/billing/src/scripts/sync-payment-methods.ts
@@ -1,7 +1,15 @@
import type { Prisma } from "@rallly/database";
import { prisma } from "@rallly/database";
-import { stripe } from "../lib/stripe";
+import { createStripeClient } from "../lib/stripe";
+
+const secretKey = process.env.STRIPE_SECRET_KEY;
+
+if (!secretKey) {
+ throw new Error("STRIPE_SECRET_KEY is not set");
+}
+
+const stripe = createStripeClient({ secretKey });
(async function syncPaymentMethods() {
let processed = 0;
diff --git a/packages/billing/src/scripts/sync-space-subscription.ts b/packages/billing/src/scripts/sync-space-subscription.ts
index 5e88433c3..41b21668a 100644
--- a/packages/billing/src/scripts/sync-space-subscription.ts
+++ b/packages/billing/src/scripts/sync-space-subscription.ts
@@ -1,6 +1,14 @@
import { prisma } from "@rallly/database";
-import { stripe } from "../lib/stripe";
+import { createStripeClient } from "../lib/stripe";
+
+const secretKey = process.env.STRIPE_SECRET_KEY;
+
+if (!secretKey) {
+ throw new Error("STRIPE_SECRET_KEY is not set");
+}
+
+const stripe = createStripeClient({ secretKey });
(async function syncSpaceSubscription() {
let processed = 0;