Generating Custom Checkout Links via API
While you can copy static checkout URLs from the Lemon Squeezy dashboard, creating checkouts dynamically via the API allows you to prefill customer emails and attach custom metadata.
1. Checkout URL Generation Flow
graph TD
A[User clicks buy button] --> B[Server calls Lemon Squeezy API]
B --> C[Pass Variant ID and User ID custom metadata]
C --> D[API returns customized checkout link]
D --> E[Redirect customer to checkout page]2. Generating Checkouts via Node.js
To call Lemon Squeezy endpoints easily, install the official package:
# Install the Lemon Squeezy Node.js SDK
npm install @lemonsqueezy/lemonsqueezy.jsWrite a backend route or Server Action to generate the payment URL:
// src/services/lemonCheckout.ts
import { lemonSqueezySetup, createCheckout } from "@lemonsqueezy/lemonsqueezy.js";
// Initialize the SDK client
lemonSqueezySetup({
apiKey: process.env.LEMONSQUEEZY_API_KEY as string,
});
export async function getPaymentLink(userId: string, email: string, variantId: string) {
try {
const storeId = process.env.LEMONSQUEEZY_STORE_ID as string;
const response = await createCheckout(storeId, variantId, {
checkoutData: {
email: email, // Prefills user email in form fields
custom: {
userId: userId, // Pass through user identity metadata
},
},
productOptions: {
redirectUrl: "https://mycompany.com/payment-success",
},
});
if (response.error) {
throw new Error(response.error.message);
}
// Return the dynamic payment link URL string
return response.data?.data.attributes.url;
} catch (err: any) {
console.error("Failed to generate payment url:", err.message);
return null;
}
}3. Redirecting the Customer
Call this function inside a server component or action:
const paymentUrl = await getPaymentLink("user_abc123", "alex@gmail.com", "45678");
if (paymentUrl) {
// Redirect customer browser to Lemon Squeezy hosted checkout
redirect(paymentUrl);
}Published on Last updated: