Skip to content

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

♻️ Replace Stripe checkout API route with a server action (RAL-1273) (#2546)

Luke Vellabf059dc910b4
diff --git a/apps/web/src/app/api/stripe/checkout/route.ts b/apps/web/src/app/api/stripe/checkout/route.ts
deleted file mode 100644
index 42f567c5e..000000000
--- a/apps/web/src/app/api/stripe/checkout/route.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import { getProPricing, stripe } from "@rallly/billing";
-import { absoluteUrl } from "@rallly/utils/absolute-url";
-import type { NextRequest } from "next/server";
-import { NextResponse } from "next/server";
-import * as z from "zod";
-import type { CustomerMetadata } from "@/features/billing/schema";
-import { getActiveSpaceForUser } from "@/features/space/data";
-import type {
- SubscriptionCheckoutMetadata,
- SubscriptionMetadata,
-} from "@/features/subscription/schema";
-import { getCurrentUser } from "@/features/user/data";
-import type { UserDTO } from "@/features/user/schema";
-import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
-
-const inputSchema = z.object({
- period: z.enum(["monthly", "yearly"]).optional(),
- return_path: z.string().optional(),
-});
-
-export async function POST(request: NextRequest) {
- let user: UserDTO | null;
-
- try {
- user = await getCurrentUser();
- } catch (error) {
- if (!(error instanceof InvalidSessionError)) {
- throw error;
- }
- return NextResponse.json({ error: "User not found" }, { status: 404 });
- }
-
- if (!user) {
- return NextResponse.redirect(absoluteUrl("/login"), 303);
- }
-
- const space = await getActiveSpaceForUser(user.id);
-
- if (!space) {
- return NextResponse.json({ error: "Space not found" }, { status: 404 });
- }
-
- if (space.ownerId !== user.id) {
- return NextResponse.json(
- { error: "You need to be the owner of this space to upgrade it" },
- { status: 403 },
- );
- }
-
- const spaceId = space.id;
- const formData = await request.formData();
- const data = inputSchema.safeParse(Object.fromEntries(formData.entries()));
-
- if (!data.success) {
- return NextResponse.json(data.error, { status: 400 });
- }
-
- const { period, return_path } = data.data;
-
- let customerId: string;
-
- if (space.tier === "pro") {
- // User already has an active subscription. Take them to customer portal
- return NextResponse.redirect(absoluteUrl("/api/stripe/portal"), 303);
- }
-
- if (user.customerId) {
- customerId = user.customerId;
- } else {
- // create a new customer in stripe
- const customer = await stripe.customers.create(
- {
- email: user.email,
- name: user.name,
- metadata: {
- userId: user.id,
- } satisfies CustomerMetadata,
- },
- {
- idempotencyKey: `cust_create_${user.id}`,
- },
- );
-
- customerId = customer.id;
- }
-
- const proPricingData = await getProPricing();
-
- const checkoutSession = await stripe.checkout.sessions.create({
- success_url: absoluteUrl(
- return_path ?? "/api/stripe/portal?session_id={CHECKOUT_SESSION_ID}",
- ),
- cancel_url: absoluteUrl(return_path),
- customer: customerId,
- customer_update: {
- name: "auto",
- address: "auto",
- },
- mode: "subscription",
- allow_promotion_codes: true,
- billing_address_collection: "auto",
- tax_id_collection: {
- enabled: true,
- },
- metadata: {
- userId: user.id,
- spaceId,
- } satisfies SubscriptionCheckoutMetadata,
- subscription_data: {
- metadata: {
- userId: user.id,
- spaceId,
- } satisfies SubscriptionMetadata,
- },
- line_items: [
- {
- price:
- period === "yearly"
- ? proPricingData.yearly.id
- : proPricingData.monthly.id,
- quantity: 1,
- },
- ],
- automatic_tax: {
- enabled: true,
- },
- expires_at: Math.floor(Date.now() / 1000) + 30 * 60, // 30 minutes
- after_expiration: {
- recovery: {
- enabled: true,
- allow_promotion_codes: true,
- },
- },
- });
-
- if (checkoutSession.url) {
- // redirect to checkout session
- return NextResponse.redirect(checkoutSession.url, 303);
- }
-
- return NextResponse.json(
- { error: "Something went wrong while creating a checkout session" },
- { status: 500 },
- );
-}
diff --git a/apps/web/src/components/upgrade-button.tsx b/apps/web/src/components/upgrade-button.tsx
index 41f2abb1b..c0f3140fe 100644
--- a/apps/web/src/components/upgrade-button.tsx
+++ b/apps/web/src/components/upgrade-button.tsx
@@ -1,8 +1,11 @@
"use client";
import { Button } from "@rallly/ui/button";
-import React from "react";
+import { usePathname } from "next/navigation";
+import type React from "react";
+import { upgradeToProAction } from "@/features/billing/actions";
import { Trans } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
export const UpgradeButton = ({
children,
@@ -12,35 +15,24 @@ export const UpgradeButton = ({
annual?: boolean;
className?: string;
}>) => {
- const formRef = React.useRef<HTMLFormElement>(null);
+ const pathname = usePathname();
+ const upgradeToPro = useSafeAction(upgradeToProAction);
return (
- <form ref={formRef} method="POST" action="/api/stripe/checkout">
- <input
- type="hidden"
- name="period"
- value={annual ? "yearly" : "monthly"}
- />
- <input
- type="hidden"
- name="return_path"
- value={window.location.pathname}
- />
- <Button
- size="xl"
- className={className}
- variant="primary"
- onClick={(e) => {
- // 🐛 Since we have nested forms, we need to prevent the default
- // action of the button from being triggered so that we don't submit
- // the parent form.
- // TODO: Fix this by making sure we never have nested forms.
- e.preventDefault();
- formRef.current?.submit();
- }}
- >
- {children || <Trans i18nKey="upgradeToPro" defaults="Upgrade to Pro" />}
- </Button>
- </form>
+ <Button
+ type="button"
+ size="xl"
+ className={className}
+ variant="primary"
+ loading={upgradeToPro.isExecuting}
+ onClick={() => {
+ upgradeToPro.execute({
+ period: annual ? "yearly" : "monthly",
+ returnPath: pathname,
+ });
+ }}
+ >
+ {children || <Trans i18nKey="upgradeToPro" defaults="Upgrade to Pro" />}
+ </Button>
);
};
diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.ts
new file mode 100644
index 000000000..338223430
--- /dev/null
+++ b/apps/web/src/features/billing/actions.ts
@@ -0,0 +1,124 @@
+"use server";
+
+import { getProPricing, stripe } from "@rallly/billing";
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { redirect } from "next/navigation";
+import * as z from "zod";
+import type { CustomerMetadata } from "@/features/billing/schema";
+import { getActiveSpaceForUser } from "@/features/space/data";
+import type {
+ SubscriptionCheckoutMetadata,
+ SubscriptionMetadata,
+} from "@/features/subscription/schema";
+import { AppError } from "@/lib/errors";
+import { authActionClient } from "@/lib/safe-action/server";
+
+export const upgradeToProAction = authActionClient
+ .metadata({ actionName: "upgrade_to_pro" })
+ .inputSchema(
+ z.object({
+ period: z.enum(["monthly", "yearly"]).optional(),
+ returnPath: z.string().startsWith("/").optional(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ const space = await getActiveSpaceForUser(ctx.user.id);
+
+ if (!space) {
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: "Space not found",
+ });
+ }
+
+ if (space.ownerId !== ctx.user.id) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You need to be the owner of this space to upgrade it",
+ });
+ }
+
+ if (space.tier === "pro") {
+ // User already has an active subscription. Take them to customer portal
+ redirect("/api/stripe/portal");
+ }
+
+ const { period, returnPath } = parsedInput;
+
+ let customerId = ctx.user.customerId;
+
+ if (!customerId) {
+ const customer = await stripe.customers.create(
+ {
+ email: ctx.user.email,
+ name: ctx.user.name,
+ metadata: {
+ userId: ctx.user.id,
+ } satisfies CustomerMetadata,
+ },
+ {
+ idempotencyKey: `cust_create_${ctx.user.id}`,
+ },
+ );
+
+ customerId = customer.id;
+ }
+
+ const proPricingData = await getProPricing();
+
+ const checkoutSession = await stripe.checkout.sessions.create({
+ success_url: absoluteUrl(
+ returnPath ?? "/api/stripe/portal?session_id={CHECKOUT_SESSION_ID}",
+ ),
+ cancel_url: absoluteUrl(returnPath),
+ customer: customerId,
+ customer_update: {
+ name: "auto",
+ address: "auto",
+ },
+ mode: "subscription",
+ allow_promotion_codes: true,
+ billing_address_collection: "auto",
+ tax_id_collection: {
+ enabled: true,
+ },
+ metadata: {
+ userId: ctx.user.id,
+ spaceId: space.id,
+ } satisfies SubscriptionCheckoutMetadata,
+ subscription_data: {
+ metadata: {
+ userId: ctx.user.id,
+ spaceId: space.id,
+ } satisfies SubscriptionMetadata,
+ },
+ line_items: [
+ {
+ price:
+ period === "yearly"
+ ? proPricingData.yearly.id
+ : proPricingData.monthly.id,
+ quantity: 1,
+ },
+ ],
+ automatic_tax: {
+ enabled: true,
+ },
+ expires_at: Math.floor(Date.now() / 1000) + 30 * 60, // 30 minutes
+ after_expiration: {
+ recovery: {
+ enabled: true,
+ allow_promotion_codes: true,
+ },
+ },
+ });
+
+ if (!checkoutSession.url) {
+ throw new AppError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Something went wrong while creating a checkout session",
+ });
+ }
+
+ redirect(checkoutSession.url);
+ });