Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Lazy-load Stripe SDK so it only loads on checkout (#6546)

Anthony Stirling66f431a2b7e9
diff --git a/frontend/editor/src/core/tests/stubbed/stripe-lazy-load.spec.ts b/frontend/editor/src/core/tests/stubbed/stripe-lazy-load.spec.ts
new file mode 100644
index 0000000000..561f0d1bc8
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/stripe-lazy-load.spec.ts
@@ -0,0 +1,81 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+/**
+ * Verifies that the Stripe SDK (@stripe/stripe-js, @stripe/react-stripe-js,
+ * and the js.stripe.com remote script) is NOT fetched on cold page loads —
+ * only when the checkout modal actually mounts. The proprietary
+ * CheckoutProvider, the SaaS TrialStatusBanner, and the SaaS Plan settings
+ * page all gate the modal behind React.lazy + a conditional render so the
+ * Stripe chunk lives in its own async bundle.
+ */
+
+const STRIPE_URL_FRAGMENTS = [
+ "js.stripe.com",
+ "@stripe/stripe-js",
+ // Vite's optimizeDeps id mangles slashes to underscores when serving
+ // pre-bundled dependencies from node_modules/.vite/deps.
+ "@stripe_stripe-js",
+ "@stripe/react-stripe-js",
+ "@stripe_react-stripe-js",
+];
+
+function isStripeRequest(url: string): boolean {
+ return STRIPE_URL_FRAGMENTS.some((fragment) => url.includes(fragment));
+}
+
+test.describe("Stripe SDK lazy loading", () => {
+ test("landing page does not fetch Stripe SDK on cold load", async ({
+ page,
+ }) => {
+ const stripeRequests: string[] = [];
+ page.on("request", (req) => {
+ const url = req.url();
+ if (isStripeRequest(url)) {
+ stripeRequests.push(url);
+ }
+ });
+
+ // The stub fixture already navigated to "/" with waitUntil:
+ // domcontentloaded. Wait for the app to actually settle so any lurking
+ // module-eval-time loadStripe() call would have already kicked off.
+ await page
+ .waitForLoadState("networkidle", { timeout: 15_000 })
+ .catch(() => {
+ // Posthog / iconify keep some connections warm — fall back to a
+ // brief settle window if networkidle never resolves.
+ });
+ await page.waitForTimeout(2_000);
+
+ expect(
+ stripeRequests,
+ `Expected no Stripe-related network activity on landing, but observed:\n${stripeRequests.join("\n")}`,
+ ).toEqual([]);
+ });
+
+ test("settings modal does not fetch Stripe SDK", async ({ page }) => {
+ const stripeRequests: string[] = [];
+ page.on("request", (req) => {
+ const url = req.url();
+ if (isStripeRequest(url)) {
+ stripeRequests.push(url);
+ }
+ });
+
+ // Opening Settings is the closest a default proprietary user gets to
+ // checkout without actually clicking Upgrade. Even rendering the
+ // settings drawer must NOT pull Stripe into the entry path — only the
+ // upgrade modal itself, which sits one click further in.
+ const settingsButton = page
+ .getByRole("button", { name: /settings/i })
+ .first();
+ if (await settingsButton.isVisible({ timeout: 5_000 }).catch(() => false)) {
+ await settingsButton.click();
+ await page.waitForTimeout(1_500);
+ }
+
+ expect(
+ stripeRequests,
+ `Expected no Stripe-related network activity after opening settings, but observed:\n${stripeRequests.join("\n")}`,
+ ).toEqual([]);
+ });
+});
diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx
index 45912667fb..e050114bee 100644
--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx
+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx
@@ -4,6 +4,8 @@ import React, {
useState,
useCallback,
useEffect,
+ lazy,
+ Suspense,
ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
@@ -13,7 +15,12 @@ import licenseService, {
mapLicenseToTier,
PlanTier,
} from "@app/services/licenseService";
-import { StripeCheckout } from "@app/components/shared/stripeCheckout";
+
+const StripeCheckout = lazy(() =>
+ import("@app/components/shared/stripeCheckout").then((m) => ({
+ default: m.StripeCheckout,
+ })),
+);
import { userManagementService } from "@app/services/userManagementService";
import { alert } from "@app/components/toast";
import {
@@ -433,16 +440,18 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({
{/* Global Checkout Modal */}
{selectedPlanGroup && (
- <StripeCheckout
- opened={isOpen}
- onClose={closeCheckout}
- planGroup={selectedPlanGroup}
- minimumSeats={minimumSeats}
- onSuccess={handlePaymentSuccess}
- onError={handlePaymentError}
- onLicenseActivated={handleLicenseActivated}
- hostedCheckoutSuccess={hostedCheckoutSuccess}
- />
+ <Suspense fallback={null}>
+ <StripeCheckout
+ opened={isOpen}
+ onClose={closeCheckout}
+ planGroup={selectedPlanGroup}
+ minimumSeats={minimumSeats}
+ onSuccess={handlePaymentSuccess}
+ onError={handlePaymentError}
+ onLicenseActivated={handleLicenseActivated}
+ hostedCheckoutSuccess={hostedCheckoutSuccess}
+ />
+ </Suspense>
)}
</CheckoutContext.Provider>
);
diff --git a/frontend/editor/src/saas/components/TrialExpiredBootstrap.tsx b/frontend/editor/src/saas/components/TrialExpiredBootstrap.tsx
index 1b185684cb..40826f1904 100644
--- a/frontend/editor/src/saas/components/TrialExpiredBootstrap.tsx
+++ b/frontend/editor/src/saas/components/TrialExpiredBootstrap.tsx
@@ -1,7 +1,10 @@
-import { useEffect, useState } from "react";
+import { lazy, Suspense, useEffect, useState } from "react";
import { useAuth } from "@app/auth/UseSession";
import { TrialExpiredModal } from "@app/components/shared/TrialExpiredModal";
-import StripeCheckout from "@app/components/shared/StripeCheckoutSaas";
+
+const StripeCheckout = lazy(
+ () => import("@app/components/shared/StripeCheckoutSaas"),
+);
/**
* Bootstrap component that shows the trial expired modal when a user's trial has ended
@@ -106,20 +109,22 @@ export default function TrialExpiredBootstrap() {
onSubscribe={handleSubscribe}
/>
- {user && (
- <StripeCheckout
- opened={checkoutOpened}
- onClose={handleCheckoutClose}
- purchaseType="subscription"
- planId="pro"
- creditsPack={null}
- planName="Pro"
- onSuccess={handleCheckoutSuccess}
- onError={(error) =>
- console.error("[TrialExpired] Checkout error:", error)
- }
- isTrialConversion={false} // Trial already ended, so this is not a conversion
- />
+ {user && checkoutOpened && (
+ <Suspense fallback={null}>
+ <StripeCheckout
+ opened={checkoutOpened}
+ onClose={handleCheckoutClose}
+ purchaseType="subscription"
+ planId="pro"
+ creditsPack={null}
+ planName="Pro"
+ onSuccess={handleCheckoutSuccess}
+ onError={(error) =>
+ console.error("[TrialExpired] Checkout error:", error)
+ }
+ isTrialConversion={false} // Trial already ended, so this is not a conversion
+ />
+ </Suspense>
)}
</>
);
diff --git a/frontend/editor/src/saas/components/shared/TrialStatusBanner.tsx b/frontend/editor/src/saas/components/shared/TrialStatusBanner.tsx
index e6e7322ec2..7efec40eb4 100644
--- a/frontend/editor/src/saas/components/shared/TrialStatusBanner.tsx
+++ b/frontend/editor/src/saas/components/shared/TrialStatusBanner.tsx
@@ -1,11 +1,14 @@
-import { useEffect, useState, useCallback } from "react";
+import { lazy, Suspense, useEffect, useState, useCallback } from "react";
import { useBanner } from "@app/contexts/BannerContext";
import { useAuth } from "@app/auth/UseSession";
import { useTranslation } from "react-i18next";
import { InfoBanner } from "@app/components/shared/InfoBanner";
-import StripeCheckout from "@app/components/shared/StripeCheckoutSaas";
import { BASE_PATH } from "@app/constants/app";
+const StripeCheckout = lazy(
+ () => import("@app/components/shared/StripeCheckoutSaas"),
+);
+
const SESSION_STORAGE_KEY = "trialBannerDismissed";
export function TrialStatusBanner() {
@@ -113,18 +116,20 @@ export function TrialStatusBanner() {
return (
<>
- {trialStatus && (
- <StripeCheckout
- opened={checkoutOpen}
- onClose={() => setCheckoutOpen(false)}
- purchaseType="subscription"
- planId="pro"
- creditsPack={null}
- planName="Pro"
- onSuccess={handleCheckoutSuccess}
- onError={(error) => console.error("Checkout error:", error)}
- isTrialConversion={true}
- />
+ {trialStatus && checkoutOpen && (
+ <Suspense fallback={null}>
+ <StripeCheckout
+ opened={checkoutOpen}
+ onClose={() => setCheckoutOpen(false)}
+ purchaseType="subscription"
+ planId="pro"
+ creditsPack={null}
+ planName="Pro"
+ onSuccess={handleCheckoutSuccess}
+ onError={(error) => console.error("Checkout error:", error)}
+ isTrialConversion={true}
+ />
+ </Suspense>
)}
</>
);
diff --git a/frontend/editor/src/saas/components/shared/config/configSections/Plan.tsx b/frontend/editor/src/saas/components/shared/config/configSections/Plan.tsx
index af7dcb2f83..8571c5db47 100644
--- a/frontend/editor/src/saas/components/shared/config/configSections/Plan.tsx
+++ b/frontend/editor/src/saas/components/shared/config/configSections/Plan.tsx
@@ -1,11 +1,15 @@
-import React, { useState, useCallback, useEffect } from "react";
+import React, { lazy, Suspense, useState, useCallback, useEffect } from "react";
import { Divider, Loader, Alert, Select, Group, Text } from "@mantine/core";
import { usePlans, PlanTier } from "@app/hooks/usePlans";
-import StripeCheckout, {
+import type {
PurchaseType,
CreditsPack,
PlanID,
} from "@app/components/shared/StripeCheckoutSaas";
+
+const StripeCheckout = lazy(
+ () => import("@app/components/shared/StripeCheckoutSaas"),
+);
import AvailablePlansSection from "@app/components/shared/config/configSections/plan/AvailablePlansSection";
import ApiPackagesSection from "@app/components/shared/config/configSections/plan/ApiPackagesSection";
import ActivePlanSection from "@app/components/shared/config/configSections/plan/ActivePlanSection";
@@ -204,29 +208,36 @@ const Plan: React.FC = () => {
/>
{/* Stripe Checkout Modal */}
- <StripeCheckout
- opened={
- checkoutOpen &&
- (selectedPlan !== null || selectedCreditsPack !== null)
- }
- onClose={handleCheckoutClose}
- purchaseType={purchaseType}
- planId={
- purchaseType === "subscription" ? (selectedPlan?.id as PlanID) : null
- }
- creditsPack={purchaseType === "credits" ? selectedCreditsPack : null}
- planName={
- purchaseType === "subscription"
- ? selectedPlan?.name || ""
- : data?.apiPackages.find((pkg) => pkg.id === selectedCreditsPack)
- ?.name || ""
- }
- onSuccess={handlePaymentSuccess}
- onError={handlePaymentError}
- isTrialConversion={
- trialStatus?.isTrialing && purchaseType === "subscription"
- }
- />
+ {checkoutOpen &&
+ (selectedPlan !== null || selectedCreditsPack !== null) && (
+ <Suspense fallback={null}>
+ <StripeCheckout
+ opened={true}
+ onClose={handleCheckoutClose}
+ purchaseType={purchaseType}
+ planId={
+ purchaseType === "subscription"
+ ? (selectedPlan?.id as PlanID)
+ : null
+ }
+ creditsPack={
+ purchaseType === "credits" ? selectedCreditsPack : null
+ }
+ planName={
+ purchaseType === "subscription"
+ ? selectedPlan?.name || ""
+ : data?.apiPackages.find(
+ (pkg) => pkg.id === selectedCreditsPack,
+ )?.name || ""
+ }
+ onSuccess={handlePaymentSuccess}
+ onError={handlePaymentError}
+ isTrialConversion={
+ trialStatus?.isTrialing && purchaseType === "subscription"
+ }
+ />
+ </Suspense>
+ )}
</div>
);
};
diff --git a/frontend/editor/src/saas/components/shared/config/configSections/plan/ApiPackagesSection.tsx b/frontend/editor/src/saas/components/shared/config/configSections/plan/ApiPackagesSection.tsx
index 09e238be04..f707d5d9a9 100644
--- a/frontend/editor/src/saas/components/shared/config/configSections/plan/ApiPackagesSection.tsx
+++ b/frontend/editor/src/saas/components/shared/config/configSections/plan/ApiPackagesSection.tsx
@@ -1,7 +1,7 @@
import React from "react";
import { Button, Card, Text, Stack, Flex, Slider } from "@mantine/core";
import { useTranslation } from "react-i18next";
-import { CreditsPack } from "@app/components/shared/StripeCheckoutSaas";
+import type { CreditsPack } from "@app/components/shared/StripeCheckoutSaas";
interface ApiPackage {
id: string;