/how-to-build-lovable

How to build Subscription system with Lovable?

Build a scalable subscription system with Lovable using step-by-step guides for payments, recurring billing, user management and analytics

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to build Subscription system with Lovable?

 

Direct answer

 

Build a subscription flow inside Lovable by creating serverless API routes, frontend pages/components, and wiring Stripe + (optionally) Supabase via Lovable Cloud Secrets. Use Chat Mode to add or edit files (no terminal), set Secrets in Lovable Cloud for API keys, Preview to test the flow, and Publish to deploy. For webhook/local webhook testing you’ll need GitHub export + Stripe CLI outside Lovable — I’ll mark that clearly.

 

What we’re building / changing

 

  • Create a Stripe-backed subscription system with: Checkout session creation, webhook handler to reconcile subscriptions, frontend subscribe page, and a subscription status component. Optionally persist subscription state in Supabase.

 

Lovable-native approach

 

  • Use Chat Mode edits to create files (API routes and UI), Preview to try flows, and Publish to deploy. No terminal/CLI required for Stripe keys or Supabase keys — store them in Lovable Cloud Secrets.
  • If you need to run Stripe CLI for webhook testing, export to GitHub and run Stripe CLI from your local terminal — labeled “outside Lovable”.

 

Meta-prompts to paste into Lovable

 

Prompt 1 — Create Stripe + Supabase helpers and environment wiring

Goal: Add helpers and configuration files to talk to Stripe and Supabase (if using Supabase).

Exact files to create/modify:

  • create src/lib/stripe.ts
  • create src/lib/supabase.ts (only if using Supabase)
  • update src/env.d.ts or config where your app reads envs (if present)

Acceptance criteria (done when…):

  • src/lib/stripe.ts exports a configured Stripe instance that reads process.env.STRIPE_SECRET_KEY
  • src/lib/supabase.ts exports a Supabase client that reads process.env.SUPABASE_URL and process.env.SUPABASE_SERVICE\_KEY (if created)

Secrets/integration steps:

  • Open Lovable Cloud Secrets UI and add: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, SUPABASE_URL, SUPABASE_SERVICE\_KEY (if used)

Code examples inside prompt (for Lovable to create files):

// create src/lib/stripe.ts
// // initialize Stripe using process.env.STRIPE_SECRET_KEY

// create src/lib/supabase.ts
// // initialize Supabase using process.env.SUPABASE_URL and process.env.SUPABASE_SERVICE_KEY

 

Prompt 2 — Add serverless API routes: create-checkout-session and webhook

Goal: Create API routes to start Checkout and to receive Stripe webhooks.

Exact files to create:

  • create src/pages/api/create-checkout-session.ts
  • create src/pages/api/webhook.ts

Acceptance criteria:

  • POST /api/create-checkout-session returns a Checkout session URL or sessionId
  • /api/webhook verifies Stripe signature using process.env.STRIPE_WEBHOOK_SECRET and updates subscription status (calls Supabase client if available)

Notes:

  • Include comments in the handler describing where to update DB (Supabase) or user records.
  • Webhook testing with Stripe CLI is labeled outside Lovable (see bottom).

Code examples inside prompt:

// create src/pages/api/create-checkout-session.ts
// // implement POST handler that creates stripe.checkout.sessions.create with mode: 'subscription'

// create src/pages/api/webhook.ts
// // verify signature with stripe.webhooks.constructEvent and process invoice.payment_succeeded or customer.subscription.created

 

Prompt 3 — Add frontend: subscribe page and status component

Goal: Add UI to let signed-in users start a subscription and view status.

Exact files to create/modify:

  • create src/pages/subscribe.tsx (or src/routes/subscribe if your framework)
  • create src/components/SubscriptionStatus.tsx
  • update nav or account page to link to /subscribe

Acceptance criteria:

  • /subscribe shows a “Start subscription” button that POSTs to /api/create-checkout-session and redirects to Stripe Checkout
  • SubscriptionStatus fetches backend /api/user-subscription (or reads Supabase) to show active/expired and next invoice date

Code examples inside prompt:

// create src/pages/subscribe.tsx
// // fetch '/api/create-checkout-session' and redirect to returned url

// create src/components/SubscriptionStatus.tsx
// // show subscription state by calling a simple GET API that returns current subscription for the logged user

 

How to verify in Lovable Preview

 

  • Preview the /subscribe page, click Start subscription: you should receive a Stripe Checkout URL from the API and be redirected to stripe.com/checkout.
  • Simulate webhook events: in Preview you cannot run Stripe CLI webhooks into Lovable’s deployed URL unless published — test by publishing and using Stripe’s dashboard or use GitHub export + local Stripe CLI (outside Lovable) to forward to the published webhook endpoint.

 

How to Publish / re-publish

 

  • Use Lovable’s Publish button to deploy serverless endpoints. Ensure Secrets are set before publishing.
  • After Publish, register the published /api/webhook URL in Stripe Dashboard as the webhook endpoint and set STRIPE_WEBHOOK_SECRET in Lovable Secrets with the value Stripe gives you.

 

Common pitfalls in Lovable (and how to avoid them)

 

  • Missing Secrets: API routes will 500 if Secrets aren’t set—always add STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET in Lovable Cloud Secrets UI before Publish.
  • Webhook testing: You cannot run Stripe CLI inside Lovable. For local webhook testing, export to GitHub and run Stripe CLI locally (outside Lovable) or publish then use Stripe dashboard to send test events.
  • Assuming local file access: Lovable Preview runs deployed serverless handlers — don’t expect a terminal or local DB unless you integrated Supabase (use Supabase hosted DB via its keys).

 

Validity bar

 

  • This approach uses Lovable Chat edits, Preview, Publish, and the Cloud Secrets UI. It does not require an in-app terminal. Stripe CLI steps are explicitly labeled as outside Lovable.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

How to add a secure, idempotent subscription webhook in Lovable

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

How to process scheduled subscription plan changes in Lovable

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

How to add a Subscriptions Search API in Lovable

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Best Practices for Building a Subscription system with AI Code Generators

The most important best practice: enforce billing and quota checks on the server side, meter every generator call, keep secrets out of the browser (use Lovable Secrets / env in Cloud), wire Stripe webhooks to update subscription state, and use Lovable-native workflow (Chat edits, Preview, Publish, Secrets UI, GitHub sync) — don’t rely on a local CLI. Do metering in a durable DB (Supabase is a good fit), run background jobs or cron outside Lovable (e.g., Supabase Edge Functions, Vercel, or GitHub Actions), and keep predictable per-customer limits so AI cost stays bounded.

 

Architecture & key components

 

Minimal pieces you need: a database for users/subscriptions/usage (Supabase), a billing provider (Stripe), server-side endpoints that authorize + meter generator calls, secrets stored via Lovable Secrets before Publish, and a background worker or scheduled task to aggregate usage and bill when needed.

  • Server endpoints — verify session, check subscription status & remaining quota, then forward to AI provider.
  • Metering — log each request (tokens or requests) into DB immediately, then reconcile later.
  • Billing webhooks — Stripe updates subscription status; your webhook updates DB.
  • Background jobs — aggregate and produce invoices, revoke access when past due.

 

Data model (simple)

 

  • users: id, email, supabase auth id
  • subscriptions: user_id, stripe_sub_id, status, tier, quota_monthly
  • usage_logs: user_id, generator, tokens, cost_estimate, created_at
  • quota_snapshots: user_id, month, used\_tokens

 

Concrete server flow & sample code

 

Flow: client calls /generate -> server checks subscription & monthly remaining -> if allowed, call OpenAI and immediately insert a usage\_log row -> return response.

// server/generate.js - Node serverless handler (Vercel/Supabase Edge style)
// uses @supabase/supabase-js and fetch to call OpenAI
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)

// handler receives JSON { user_id, prompt }
export default async function handler(req, res) {
  // // Authenticate request (use Supabase JWT or session cookie)
  const { user_id, prompt } = req.body

  // // Check subscription row
  const { data: sub } = await supabase.from('subscriptions').select('*').eq('user_id', user_id).single()
  if (!sub || sub.status !== 'active') return res.status(402).json({ error: 'subscription required' })

  // // Compute estimated tokens (simple heuristic) and check quota
  const estimatedTokens = Math.max(50, Math.min(2000, Math.floor(prompt.length / 4)))
  const { data: used } = await supabase.rpc('monthly_used_tokens', { p_user_id: user_id }) // optional stored proc
  if ((used || 0) + estimatedTokens > sub.quota_monthly) return res.status(403).json({ error: 'quota exceeded' })

  // // Call OpenAI
  const openaiResp = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ model: 'gpt-4o-mini', messages: [{ role: 'user', content: prompt }] })
  })
  const body = await openaiResp.json()

  // // Log usage immediately
  await supabase.from('usage_logs').insert({ user_id, generator: 'openai-chat', tokens: estimatedTokens, cost_estimate: 0.0001 * estimatedTokens })

  return res.json(body)
}

 

Stripe webhook example (verify signature)

 

// server/stripe-webhook.js
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)

export default async function handler(req, res) {
  const sig = req.headers['stripe-signature']
  let event
  try {
    event = stripe.webhooks.constructEvent(await req.text(), sig, process.env.STRIPE_WEBHOOK_SECRET)
  } catch (err) { return res.status(400).send(`Webhook error: ${err.message}`) }

  // // handle subscription events
  if (event.type === 'invoice.payment_failed') {
    const subId = event.data.object.subscription
    // // update your DB: mark subscription unpaid
  }
  if (event.type === 'customer.subscription.updated') {
    // // update subscription status and tier in DB
  }
  res.json({ received: true })
}

 

Lovable-specific workflow tips

 

  • Secrets: add OPENAI_KEY, STRIPE_SECRET_KEY, SUPABASE_SERVICE\_KEY inside Lovable Secrets UI before Publish — never embed them in client code.
  • No terminal: run DB migrations in Supabase Dashboard or via GitHub Actions after exporting your repo from Lovable to GitHub.
  • Preview: test server endpoints via Lovable Preview, but webhooks need a public endpoint (use ngrok only for local dev; in Lovable Cloud publish and set Stripe webhook to the published URL).
  • Export to GitHub: when you need background workers or cron, export to GitHub and use Actions or deploy to Vercel/Supabase Edge Functions.

 

Operational and cost controls

 

  • Pre-authorization: require a positive balance or active Stripe subscription before allowing calls.
  • Rate-limit: implement per-user rate limits to avoid runaway costs.
  • Reconciliation: run daily jobs to recalc true token usage and correct billing.

 

Final note: design for server-side enforcement, store secrets via Lovable Secrets, use Supabase for durable metering, wire Stripe webhooks, and export/sync to GitHub when you need background workers or migrations — that pattern avoids the common "works locally but breaks in Cloud" pitfalls.

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022