# BuildBase: every published post and the changelog > The full text of https://www.buildbase.app, for agents. The map is https://www.buildbase.app/llms.txt; the API and SDK documentation is https://docs.buildbase.app/llms-full.txt. Each post is also served alone at its URL plus `.md`. ## Orb vs BuildBase: what $6.00 a credit actually buys > Orb now publishes a self-serve price: $6.00 per credit, with credits drawn by billings and by ingested events at the same time. Here is the arithmetic, and where BuildBase fits instead. - Source: https://www.buildbase.app/compare/orb-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-11-06 ### In short Orb charges $6.00 per credit on its self-serve Business plan, and credits drain from two meters at once: one per $1,000 of billings, one per 200,000 ingested events. Past 200 events per dollar billed, ingestion sets your bill rather than the 0.60%. BuildBase makes billing one of 20 modules on your own Stripe account. For years the honest answer to "what does Orb cost" was that nobody outside their sales calls knew. The roundups on page one still say contact sales. That changed. Orb publishes a self-serve price now, and the pages telling you it does not are out of date. The price turns out to be stranger than a percentage. None of them has done the arithmetic on it, so we did. ### The one-paragraph answer Orb is a dedicated usage-metering and billing engine, owned by Adyen since July. Its Business plan costs $6.00 per credit, and credits drain from two meters at once: one per $1,000 of billings processed, one per 200,000 events ingested. BuildBase is an SDK where billing is one of 20 modules, sitting beside authentication, workspaces and role permissions, and running on your own Stripe account. Pick Orb when metered events genuinely are your pricing and getting them right is an engineering problem. Pick BuildBase when billing is the fourth system you have not built yet. They barely compete, because they answer different questions. ### What a credit actually is A credit is two meters sharing one balance. Orb's pricing page quotes the rate: $6.00 per credit on Business, or less with volume discounts, and new accounts get 100 free credits. An equivalence sits in the FAQ: one credit "works out to 0.60% of billing volume, plus event ingestion and other metered dimensions." Read that second clause again. It is doing more work than it looks. The consumption table underneath tells you what a credit really buys, and it is not one thing. One credit is $1,000 of billings processed through Orb. It is also 200,000 events ingested, live and test alike, and two credits is 500,000 rows exported. Those are not three ways of describing one credit, they are separate meters drawing down a single balance. So your bill is not 0.60% of revenue. It is that **plus** $0.03 per 1,000 ingested events, which is what $6.00 per 200,000 events works out to, and the 0.60% is simply the floor you pay when you ingest almost nothing. ### The crossover is 200 events per dollar The ingestion dial starts costing more than the billings dial at **200 ingested events per dollar of billings**. The arithmetic is short. Billings consume credits at one per $1,000, so a dollar of revenue burns 0.001 credits. Events consume credits at one per 200,000, so an event burns 0.000005 credits. Divide one by the other and the crossover falls at 200 ingested events for every dollar of billings. Below that, revenue sets your bill. Above it, your meter does. Two products, same revenue: A B2B tool bills $50,000 a month and ingests two million events. Billings cost 50 credits, events cost 10 credits, so 60 credits at $6.00 is $360. That is 0.72% of billings, a fifth above the headline and no real surprise. An AI product bills the same $50,000 and ingests twenty million events, because it meters per call and per token. Billings still cost 50 credits. Events now cost 100 credits. The bill is 150 credits, or $900, which is 1.8% of billings - three times the number on the pricing page, for identical revenue. Neither product is being overcharged. Orb's costs really do scale with ingestion, and pricing the thing that drives your cost is defensible. But a founder who budgets 0.60% off the FAQ and happens to be building the second product will be wrong by a factor of three, and no page currently ranking for Orb's pricing will have warned them. Work out your own ratio before you model anything. Monthly ingested events divided by monthly dollars billed. If that number is comfortably under 200, the headline percentage is roughly your bill. If it is over, ingestion is what you are buying. Price it as such. ### Where BuildBase charges differently BuildBase charges a flat plan price and takes no share of your revenue. Free at $0, then Launch at $19, Grow at $49 and Scale at $99 a month, with a seven-day trial on the paid plans and no card needed to start one. Yearly is ten months for twelve. Those were current on 31 October 2026, and the live ones are always at [/pricing](/pricing). Nothing in that scales with what you bill your customers. Stripe's own fees are Stripe's, charged to [your own Stripe account](/blog/bring-your-own-stripe), and nothing sits in between. We do meter three things and bill overage on them: workflow runs at $0.25, $0.15 and $0.10 per 1,000 on Launch, Grow and Scale, web analytics events at $2 per 100,000, and storage at $0.10 per GB-month. Every other quota is a hard allowance that simply stops. That is a deliberately smaller promise than Orb's. Our billing module does plan versioning, seat and usage pricing in flat, graduated or volume tiers, add-ons, promotion codes, Stripe Tax, and a credit ledger with expiry and auto top-up. Per-plan limits apply to any metric you define, with overage reported to Stripe Billing Meters. What it is not is an ingestion pipeline. | Feature | BuildBase | Orb | | --- | --- | --- | | Published price | Free $0, then $19, $49 and $99 a month | Business at $6.00 per credit, less with volume discounts; Enterprise is custom | | How the bill grows | Flat plan price; overage only on workflow runs, analytics events and storage | Credits drawn by billings ($1,000 each) and events (200,000 each), so revenue and ingestion both push it up | | Event ingestion | Per-plan limits on any metric, with overage reported to Stripe Billing Meters | Hosted rollups documented at 1M+ billing events per second in production | | Late data and corrections | Not built | Backfills that recalculate affected invoices, and simulations against historical usage | | Revenue recognition and ERP | Not built: no revenue recognition, no accounting sync | Recognized and deferred revenue with exports, plus a one-way NetSuite sync | | Auth, workspaces and roles | 16 sign-in methods, multi-tenant workspaces and role permissions in the same instance | Out of scope: Orb is a billing and metering product | | Payment relationship | Your own Stripe account | Owned by Adyen since 1 July 2026 | ### The acquisition, with less certainty than you have read elsewhere Adyen acquired Orb. Its own knowledge hub says the deal was announced in June 2026 and completed on 1 July. That much is from the acquirer and is solid. Beyond it, be careful. A deal value circulates widely in third-party coverage, and so does a description of how Adyen runs Orb internally, but neither appears on an Adyen or Orb page we could load today. We have repeated both in [our own earlier writing](/compare/lago-alternatives), and on this pass we could not stand them up, so they are not in this post. Treat any specific number you see attached to this deal as reported rather than confirmed. What the acquisition does change is the premise of every "neutral metering engine" pitch. [Metronome went to Stripe](/compare/metronome-vs-buildbase) on 14 January 2026, per Stripe's own newsroom post, and Orb went to Adyen on 1 July. If you were shopping for a metering layer precisely so a payments company would not own it, the two deepest options on the list are now owned by payments companies. That may not matter to you at all, and Orb's engine did not get worse on 1 July. ### Where Orb wins > **Where Orb wins:** Three things, and they are not close. > > **Throughput we do not publish a number for.** Orb documents hosted rollups > handling 1M+ billing events per second in production deployments. Our constants > carry no throughput figure at all, deliberately, because our metering is sized > for per-plan quotas and overage rather than for being the pipeline behind > someone's inference API. Orb's own customer page names Vercel, Replit, Supabase > and Baseten, which tells you the volume band it is built for. > > **Late data, and being able to change your mind.** Orb ships backfills and > corrections that recalculate already-issued invoices when events arrive late, > and simulations that replay a pricing change against historical usage before you > ship it. BuildBase has neither. If an event lands two days after the invoice, we > have no story for that and Orb has a product for it. > > **The finance side of billing.** Orb tracks recognized and deferred revenue with > exports, and syncs to NetSuite as real invoices, credit memos and customer > deposits with line-level service periods. BuildBase ships no ERP integration, no > accounting sync and no revenue recognition in any of its 20 modules. A finance > team closing the books in NetSuite is a customer we do not serve, and no amount > of module count changes that. ### So which problem do you have Ask what breaks first, not which is cheaper. If events are the product and double-counting one is a revenue incident, you want metering infrastructure, and you should go read the field properly rather than take our word for it. [The best usage-based billing tools](/compare/best-usage-based-billing-tools) and [metered billing for AI products](/compare/best-metered-billing-tools-for-ai-products) both cover Orb, and it comes out well in both. [Lago](/compare/lago-vs-buildbase) is the one to look at if self-hosting matters. If instead the honest description is "we bill a few hundred companies for seats and a plan tier, and we also need login, and workspaces, and a way to say who can see what", then a credit that drains on ingestion is priced for a problem you do not have. [Metered and seat-based billing are different businesses](/blog/metered-vs-seat-based-billing). We costed the multi-vendor version of that stack in [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost), and the integration work between them is the line item that never appears on anyone's pricing page. We know the second shape because it is ours. BuildBase meters its own workflow runs through the same module we sell, which is how those overage rates above exist at all, and PlugNode runs usage-based credit metering on it. The thing that made that work was never ingestion throughput. It was that the meter already knew which workspace a run belonged to and whether the caller's role was allowed to start it. Bolt a metering engine on from outside and those two questions are yours to answer, in glue code, for every product you ship. That is the trade. We give up depth, and the three things above are not a courtesy. A note on sourcing. Orb's $6.00 per credit, the 100 free credits, the 0.60% FAQ line and the consumption table (one credit per $1,000 of billings and per 200,000 events, two credits per 500,000 exported rows) were read on withorb.com on 6 November 2026, as were the page-one search results described at the top. The hosted-rollup throughput, backfills, simulations and revenue recognition come from docs.withorb.com the same day, the NetSuite behaviour from Orb's own product page, and the customer names from its customers page. Orb's acquisition dates are Adyen's own knowledge hub, and Metronome's are Stripe's newsroom, both read the same day. Every credit calculation above is ours, worked from Orb's published figures and shown so you can check it. Our plan prices and overage rates come from the shared constants this site builds from, verified 31 October 2026, and the live ones are always at [/pricing](/pricing). --- ## Metronome vs BuildBase: metering infrastructure, or one module of your app? > Metronome is usage-based billing infrastructure, now part of Stripe, priced on billing volume and ingested events. BuildBase makes billing one of 20 modules on your own Stripe account. - Source: https://www.buildbase.app/compare/metronome-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-11-05 ### In short Metronome is usage-based billing infrastructure, now part of Stripe. Its Starter tier runs 0.8% of billing volume plus $0.04 per 1,000 ingest events; the tier above is contact sales. BuildBase makes billing one of 20 modules on your own Stripe. Metronome fits per-event pricing at scale; BuildBase fits seats and plans. Search "Metronome alternatives" and the same roster comes back on every page: Orb, Lago, Chargebee, Stripe Billing, maybe Recurly. Those lists are written by billing vendors, so they all answer one question - which metering engine replaces this metering engine. For a lot of the people searching, that question is already the wrong one. ### The one-paragraph answer Metronome is usage-based billing infrastructure: it ingests metered events, rates them, and turns them into invoices and negotiated contracts. Since January it has been part of Stripe. BuildBase is an SDK where billing is one of 20 modules, sitting beside authentication, workspaces and role permissions, and running on your own Stripe account. Pick Metronome when metered events _are_ your pricing and the volume is high enough that ingestion accuracy is a genuine engineering problem. Pick BuildBase when you charge for seats or plans and billing is the fourth system you still have to build. They are not the same purchase. ### What each one is selling Metronome sells the part of billing that gets hard at scale. Events arrive, they get rated against a contract, and an invoice comes out the other end with the commits and drawdowns applied correctly. Their docs are organised around contracts, not plans, and the plan-based API is marked legacy for new customers. That is a product built for companies negotiating committed spend, not for a team picking a monthly price. BuildBase sells the systems around it. Billing is in there, and it is a real billing module: subscription plans with versioning, seat and usage pricing in flat, graduated or volume tiers, add-ons, promotion codes, Stripe Tax, and a credit ledger with expiry and auto top-up. Per-plan limits apply to any metric you define, with overage reported to Stripe Billing Meters. But it sits next to [multi-tenant workspaces](/guides/multi-tenant-workspaces-in-an-afternoon), role permissions, email and workflow automation, which is the actual reason to buy it. So this is not really a contest between two billing products. It is a question about what else is unbuilt. ### Where the pricing models split Metronome publishes one rate and keeps the rest behind a conversation. Its Starter tier reads 0.8% of billing volume plus $0.04 per 1,000 ingested events; the Custom tier is contact sales, with invoicing integrations, data exports and an account manager attached. Verified on metronome.com on 5 November 2026 - a billing vendor's own rate card moves without an announcement, so check it before you commit to anything. Read the shape rather than the rate. A share of billing volume means the bill grows with your revenue whether or not the billing got harder, which is the [revenue tax every billing platform charges in some form](/blog/billing-platform-revenue-tax). The per-event line means the bill also grows with how granular your metering is. Both are correct ways to price infrastructure that scales with you. They are also exactly wrong for a product that bills 400 companies for 12 seats each and ingests almost nothing. BuildBase charges a flat plan price instead: Free at $0, then Launch at $19, Grow at $49 and Scale at $99 a month, with a seven-day trial on the paid plans and no card needed to start one. Those are our published plans as of 31 October 2026, and the live ones are always at [/pricing](/pricing). We take no percentage of your revenue. Stripe's own fees are Stripe's, charged to [your own Stripe account](/blog/bring-your-own-stripe), and nothing sits in between. | Feature | BuildBase | Metronome | | --- | --- | --- | | Published price | Free $0, then $19, $49 and $99 a month | Starter at 0.8% of billing volume plus $0.04 per 1,000 ingested events; Custom is contact sales | | How the bill grows | Flat plan price; overage only on workflow runs, analytics events and storage | A share of billing volume, so the bill tracks your revenue | | Event ingestion | Per-plan limits on any metric, with overage reported to Stripe Billing Meters | A dedicated ingest API, documented at 100,000 events per second | | Negotiated contracts | Not built: no commits, no drawdown, no revenue recognition | Prepaid and postpaid commits, drawdown, renewals and revenue recognition | | ERP and marketplace billing | Not built | NetSuite and Salesforce, plus AWS, Azure and GCP marketplaces | | Auth, workspaces and roles | 16 sign-in methods, multi-tenant workspaces and role permissions in the same instance | Out of scope: its docs cover billing only | | Stripe relationship | Your own Stripe account | Native Stripe integration, and Metronome is part of Stripe since January 2026 | ### The acquisition changes the question Stripe completed its purchase of Metronome on 14 January 2026 and said it would fold the metering engine into Stripe Billing. Metronome's homepage now carries the line itself. Most of the "Metronome alternatives" posts still ranking were written as though you were choosing a neutral metering vendor to sit in front of whichever processor you liked. That framing is gone. If part of why you are shopping is not wanting a payment company to own your metering roadmap, Metronome is now the thing you were avoiding, and [Orb went the same way when Adyen bought it](/compare/lago-alternatives). Worth being honest about the other direction, though. Most small teams were going to be on Stripe regardless, and a metering engine owned by Stripe is not obviously worse for them. What nobody can tell you yet is whether Metronome stays separately purchasable, and Stripe has not said. Anyone claiming to know is guessing. ### Where Metronome wins > **Where Metronome wins:** Two things, and neither is close. > > **Enterprise contract structures we do not build at all.** Metronome ships > prepaid and postpaid commits with drawdown, negotiated one-time charges, > contract renewals and revenue recognition, plus NetSuite sync and metering > through the AWS, Azure and GCP marketplaces. BuildBase has subscriptions, > seats, tiers, credits and quota overage. It has no commits, no drawdown, no > revenue recognition, no ERP sync and no cloud marketplace billing. A company > closing committed-spend deals through AWS Marketplace should buy Metronome and > not think about us again. > > **Published ingestion scale.** Metronome's docs state 100,000 events per second > without pre-aggregation. We publish no comparable figure, because we do not > have one to publish - our metering is sized for per-plan quotas and overage, > not for being the ingestion pipeline behind a frontier model's API. Stripe's > own announcement named OpenAI, Anthropic and NVIDIA among their customers, > which makes the point better than a benchmark would. ### The part the vendor lists skip Every roundup on page one assumes you have already decided billing is a separate infrastructure purchase. Ours makes the opposite assumption, so here is the check that actually decides it: what is your billable unit, and how many of them do you ingest a day? If the answer is tokens, gigabytes, API calls or compute-seconds, in volumes where double-counting an event is a revenue incident, you want metering infrastructure. Go read the field properly. We did a pass at it in [the best usage-based billing tools](/compare/best-usage-based-billing-tools) and [metered billing for AI products](/compare/best-metered-billing-tools-for-ai-products), and Metronome comes out well in both. If the answer is "seats, and a plan tier, and a usage allowance we mostly enforce rather than bill", then a per-event rate card is priced for a problem you do not have. [Metered and seat-based billing are different businesses](/blog/metered-vs-seat-based-billing). Tooling that is excellent at one is overbuilt for the other. We know the shape of that second case because it is ours. BuildBase bills its own workflow runs at $0.25, $0.15 and $0.10 per 1,000 on Launch, Grow and Scale, metered through the same module we sell - and the thing that made it work was never ingestion throughput. It was that the meter already knew which workspace the run belonged to and whether the caller's role was allowed to start it. PlugNode, one of our own products, runs per-flow-run billing on exactly that. Bolt a metering engine on from outside and you are answering those two questions yourself, in glue code, for every product you ship. ### How to decide Ask which thing breaks first. Contracts with commits, and a finance team that needs revenue recognition? Hand that to Metronome. If it is "we need billing, and also login, and also workspaces, and also a way to say who can see what," you are looking at four vendors, four integrations and the wiring between them, which is the line item nobody puts on a pricing page. We costed one version of that stack in [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost). A note on sourcing. Metronome's two tiers, its rates and the line about being part of Stripe were read on metronome.com on 5 November 2026. The commits, drawdown and revenue recognition, and the legacy status of the plan-based API, come from docs.metronome.com the same day, and the ingestion figure from its ingest API reference. The acquisition date is Stripe's own newsroom post. Our plan prices come from the shared constants this site builds from, verified 31 October 2026, and the live ones are always at [/pricing](/pricing). --- ## Stripe Billing vs BuildBase, and why it is not either-or > Stripe Billing is the subscription engine on your Stripe account. BuildBase is the entitlement layer above it, on that same account. Here is what each one actually decides. - Source: https://www.buildbase.app/compare/stripe-billing-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-11-05 ### In short Stripe Billing and BuildBase are not substitutes. BuildBase sells plans through Stripe Checkout on your own Stripe account, so Stripe charges for Billing either way. What differs is the layer above: Stripe Billing produces the invoice, BuildBase turns an active subscription into quotas and roles. Most "X vs BuildBase" posts are about substitution. This one is not, and pretending otherwise would cost you an afternoon. BuildBase sells plans through Stripe Checkout on your own Stripe account. The subscription it creates is a Stripe subscription, sitting in your Stripe dashboard, raising Stripe invoices. So the question was never which of these two charges your customer's card. Stripe does, either way. The question is what sits above that charge and decides what the customer is now allowed to do. ### The one-paragraph answer Pick Stripe Billing on its own if what you need is the invoice: recurring plans, proration, tax, dunning and a customer portal you do not have to build. Pick BuildBase if the invoice was never the hard part, and the work you keep postponing is the code that turns "this subscription is active" into "this workspace member may call this endpoint 40,000 more times this month." In practice you run both, because BuildBase sells through Stripe either way. ### The fee is a constant, not a difference Stripe charges 0.7% of billing volume for Billing, read from its own pricing page on 4 November 2026. Its wording for what that covers is "Billing transactions processed on and off Stripe," excluding one-off invoices. There is a contracted alternative: $620 a month on a one-year contract for up to $100,000 of monthly billing volume, then $1,500, $2,950 and $5,750 for the $250,000, $500,000 and $1,000,000 tiers, with 0.67% above each cap. Card processing sits outside all of that and does not change: 2.9% plus 30 cents for domestic cards. Now the part that decides this comparison. Because BuildBase's subscriptions are Stripe subscriptions on your account, that percentage does not vanish when you adopt BuildBase. Put it in both columns and move on. TODO(dharmik): Stripe does not publish a per-integration-path breakdown of what counts as Billing volume, so no public page settles whether a Checkout subscription created through BuildBase is rated exactly like one created in the Stripe dashboard. Confirm against a live account before anyone quotes a saving here. That is the opposite of what a comparison page is meant to say, which is why it goes near the top instead of into a footnote. If you came looking for a way around the 0.7%, the options that genuinely move that number are merchant-of-record platforms and standalone metering engines, and they are sorted by shape in [Stripe Billing alternatives](/compare/stripe-billing-alternatives). We are not one of them. ### What each one actually decides Stripe Billing decides what the customer owes. It models the plan, prorates a mid-cycle change, applies tax, retries the failed card, and produces a document a finance team can reconcile. That is a deep and unglamorous problem, and Stripe has spent years on it. BuildBase decides what the customer may do. A plan here carries entitlements: features gated by plan, per-metric quotas, credits with a ledger behind them. `bb.usage.record` meters a quota and checks it in the same call. The subscription that defines that quota lives in the same instance as the workspace it belongs to and the roles of the people inside it, which is the agreement you would otherwise maintain by hand between three systems. Does Stripe have entitlements? It has the primitives, and plenty of teams build the layer themselves on subscription metadata. The real question is whether you want to own that code, and how it behaves the week someone downgrades mid-cycle while a seat is still active. ### The dogfood detail Our own metering ends up back inside Stripe. PlugNode bills per flow run, and on the paid plans workflow runs are a quota that bills over: $0.25 per 1,000 on Launch, $0.15 on Grow, $0.10 on Scale. BuildBase counts those runs against the workspace, then reports the overage into Stripe Billing Meters so the charge lands on the same invoice as the plan. If we thought Stripe Billing was the thing to replace, that is not how we would have built it. | Feature | BuildBase | Stripe Billing | | --- | --- | --- | | What it charges you for | A plan price that does not move with revenue | 0.7% of billing volume | | Whose Stripe account | Yours | Yours | | Invoices, tax and dunning | Stripe Tax and promotion codes at checkout | Its core product | | Entitlements and quotas | Per-plan limits, credits ledger, quota checks | Build it on subscription metadata | | Workspaces, roles and auth | Same instance, 20 modules | Not its job | The price row is the one people read first. It is also the one most likely to mislead, because a percentage and a plan price are not two quotes for the same thing: they are two shapes of cost, and only one of them moves when you have a good quarter. ### Our pricing, for the record Ours comes out of the repo rather than off a web page. Free is $0, Launch is $19 a month, Grow $49 and Scale $99, last checked against the production API on 31 October 2026. The paid plans open with a 7-day trial that does not ask for a card. Free has no trial, because there is nothing to trial into. Live figures are at [/pricing](/pricing). Set that beside 0.7% and the shapes differ in a way worth noticing: a percentage tracks your revenue, a plan price tracks your plan. [The crossover math](/blog/billing-platform-revenue-tax) is worked properly elsewhere, with one caveat for this page. That post compares a flat plan against a percentage vendor you could drop. Stripe is not a vendor you drop. > **Where Stripe Billing wins:** **Invoicing depth we do not match.** Proration edge cases, credit notes, the > dunning retries Stripe tunes on its own data, and a customer portal that > handles the awkward cases without you shipping a screen. If your finance team > has opinions about reconciliation, those opinions are about Stripe Billing, > and they are reasonable ones. > > **It meters a long way for free.** Basic usage-based billing through the Meters > API includes up to 100 million events a month. That is past the point where > most products know whether their pricing model works at all. > > **Nothing to migrate.** Turning Billing on is a setting inside an account you > already have. Adopting a bundle is a larger decision and a harder one to > reverse, and it should be judged that way. > > **At small volume the percentage is cheap.** 0.7% of a few hundred dollars a > month is a rounding error against any flat plan, ours included. Percentage > pricing is genuinely kind to a product that has not found its revenue yet. ### Where each one is the wrong call Stripe Billing alone is the wrong call if you keep writing the same `if (plan === 'pro')` branch in new places and nobody can say what a trial user is allowed to do without reading three files. That is an entitlement problem wearing a billing costume, and no invoicing feature fixes it. The shape of the fix is in [what entitlements are](/blog/what-are-entitlements). BuildBase is the wrong call if billing is the only thing you still need and your auth, workspaces and roles already work. Adopting a backend to get quotas is a bad trade when the rest of it would be replacing things that are fine. The bundle pays off while you are still choosing the pieces, which is the same argument [the Stigg comparison](/compare/buildbase-vs-stigg) reaches from the entitlements side. ### If you are starting from Stripe Billing today Stripe stays. You connect the account BuildBase will sell on, then define your plans, prices and trials in BuildBase, and those sync out to that account. The genuinely new work is the mapping from a plan to what it entitles, which is also the thing you are actually adopting, so it is worth doing slowly. TODO(dharmik): the repo documents the sync in one direction, plans defined in BuildBase pushed to Stripe, and nothing I can find describes what happens to subscriptions already running on that account when it is connected. Write that path down before this post advises anyone mid-flight. [How BYO-Stripe works](/blog/bring-your-own-stripe) covers the account side. [Charging per API call](/guides/charge-per-api-call-nextjs) is the smallest end-to-end example of the metering side. --- ## Descope vs BuildBase: a flow builder for auth, or auth inside a backend > Descope is an auth platform with a drag-and-drop flow builder, SSO and mobile SDKs. BuildBase is one SDK for auth, billing and workspaces. Prices, sign-in methods and where each one wins. - Source: https://www.buildbase.app/compare/descope-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-11-03 ### In short Descope is auth built on a visual flow builder, with SSO and mobile SDKs, free to 7,500 MAU and $799 a month for 25,000. BuildBase is one SDK for auth, billing, workspaces and email, free to 10,000 users and $19 a month for 25,000. Descope wins on enterprise identity and mobile, BuildBase on price and scope. Descope and BuildBase both let you add passkeys, magic links and a Google button without writing the ceremony yourself. That is where the overlap ends. Descope is an authentication platform, and it goes deep on identity. BuildBase is a backend where authentication is one of 20 modules, and it goes wide. ### The one-paragraph answer If you sell to enterprises that will ask for SAML SSO and SCIM, ship native mobile apps, or want product people to edit the sign-in steps on a canvas, Descope is the stronger tool and it is not close. If you are building a web SaaS and need sign-in, workspaces, subscriptions and the emails around them to agree with each other, BuildBase does that in one SDK, and at list price it costs a fraction of Descope for the same user count. ### Where each fits Descope's centre is **Flows**: sign-up, sign-in and step-up sequences built in a drag-and-drop editor, connecting screens, conditions and third-party connectors, then embedded in your app or served as a hosted page. Around it sit SSO, SCIM, fine-grained authorization, an admin portal for your customers, and SDKs for web, mobile and backend. BuildBase's centre is the workspace. A user signs in, belongs to workspaces with roles, and each workspace has a plan, quotas, credits and invoices. Auth is the front door to that, configured in the console and rendered on a hosted sign-in page in 8 languages. You do not design the screens on a canvas; you tick the methods each app offers, and the page draws them. ### Sign-in methods, side by side Both cover the methods most web apps want. The differences are in the paid tiers. Descope's plans all include passkeys, email magic links, email codes, authenticator apps, social login and SSO. Google One Tap and a custom OIDC provider start on Pro, and anonymous users on Growth. Text message and voice codes go through Descope for up to 100 deliveries a month, then through your own connector. BuildBase's sign-in methods are email and password, magic links, email codes, phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, one OpenID Connect or OAuth 2.0 provider of your own, Ethereum and Solana wallets, and enterprise SSO (Enterprise plan, through your own WorkOS account). Phone sign-in uses SMS sign-in codes through your own provider, Twilio or a signed webhook. Around those methods sit Google One Tap, usernames, guest users and device code sign-in for CLIs and TVs. Two-step sign-in is an authenticator app, single-use backup codes or text-message codes, under a policy of off, optional or required, and an authenticator app or a passkey is the stronger choice. Which plan includes which method is on [the pricing page](/pricing). The SMS line deserves a second look, because both products push you to your own provider. Descope's 100 a month is a trial allowance: past it, phone sign-in stops until a connector is set up. BuildBase starts there, with no allowance at all, so the Twilio account is part of setup rather than a surprise in month two. Twilio's own price per code, on its [Verify pricing page](https://www.twilio.com/en-us/verify/pricing), is the same either way. ### Pricing, verified 17 October 2026 Descope publishes four plans. **Free** is $0 for 7,500 MAU with no overages, so you upgrade to grow past it. **Pro** starts at $249 a month for 10,000 MAU and **Growth** at $799 a month for 25,000, both billed annually, with each extra MAU at $0.05. **Enterprise** is custom. BuildBase has four published plans: **Free** at $0 with 10,000 monthly active users, **Launch** at $19 a month with 25,000, **Grow** at $49 with 100,000, and **Scale** at $99 with 500,000. Free has no trial and stops at its allowance; the paid plans start with a 7-day trial that does not ask for a card. Put both on the same user counts, at list price: | Monthly active users | Descope | BuildBase | | -------------------- | ---------------------------- | ------------ | | 7,500 | $0 (Free) | $0 (Free) | | 25,000 | $799 (Growth) | $19 (Launch) | | 50,000 | $2,049 (Growth plus overage) | $49 (Grow) | | 100,000 | $4,549 (Growth plus overage) | $49 (Grow) | The overage rows are $799 plus $0.05 for each MAU above 25,000: $1,250 more at 50,000 and $3,750 more at 100,000. From 25,000 up, Descope's Pro plan would cost more than Growth. Two caveats keep this honest. Descope's price buys SSO connections, the flow builder and compliance paperwork that ours does not. And at 7,500 users both are free, but only Descope's free plan includes SSO connections. | Feature | BuildBase | Descope | | --- | --- | --- | | Free plan | 10,000 MAU on Free; paid plans start with a 7-day trial without a card | 7,500 MAU, no overages | | At 25,000 MAU | $19/mo (Launch) | $799/mo (Growth, billed annually) | | Passkeys, magic links, email codes | Built in; plans on the pricing page | Included on every plan | | Authenticator app second step | Two-step sign-in with backup codes, or text-message codes | Included on every plan | | SMS and voice codes | Through your own Twilio or webhook only | 100 a month through Descope, then your own connector | | SAML / OIDC enterprise SSO | Enterprise plan only, through your own WorkOS account | 3 to 10 connections by plan, more as an add-on | | Designing the sign-in steps | Tick methods per app; hosted page in 8 languages | Drag-and-drop Flow Builder | | Client SDKs | Next.js, Vite, React Router / Remix, TanStack Start | Web, Swift, Kotlin, Flutter and more | | Billing, workspaces, email, workflows | Included, 20 modules in one instance | Not part of the product | > **Where Descope wins:** Descope does several things better, and if any of them is on your list, it > should win. > > **Enterprise identity.** Descope includes SAML and OIDC SSO connections even on its free plan, adds a self-service SSO setup for your customers' IT admins from Pro, and SCIM provisioning from Growth. Adaptive MFA and step-up authentication are on every plan. Our > SAML and OIDC SSO is on the Enterprise plan only, through your own WorkOS > account. If an enterprise buyer's security review includes SSO and a custom > plan is not on the table, this comparison is over. > > **Mobile.** Descope has SDKs for Swift, Kotlin, React Native and Flutter, plus > Vue.js, Angular and SvelteKit on the web. Our SDK is for React-based web apps > and JavaScript backends. If your product is a phone app, Descope covers ground > we do not. > > **Editing the flow without a deploy.** Flows let someone change the sign-up > steps, add a condition or plug in a connector from a canvas. Our hosted page is > configurable, not programmable: you choose the methods, the branding and the > words, not the order of the screens. > > **Compliance paperwork.** Descope's Pro and Growth plans include SOC 2 reports, > and Growth offers a HIPAA BAA. A customer whose procurement checklist asks for > either gets an answer from Descope today. > > **A free plan with SSO.** 7,500 MAU and up to three SSO connections for > nothing. Our Free plan covers more users, 10,000, but SSO is on our Enterprise > plan only. ### How to decide Write down who signs in to your product a year from now. If the answer includes enterprise employees through their company's identity provider, or people on a native phone app, start with Descope and price the billing and workspace pieces separately. If the answer is people and teams on a web app who will subscribe, invite colleagues and hit quotas, the auth decision is the small half of the problem. That is the case BuildBase is built for, and the reason the price above covers far more than sign-in. The [Clerk comparison](/compare/clerk-vs-buildbase) and the [WorkOS comparison](/compare/workos-vs-buildbase) make the same trade from other angles, [Frontegg](/compare/frontegg-vs-buildbase) is the other vendor that puts SSO connections on its free plan, and [best auth for B2B SaaS](/compare/best-auth-for-b2b-saas) sorts the field by whether you need SSO yet. ### Sources Descope figures verified 17 October 2026 on Descope's own pages: [descope.com/pricing](https://www.descope.com/pricing) (plans, MAU allowances, the $0.05 overage, SSO connections per plan, 100 SMS or voice deliveries a month through Descope, SOC 2 reports and HIPAA BAA by plan, Google One Tap and custom OIDC provider from Pro), [Descope getting started](https://docs.descope.com/getting-started) (supported SDKs) and [Descope Flows](https://docs.descope.com/flows) (the drag-and-drop Flow Builder). BuildBase plans are our published pricing, last checked against the production plans on 31 October 2026 (PLAN_FACTS). --- ## Frontegg vs BuildBase: SSO on the free plan, or 20 modules on one bill > Frontegg puts enterprise SSO on its free plan and charges $0.10 per MAU above 7,500. BuildBase is one SDK for auth, billing and workspaces. Verified prices, and where each one wins. - Source: https://www.buildbase.app/compare/frontegg-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-11-03 ### In short Frontegg is CIAM with enterprise SSO and SCIM on its free plan, and a calculator charging $0.10 per monthly active user above 7,500 that stops quoting at $2,500 a month. BuildBase is one SDK for auth, billing, workspaces and email, free to 10,000 users and $19 at 25,000. Frontegg wins on identity depth. Frontegg's pricing page has a slider. Drag it far enough and the price disappears: past 32,500 monthly active users the number is replaced by "Talk to Us". The same thing happens at 25 enterprise connections, and at 2,500 machine-to-machine tokens. All three stop at the same place, $2,500 a month, which tells you where the self-serve product ends and the sales call begins. That ceiling is the most useful thing on the page, and it frames the whole comparison. ### The one-paragraph answer If your next three customers will ask for SAML before they sign, and you want that working this week without a plan upgrade or a WorkOS account of your own, Frontegg is the better pick and the free plan makes it easy to prove. If what you actually need is sign-in plus subscriptions plus workspaces plus the emails that go with them, all agreeing with each other on one bill, that is the case BuildBase is built for, and at 25,000 users the list prices are $1,750 and $19. ### Where each fits Frontegg is CIAM, and it goes deep. Enterprise SSO and SCIM, an embedded self-service admin portal your customers run themselves, ReBAC, hierarchical tenants, and an identity protection set that covers bot detection, impossible travel, new-device and suspicious-IP detection, stale users and accounts-at-risk analytics. Much of it ships as in-app components you drop into your product rather than screens you build. BuildBase's centre is the workspace. Someone signs in, belongs to workspaces with roles, and each workspace carries a plan, quotas, credits and invoices. Auth is the front door to that and one of 20 modules in a single instance. You do not get a tenant security centre component. You do get the billing that Frontegg leaves to you. ### What Frontegg's calculator charges, verified 3 November 2026 Frontegg publishes two plans. **Pay as you go** is $0 a month, and its always-included list is 7,500 monthly active users, 5 enterprise connections for SSO or SCIM, unlimited organizations, a custom domain and a fully customised hosted login. **Enterprise** is custom, and adds multiple environments, advanced fraud protection, a 99.99% uptime SLA and premium support. Everything above the free allowance is metered, and the calculator is linear: | What you move | Free allowance | Rate above it | | ---------------------- | -------------- | --------------- | | Monthly active users | 7,500 | $0.10 each | | Enterprise connections | 5 | $125 each | | M2M tokens | none | $1 each monthly | The rates hold exactly until the total reaches $2,500 a month. At 10,000 users the calculator reads $250, at 25,000 it reads $1,750, at 32,500 it reads $2,500, and at 33,000 it stops quoting. Enterprise connections do the same thing at 25, and M2M tokens at 2,500. So "pay as you go" is true over a defined range, and that range is narrower than the sliders suggest. Worth knowing before you plan around it. ### Our pricing beside it BuildBase publishes four plans. **Free** is $0 with 10,000 monthly active users. **Launch** is $19 a month with 25,000, **Grow** $49 with 100,000, and **Scale** $99 with 500,000. Free has no trial and stops at its allowance; the paid plans open with a 7-day trial that does not ask for a card. Put both on the same user counts, at list price, with no extra Frontegg connections or M2M tokens beyond the free allowance: | Monthly active users | Frontegg | BuildBase | | -------------------- | ---------- | ------------ | | 7,500 | $0 | $0 (Free) | | 10,000 | $250 | $0 (Free) | | 25,000 | $1,750 | $19 (Launch) | | 32,500 | $2,500 | $19 (Launch) | | 50,000 | Talk to Us | $49 (Grow) | Two things keep that table honest. Frontegg's column buys five SSO connections and an identity product ours does not match, and our Free plan covers 10,000 users but carries no SSO at all. The gap is real, and so is what it pays for. > **Key takeaway:** Frontegg charges for identity and hands you the free SSO early. BuildBase > charges for a backend and puts SSO late. Which is cheaper depends entirely on > whether the SSO arrives before the revenue does. ### Sign-in methods Both cover what a web app needs. Frontegg's authentication list runs to password, passwordless, social logins, enterprise SSO, passkeys, MFA, bot detection, email verification, signup flows, session management and user impersonation, with a login builder for the box itself. BuildBase ships email and password, magic links, email codes, phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, one OpenID Connect or OAuth 2.0 provider of your own, Ethereum and Solana wallets, and enterprise SSO on the Enterprise plan, through your own WorkOS account. Phone sign-in is SMS sign-in codes through your own provider, Twilio or a signed webhook. Around those sit Google One Tap, usernames, guest users and device code sign-in for CLIs and TVs. Two-step sign-in is an authenticator app, single-use backup codes or text-message codes, under one policy of off, optional or required, and an authenticator app or a passkey is the stronger choice. Separately, every BuildBase app is an OAuth 2.0 authorization server, which is how agents and third-party apps get access. Frontegg has been building toward the same reader from the other direction, with M2M tokens, token restriction policies and an MCP server for coding assistants. | Feature | BuildBase | Frontegg | | --- | --- | --- | | Free plan | 10,000 MAU on Free; paid plans open with a 7-day trial without a card | 7,500 MAU and 5 enterprise connections, $0 | | At 25,000 MAU | $19/mo (Launch) | $1,750/mo (Pay as you go) | | Where the published price stops | Scale at $99/mo covers 500,000 MAU | $2,500/mo, then Talk to Us | | SAML / OIDC enterprise SSO | Enterprise plan only, through your own WorkOS account | 5 connections on the free plan, $125 each after | | Directory Sync (SCIM) | Enterprise plan, through your own WorkOS account | Shares the enterprise connection allowance | | Identity protection | Brute-force protection and a breached-password check | Impossible travel, new device, suspicious IP, bot detection | | Authorization model | Roles and permissions per workspace | Custom roles, permissions, ReBAC, tenant hierarchies | | Client SDKs | Next.js, Vite, React Router / Remix, TanStack Start | React, Next.js, Angular, Vue, Swift, Kotlin, Flutter | | Backend SDKs | JavaScript and TypeScript, on Node.js, Bun, Deno, Workers | Node.js, Go, Python FastAPI and Flask, Java | | Billing, workspaces, email, workflows | Included, 20 modules in one instance | Not part of the product | > **Where Frontegg wins:** Frontegg beats us in several places, and if one of them is on your list it > should win. > > **Enterprise SSO on the free plan.** Five SAML or OIDC connections, at $0, > before you have a customer. Ours is on the Enterprise plan, through your own > WorkOS account, which means a conversation and a WorkOS bill of your own. For a > seed-stage B2B company whose first logo wants SSO, that difference decides it. > > **Identity protection.** Impossible travel detection, new-device detection, > suspicious IP detection, accounts-at-risk analytics and a tenant security > centre your customers can open themselves. We have brute-force protection and a > check against breached passwords. That is not the same product. > > **Mobile and framework reach.** Frontegg publishes SDKs for iOS Swift, Android > Kotlin, React Native, Flutter and Ionic Capacitor, and on the web covers > Angular, Vue.js and Vanilla.js. Our frontend SDK is React, which is four > frameworks and no phone app. > > **Backend languages.** Go, Python and Java, against our JavaScript and > TypeScript. If your API is written in Go, Frontegg has a first-party SDK for it > and we do not. > > **Authorization depth.** ReBAC and hierarchical tenant structures, for products > where a parent organization needs graded access to its children. Our roles and > permissions are per workspace, which is simpler and sometimes too simple. > > **Compliance paperwork.** Frontegg's Enterprise plan carries a 99.99% uptime > SLA, a support SLA, custom legal agreements and a HIPAA BAA. A procurement > checklist asking for any of those gets an answer from Frontegg today. ### How to decide Ask when SSO arrives relative to revenue. If an enterprise buyer is in the next two quarters and you have no WorkOS account, Frontegg's free five connections are worth more than the price gap, and you should price the billing and workspace work separately because you will still be writing it. If instead your users are teams on a web app who subscribe, invite colleagues and hit quotas, sign-in is the small half of the problem. The [WorkOS comparison](/compare/workos-vs-buildbase) makes this trade from the identity side, [best auth for B2B SaaS](/compare/best-auth-for-b2b-saas) sorts the field by whether you need SSO yet, and [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost) prices the pieces Frontegg leaves out. If isolation is what worries you, [best multi-tenant backend](/compare/best-multi-tenant-backend) covers who maintains that policy. ### Sources Frontegg figures verified 3 November 2026 on Frontegg's own pages: [frontegg.com/pricing](https://frontegg.com/pricing) for the two plans, the always-included allowances, the $0.10 per monthly active user, $125 per enterprise connection and $1 per M2M token rates read off the calculator, the $2,500 point where it stops quoting, the feature comparison table and the Enterprise 99.99% uptime SLA and HIPAA BAA, and [the Frontegg SDK overview](https://developers.frontegg.com/ciam/sdks/overview) for the frontend, mobile and backend SDK lists and the MCP server. BuildBase plans are our published pricing, last checked against the production plans on 31 October 2026 (PLAN_FACTS). --- ## FusionAuth vs BuildBase: free to self-host, under a licence worth reading > FusionAuth Community is free to self-host and publishes no user cap, but it is not open source. What the licence actually restricts, what the paid tiers publish, and what you still build after login. - Source: https://www.buildbase.app/compare/fusionauth-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-11-01 ### In short FusionAuth Community is free to self-host with no published user cap, but it ships under the FusionAuth Customer License Agreement, a proprietary agreement. Paid tiers start at $162 a month. BuildBase is not an identity product: it is 20 modules on one instance, with a Free plan and paid plans from $19 a month. Nearly every directory listing I opened while writing this says FusionAuth Community is free and open source. The first half is true. The second half is not, and FusionAuth does not claim it either: its own licence FAQ says the company has chosen a closed source model for the core product. The free edition is real, it is genuinely free, and it is governed by a proprietary agreement that you accept by downloading the software. Those three things fit together fine. They just do not fit the sentence everyone keeps repeating. That matters less than it sounds. A FusionAuth evaluation gets stuck on the licence; the expensive question is the one nobody asks. ### Which one should you pick Pick FusionAuth if identity is the whole job and you want to run it yourself. It is a complete identity server, it costs nothing to self-host, your backend can be in any language it publishes a client library for, and it will still run on your hardware the day the vendor stops returning calls. Pick BuildBase if the login box is the small half of the problem and the real work is workspaces, roles, plans, quotas, invoices and the mail that goes with them. These two products overlap at the sign-in form and almost nowhere after it. ### What you are choosing between FusionAuth is an identity server you deploy. Users, tenants, applications, groups, tokens, the OAuth 2.0 and OIDC flows around them, plus lambdas for custom logic and connectors for pulling identities from somewhere else. You run the binary and you own the database. It is single-purpose software, deep rather than wide. BuildBase starts from the workspace instead of the session. Someone signs in, belongs to workspaces with roles, and each workspace carries a plan, quotas, credits and invoices. Authentication is one of 20 modules on a single instance. PlugNode, one of six products of ours that run on it, uses auth, team workspaces with role-based access control, Stripe billing and usage-based credit metering out of the same records, which is the part that would otherwise be a mapping table somebody maintains forever. Different question, really. FusionAuth asks how identity should work and hands you most of the controls. We assume it is settled and start at what the account does next. ### What FusionAuth costs, verified 1 November 2026 Four plans, and the pricing page publishes less than you would expect. **Community** is free and self-hosted: "Self-host FusionAuth on your own infrastructure for free," with no user cap stated on the page. **Starter** starts at $162 a month, billed annually, and includes basic hosting. **Essentials** and **Enterprise** both read "Starting at $2,970/mo", billed annually, the first with business hosting and the second with high availability hosting. I read those cards twice on 1 November 2026 and they carried the same figure both times, at the page's default selector position of 1,000 monthly active users. Treat that $2,970 collision as a reason to call sales rather than a price. The page sets a monthly active user selector and then publishes no per-MAU rate, no included-MAU allowance per tier, and no explanation of how moving the selector changes any of the four cards. Every number carries "Starting at". So the honest summary is that FusionAuth publishes a floor and a billing unit, and the rest of the quote is a conversation. The billing unit is documented far better than the price is. An active user is anyone who logs in during the period, counted once however often they return. Non-production instances are exempt. That covers development, UAT, testing and CI, and instance count does not change the licence cost either, so three nodes running for availability is still one licence. Our side is our own published pricing, last checked against the live page on 31 October 2026. Free is $0 with 10,000 monthly active users, 50 workspaces, 1 GB of storage and 2 team seats, and it stops at its allowance rather than billing over. Launch is $19 a month with 25,000 monthly active users, 1,000 workspaces, 10 GB of storage and 3 team seats. Grow is $49 with 100,000 and Scale is $99 with 500,000. The paid plans start with a 7-day trial that does not ask for a card, and yearly billing is ten months for twelve. Three quotas bill past their allowance on the paid plans: workflow runs at $0.25, $0.15 or $0.10 per 1,000 runs on Launch, Grow and Scale, web analytics events at $2 per 100,000 events, and storage at $0.10 per GB-month. We publish no uptime figure: targets vary by plan. > **Key takeaway:** You cannot build an honest side-by-side dollar table from these two pricing > pages, and you should distrust one that tries. FusionAuth's published figures > are floors with no scaling curve attached. Ours are complete prices for a > different product. The comparison that decides it is not price per user. ### The licence, since nobody quotes it The agreement at fusionauth.io/license is the FusionAuth Customer License Agreement, version 2, dated 4 May 2026, and section 2.3 is explicit about how the free tier enters it: free-tier licensees are bound by downloading the free-tier software. There is no separate permissive licence underneath. Section 3 is the part worth reading before you commit. No disassembling, reverse engineering, modifying or making derivative works, at 3(d). No distributing, renting, leasing, sublicensing, assigning, transmitting or selling it onward, at 3(f), and no running it on a service bureau or time sharing basis, at 3(e). Then 3(g): you may not use the software to create or develop a competing product or service. Ownership stays put, by section 5.1. Some bundled third-party components carry their own open source notices, and section 14.1 says those are governed separately. One more clause is easy to miss. Section 2.3 applies section 2.1 to free-tier licensees except 2.1.3, which is the software warranty. So the free tier runs under the section 7 disclaimer: the offerings are provided "AS IS", with no representations or warranties of any kind. None of that makes FusionAuth a bad choice. Paid features over a free core is an ordinary arrangement, and the free tier here is more generous than most. But "free and open source" and "free under a proprietary agreement with a no-compete clause and no warranty" are different propositions, and only one of them is what you are actually agreeing to. If your reason for self-hosting is that you want terms nobody can revoke, this is the paragraph that decides it, and [the difference between self-hosted and open source](/blog/self-hosted-vs-open-source) is worth settling before you pick either product. [Ory](/compare/ory-vs-buildbase) is the contrast that makes it legible: its core really is Apache-2.0, and that is a different kind of promise from a free tier under a customer agreement. Ours is a smaller promise and not a competing one. There is no free self-hosted tier: self-hosting is arranged by talking to us, priced per installation, and that price is not on sale, so there is no figure to give you. Once it is set up, you create the installation in the dashboard, deploy the compose file, and the installation checks in. FusionAuth's floor is download and run. Ours is a conversation first, then an installation that phones home. ### What the free edition actually includes More than you would guess, and the docs state the rule plainly: Community has all features not otherwise labeled in the documentation. The question is only which features carry a label. Starter adds SAML v2 IdP-initiated login, advanced multi-factor methods and connectors. Enterprise adds SCIM, threat detection, the tenant manager, the MFA lambda and application MFA policies; the SCIM API docs carry an "Enterprise plan required" notice on the page itself. Read that list the right way round. General SAML v2 support is not labelled, which puts it in the free tier, and only IdP-initiated login moves to Starter. A FusionAuth install you pay nothing for can terminate SAML single sign-on for a customer. That is worth saying plainly, because it is the single biggest thing FusionAuth gives away that we charge for, and I come back to it below. ### Sign-in methods and SSO These are not the same kind of list. BuildBase ships a fixed set you switch on: email and password, magic links, email codes, phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, one OpenID Connect or OAuth 2.0 provider of your own, Ethereum and Solana wallets, and Enterprise SSO. Around those sit guest users, usernames, device code sign-in and Google One Tap, which are ways of using the methods rather than methods themselves. Separately, every app is an OAuth 2.0 authorization server, which is how agents and third-party apps get access. FusionAuth gives you the protocols and the configuration surface and lets you assemble the list, which is the more flexible answer and the more work. Enterprise SSO is where the two diverge commercially. BuildBase sells SAML and OIDC sign-in and Directory Sync (SCIM) on the Enterprise plan, through your own WorkOS account: a customer's IT admin connects their provider from a setup link, verified domains send each person to their company sign-in, single sign-on can be required per company, and directory groups map to roles. FusionAuth puts SCIM on Enterprise too. But its SAML sits in the free tier, so if the only enterprise question on your roadmap is "can you do SAML", FusionAuth answers it for nothing and we do not. [Best auth for B2B SaaS](/compare/best-auth-for-b2b-saas) sorts the wider field by whether you need that this quarter, and the [WorkOS comparison](/compare/workos-vs-buildbase) covers what our arrangement costs. | Feature | BuildBase | FusionAuth | | --- | --- | --- | | Licence | Proprietary SDK and platform | FusionAuth Customer License Agreement; free tier bound on download | | Free tier | Free plan; paid plans start with a 7-day trial, no card | Community, self-hosted, no user cap published | | What gets metered | Monthly active users, 10,000 on Free and 25,000 on Launch | Monthly active users; non-production instances excluded | | Published entry price | Free; paid plans from $19/mo | Free self-hosted; Starter from $162/mo, billed annually | | Price transparency | Full price list for every plan | Floors only; no per-MAU rate or allowance published | | Languages | TypeScript and JavaScript | Seven client libraries, plus Android and iOS SDKs | | SAML single sign-on | Enterprise plan, through your own WorkOS account | In the free tier; IdP-initiated login from Starter | | Directory sync (SCIM) | Enterprise plan, through your own WorkOS account | Enterprise plan | | Billing, email, workflows | Included, 20 modules on one instance | Not part of the product | | Air-gapped deployment | Not offered | Air-gapped licence, by arrangement with sales | > **Where FusionAuth wins:** **Your backend does not have to be JavaScript.** FusionAuth publishes client > libraries for Go, Java, .NET Core, PHP, Python, Ruby and TypeScript, front-end > SDKs for Angular, React and Vue, a Kotlin SDK for Android and a Swift SDK for > iOS, plus an OpenAPI spec for anything else. Our SDK is TypeScript, and we do > not support Vue, Svelte, React Native or native mobile at all. If your API is > Django or Go, or your product is a native app, FusionAuth is adoptable and we > are not. That single fact ends this comparison more often than anything else on > this page. > > **SAML for nothing.** General SAML v2 is unlabelled in FusionAuth's docs, which > puts it in the free self-hosted edition. Our Enterprise SSO is on the Enterprise > plan, through your own WorkOS account. When a buyer's security review asks the > SAML question, FusionAuth can answer it on a free install and we send you to a > sales conversation. That is a real gap and no module count closes it. > > **Free at any user count, with no licence fee.** Community publishes no MAU cap. > You can run it for ten users or a hundred thousand without a licence fee, and > the only bill is infrastructure and the hours to operate it. Ours is free up to > 10,000 monthly active users, and past that a paid plan from $19 a month. [The > real cost of self-hosting against a managed > service](/blog/self-host-vs-managed-cost) prices the hours either way, but free > is free. > > **It runs where you need it to.** FusionAuth sells an air-gapped licence for > networks with limited or no connectivity. We have nothing equivalent, and a > self-hosted installation of ours checks in with our dashboard. For defence, health or > regulated deployments that is not a preference, it is the requirement. > > **Depth in identity we do not match.** Lambdas for custom token and > registration logic, connectors from Starter for federating against an existing identity > store, a tenant manager, and threat detection on the Enterprise tier. We ship a > fixed set of sign-in methods you switch on. If your problem really is identity > rather than the account built around it, theirs is the deeper toolkit and it is > not close. ### How to decide Two questions end this outright. Is your backend JavaScript, and is your front end web? If not, stop here: FusionAuth is the only one of the two you can adopt. Does a contract require you to run identity on your own hardware, air-gapped or otherwise? FusionAuth again. Read section 3 first, especially 3(g). If neither lands, the question is what you are actually buying. FusionAuth will hold your users, run your flows, federate your OAuth clients and terminate SAML, and it will not invoice anyone, enforce a quota, meter a credit, send a campaign or run a workflow, because it was never meant to. Those stay yours. [The cost of building auth yourself](/blog/cost-of-building-auth-yourself) does the arithmetic for the half FusionAuth does cover, and the half it does not is usually larger: plans, subscription state, entitlements, usage counters, invoices, dunning and the mail around all of it. [Auth0 alternatives](/compare/auth0-alternatives) works through the same trap from the other direction. So do not let the licence argument eat the evaluation. It is worth twenty minutes, and the answer is clear once you read section 3. Then go price the second system, the one that turns a signed-in user into a paying customer, because that is where the real number is. If the workspace that signs in is also the record that gets billed, a bundle removes a mapping you would otherwise own for the life of the product. That cuts both ways: fewer vendors to keep in step, less freedom to swap one piece out. [What RBAC actually is](/blog/what-is-rbac) covers the roles half if that is the piece you are weighing, and [SuperTokens](/compare/supertokens-vs-buildbase) is the closest sibling comparison if free self-hosting with paid add-ons is the shape you are shopping for. ### Sources FusionAuth figures verified 1 November 2026 against FusionAuth's own pages. [fusionauth.io/pricing](https://fusionauth.io/pricing) for the four plans, the free self-hosted Community edition, the $162 Starter floor, the $2,970 shown for Essentials and Enterprise at the default 1,000 MAU selector position, and the hosting and support lines. [fusionauth.io/license](https://fusionauth.io/license) for the FusionAuth Customer License Agreement version 2 of 4 May 2026, section 2.3 on free-tier acceptance and the 2.1.3 warranty exclusion, sections 3(d) to 3(g), the section 7 "AS IS" disclaimer, section 5.1 and section 14.1. [fusionauth.io/license-faq](https://fusionauth.io/license-faq) for the closed source model, the paid self-hosted licences, and the statement that you typically do not pay to run Community behind your own web or mobile application. [fusionauth.io/docs/get-started/core-concepts/licensing](https://fusionauth.io/docs/get-started/core-concepts/licensing) for the MAU definition, the exclusion of logins against non-production instances, the four plan names, the note that instance count does not change what a licence costs, and the air-gapped licence. [fusionauth.io/docs/v1/tech/premium-features/](https://fusionauth.io/docs/v1/tech/premium-features/) for the tier labels and the rule that Community holds everything unlabelled. [fusionauth.io/docs/apis/scim/](https://fusionauth.io/docs/apis/scim/) carries the Enterprise requirement on SCIM. [fusionauth.io/docs/sdks/](https://fusionauth.io/docs/sdks/) lists the client libraries and SDKs. BuildBase plans, modules and sign-in methods come from our own constants, last checked against the live pricing page on 31 October 2026 (PLAN_FACTS). --- ## Ory vs BuildBase: priced per daily user, assembled per service > Ory bills per average daily active user and ships as four services you run yourself. What that converts to, where Ory wins outright, and when BuildBase is the wrong shape for the job. - Source: https://www.buildbase.app/compare/ory-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-10-31 ### In short Ory is an Apache-2.0 identity stack - Kratos, Hydra, Keto, Oathkeeper - you run yourself, or Ory Network at $770 a year with $21 of monthly credit at $0.14 per average daily active user. BuildBase is 20 modules on one instance, free for 10,000 monthly active users and $19 on Launch for 25,000. Ory does not sell you a monthly active user. That reads like a quibble until you try to budget. Ory Network meters average daily active users, the average daily count of unique people who call the Identities APIs, and every auth comparison you have read is written in MAU, including the ones on this site. So the first job with an Ory quote is working out what it says in the unit you actually hold. Nobody does that conversion for you, and no pricing page can do it honestly: it depends on how often your users come back. ### Which one should you pick Pick Ory if your backend is not JavaScript, if you need to be an OAuth 2.0 provider that other people's software federates to, or if running the thing yourself under a permissive licence outranks every other requirement. Pick BuildBase if the login box is the small half of the problem and the real work is workspaces, roles, plans, quotas and the mail that goes with them. Past the sign-in form these two barely overlap, which both pricing pages make harder to see than it should be. ### What you are choosing between Ory is a set of services, not a product you install. Kratos holds identities and runs the self-service flows around them: login, registration, verification, recovery and profile, against an identity schema you define yourself. Hydra is the OAuth 2.0 and OpenID Connect provider. Keto does permissions as Zanzibar-style relationship tuples, sold on the Network as Ory Permissions. Oathkeeper sits in front of your APIs as an identity-aware proxy, and Polis bridges SAML into OAuth 2.0 and OIDC and speaks SCIM 2.0. You take the ones you need and you operate them. BuildBase starts from the workspace instead of the session. Someone signs in, belongs to workspaces with roles, and each workspace carries a plan, quotas, credits and invoices. Authentication is one of 20 modules on a single instance. PlugNode, one of six products of ours that run on it, uses auth, team workspaces with role-based access control, Stripe billing and usage-based credit metering out of the same records. So Ory asks how identity should work and hands you a lot of rope. BuildBase assumes identity is settled and asks what the account does afterwards. ### What Ory Network costs, verified 31 October 2026 Four tiers, two published prices. **Developer** is free: no usage metering, one member, two development environments, and no production or staging environment at all, which makes it a tier for building rather than shipping. **Production** is $770 a year and carries $21.00 of included monthly usage credit, one production environment, three staging, five development and one custom domain. **Growth** is $9,350 a year with $255.00 of monthly credit, two production environments, five staging, twenty development and up to three organizations. **Enterprise** is contact-only. Three things are metered, and none of them is a monthly active user: - Average daily active users: $0.14 on Production, $0.12 on Growth - Machine-to-machine tokens from the client credentials flow: $0.007 and $0.006 per token per month - Permission checks against the Permissions API: $0.000090 and $0.000085 per check per month Now do the arithmetic the page leaves to you. That $21.00 of credit at $0.14 covers 150 average daily active users before a usage charge appears, and $770 a year is about $64 a month. On Growth, $255.00 at $0.12 is roughly 2,125. Whether 150 daily actives is a lot depends entirely on your product. What happens past the credit is the part the page does not say. It publishes the rates and it publishes the credit; it does not state how usage above the credit is billed. Monthly-billed figures for Production and Growth are not shown either. Plan with the annual numbers and treat them as a floor. Read the tier table before the price, though, because the gating is where this gets decided. One-click SAML, SCIM directory sync, multi-tenant production environments and multi-brand projects are Enterprise only. B2B SSO on Growth is OIDC and not SAML. B2B organizations start on Growth and stop at three. Every Ory tier, the free one included, carries MFA with hardware keys, the fine-grained Permission API, and OAuth 2.0 client credentials, authorization code, token rotation and the OIDC provider. Ory also publishes a 99.99% SLA on its Enterprise tier. Our side is our own published pricing, last checked against the production plans on 31 October 2026. Free is $0 with 10,000 monthly active users, 50 workspaces, 1 GB of storage and 2 team seats, and it stops at its allowance. Launch is $19 a month with 25,000 monthly active users, 1,000 workspaces, 10 GB of storage and 3 team seats. Grow is $49 with 100,000 and Scale is $99 with 500,000. The paid plans start with a 7-day trial that does not ask for a card. Yearly billing is ten months for twelve. On the paid plans three things bill over their allowance: workflow runs at $0.25, $0.15 or $0.10 per 1,000, web analytics events at $2 per 100,000, and storage at $0.10 per GB-month. On uptime we publish no number: targets vary by plan, which is less than Ory offers its Enterprise customers. > **Key takeaway:** There is no table in this post putting those two columns side by side in > dollars, and you should distrust any post that builds one. A monthly active user > and an average daily active user count different things. The ratio between them > is a property of your product, and only you can measure it. ### What self-hosting Ory gives you, and what it does not The binaries are free and unmetered. Kratos, Hydra, Keto, Oathkeeper and Polis are Apache-2.0 on Ory's own open source page and on GitHub, and no licence fee attaches to running them at any user count. That is real, and no pricing change next year takes it back. Then read the Kratos README. It describes an Ory Enterprise License, a paid self-hosted edition adding features the free build does not have, SCIM and SAML named among them, plus CVE patches under an SLA, advanced scaling and multi-tenancy, premium support and a private Docker registry. Ory's open source page positions the free build for evaluation and prototyping, and marks it as lacking CVE security patching and production Helm charts. Ory's own pages pull in two directions here. Polis ships SAML and SCIM 2.0 under Apache-2.0, the same two the Kratos README puts behind the Enterprise License. Both are Ory properties. The Enterprise License carries no published price, so there is no figure to quote. Which of those two shapes Ory is depends on the build you run, and [the difference between self-hosted and open source](/blog/self-hosted-vs-open-source) is worth settling before you commit to either. Paid add-ons over a free self-hosted core are a common arrangement, and [SuperTokens prices the same one in public](/compare/supertokens-vs-buildbase): multi-factor sign-in, account linking and multi-tenancy are paid there on self-hosted installs too, and two of the three carry a monthly minimum whatever your user count. Read the figures off their pricing page rather than off this one, because they were last checked for that post and not for this one. Ours is a smaller promise. There is no free self-hosted tier: self-hosting is arranged by talking to us, priced per installation, and that price is not on sale, so there is no number to give you there either. Once it is set up, you create the installation in the dashboard, deploy the compose file with Docker, and the installation checks in. Ory's floor is clone and run; ours is a conversation first, then an installation that phones home. [The real cost of self-hosting against a managed service](/blog/self-host-vs-managed-cost) prices the hours either way. ### Sign-in, SSO and permissions The two method lists are not comparable, because they are not the same kind of list. BuildBase ships a fixed set you switch on: email and password, magic links, email codes, phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, one OpenID Connect or OAuth 2.0 provider of your own, Ethereum and Solana wallets, and Enterprise SSO. Around those sit guest users, usernames, device code sign-in and Google One Tap, which are ways of using the methods rather than methods themselves. Separately, every app is an OAuth 2.0 authorization server, which is how agents and third-party apps get access. Kratos gives you flows and an identity schema and leaves the list to what you configure. Hydra is what makes you an OAuth 2.0 and OpenID Connect provider for other people's software, and nothing on our side claims to be that. Agent access is not the same product as being the identity provider a partner federates to, and a comparison that blurs the two is doing you no favours. Enterprise SSO is where the stories rhyme. BuildBase sells SAML and OIDC sign-in and Directory Sync (SCIM) on the Enterprise plan, through your own WorkOS account: a customer's IT admin connects their provider from a setup link, verified domains send each person to their company sign-in, single sign-on can be required per company, and directory groups map to roles. Ory puts one-click SAML and SCIM on its Enterprise tier, with OIDC-only B2B SSO on Growth. Both products charge for the thing your buyer's security review will ask about. The [WorkOS comparison](/compare/workos-vs-buildbase) goes through what that arrangement costs on our side, and [best auth for B2B SaaS](/compare/best-auth-for-b2b-saas) sorts the wider field by whether you need it this quarter. Permissions is the one place Ory models something roles cannot. Keto works in relationship tuples between objects and subjects, metered at $0.000090 per check on Production. Ours is role-based at the organization and workspace level, with custom permissions, role-scoped API keys and three-tier resolution, which [what RBAC actually is](/blog/what-is-rbac) covers. Ask whether someone may read a document because their team owns the folder it sits in. Ory models that. Roles cannot. | Feature | BuildBase | Ory | | --- | --- | --- | | Licence | Proprietary SDK and platform | Apache-2.0 core; paid Enterprise License for self-hosted SCIM and SAML | | Free tier | Free plan, 10,000 MAU; 7-day trial on paid plans, no card | Developer tier free, but no production environment | | What gets metered | Monthly active users, 25,000 on Launch | Average daily active users, M2M tokens, permission checks | | Published entry price | $0 (Free), then $19/mo (Launch) | $770/yr, about $64/mo, plus $0.14 per aDAU past $21.00 of credit | | Languages | TypeScript and JavaScript | Nine official SDKs plus a REST API | | Enterprise SSO and directory sync | Enterprise plan, through your own WorkOS account | Enterprise tier; OIDC-only B2B SSO on Growth | | Permissions model | Roles at org and workspace level, custom permissions | Zanzibar relationship tuples, billed per check | | OAuth 2.0 provider for third parties | Authorization server for agents and connected apps | Hydra, a general-purpose OAuth 2.0 and OIDC provider | | Billing, email, workflows | Included, 20 modules on one instance | Not part of the product | | If you run it yourself | One compose file: server, client app, auth portal, Mongo, Redis | Kratos, Hydra, Keto, Oathkeeper and Polis, as needed | > **Where Ory wins:** **Nine official SDKs, against one.** Ory publishes TypeScript, Go, Python, Java, > PHP, Dart, Ruby, C# and Rust, plus a documented REST API. Our SDK is TypeScript: > Next.js, Vite, React Router / Remix and TanStack Start on the front end, Express, > NestJS, Fastify, Hono and Astro on the server. A Django or Go API is a > straightforward Ory install and not a BuildBase one at all. This is the biggest > honest gap between the two, and no module count closes it. > > **Apache-2.0 you can run forever.** Kratos, Hydra, Keto, Oathkeeper and Polis > carry a permissive licence, which means you clone them, run them, and never have > a vendor in the loop or a per-installation fee to renew for the life of the > deployment. Self-hosting here is arranged with us, per installation, and each > installation checks in with our dashboard. That is a smaller promise. When owning the > deployment outright is the first requirement, Ory settles the comparison before > anything else gets discussed. > > **A free tier that does real work.** Ory's Developer tier costs nothing, meters > nothing, and still carries MFA, the fine-grained Permission API and the OAuth 2.0 > provider flows. It has no production environment, so it is a building tier rather > than a shipping one. Ours is a Free plan with 10,000 monthly active users that > stops at its allowance, without every feature the paid plans carry. Both are > free; Ory's gives you more of its feature list for nothing. > > **Relationship-based permissions.** Keto expresses authorization that roles > cannot reach, like a grant that exists because a team owns a parent object. If > your access model is shaped that way, Ory has the product and we do not. > > **A published uptime SLA.** Ory commits to one on its Enterprise tier. Our > targets vary by plan and we publish no figure, which is a weaker answer to the > same question. ### How to decide Two questions end this outright, and if either lands you can stop reading. Is your backend JavaScript? If not, Ory is the only one of the two you can adopt, and nothing further matters. Does a contract require you to run identity on your own hardware under a licence nobody can revoke? Then Ory again, with the Enterprise License question parked until you know whether you need SCIM in the self-hosted build. If neither lands, the question becomes what you are really buying. An identity stack is not an account system. Ory will hold your users, federate your OAuth clients and answer permission checks, and it will not invoice anyone, enforce a quota, send a campaign or run a workflow, because it was never meant to. Those stay yours to build and maintain, and [the cost of building auth yourself](/blog/cost-of-building-auth-yourself) is the sibling arithmetic for the half Ory does cover. If the workspace that signs in is also the record that gets billed, a bundle removes a mapping you would otherwise own for the life of the product. That is the trade, and it cuts both ways: fewer agreements to keep, less freedom to swap one piece out. ### Sources Ory figures verified 31 October 2026 against Ory's own pages. `ory.sh` now redirects to `ory.com`. [ory.com/pricing](https://www.ory.com/pricing/) for the four tiers, the $770 and $9,350 annual prices, the $21.00 and $255.00 monthly credits, the $0.14 and $0.12 aDAU rates, the machine-to-machine and permission-check rates, the environment counts, the Enterprise-only SAML and SCIM gating, the OIDC-only B2B SSO on Growth and the Enterprise SLA. [ory.com/open-source](https://www.ory.com/open-source/) for the Apache-2 licensing of Hydra, Kratos, Polis, Keto and Oathkeeper and the evaluation positioning of the free build. [github.com/ory/kratos](https://github.com/ory/kratos) for the Ory Enterprise License description, and [github.com/ory/polis](https://github.com/ory/polis) for the SAML and SCIM 2.0 bridge under Apache-2.0. [ory.com/docs/sdk](https://www.ory.com/docs/sdk) for the nine official SDKs. BuildBase plans, modules and sign-in methods come from our own constants, last checked against the production plans on 31 October 2026 (PLAN_FACTS). --- ## SuperTokens vs BuildBase: where free self-hosting stops being free > SuperTokens core is free to self-host at any scale. MFA, account linking and multi-tenancy are paid add-ons with a $100 a month floor. How that compares with BuildBase, free to 10,000 users. - Source: https://www.buildbase.app/compare/supertokens-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-10-30 ### In short SuperTokens is open source and free to self-host at any user count; its managed cloud is $0.02 per monthly active user, free under 5,000. MFA, account linking and multi-tenancy are paid add-ons with a $100 a month floor, self-hosted too. BuildBase has a Free plan to 10,000 users, then Launch at $19 for 25,000. SuperTokens costs nothing to run. That is not a marketing line, it is the licence: the core is Apache 2.0, you host it next to your app, and there is no cap on how many people sign in. If that is the whole of your problem, go and install it. The interesting part is what happens after that. ### The one-paragraph answer Pick SuperTokens if you want to own the deployment, your team is happy running a service and its database, and your requirements stop at the sign-in box. Pick BuildBase if sign-in is the small half of the problem and the real work is workspaces, subscriptions, quotas and the mail that goes with them. The money question is not free against $19, though, because SuperTokens charges for multi-factor sign-in, account linking and multi-tenancy on self-hosted installs too, and the first two carry a $100 a month minimum whatever your user count. ### Where each fits SuperTokens is built out of recipes you compose: email and password, passwordless by one-time code or magic link, social login, passkeys, unified login through an OAuth2 provider, machine-to-machine tokens, multi-factor authentication with step-up, and enterprise login with multi-tenancy. You run the core yourself or let them run it. The backend SDKs are Node.js, Python and Go, and the front end is React or the framework-agnostic web-js package. That Python and Go support matters more than it sounds: it is the reason SuperTokens turns up in stacks where the API is not JavaScript at all. BuildBase starts somewhere else. The centre is the workspace, not the session. A person signs in, belongs to workspaces with roles, and each workspace carries a plan, quotas, credits and invoices. Authentication is the front door to that and one of 20 modules in a single instance, rendered on a hosted sign-in page. You do not assemble recipes; you tick the methods an app offers and the page draws them. So the two products answer different questions. SuperTokens asks how sign-in should work and gives you a lot of rope. BuildBase assumes sign-in is solved and asks what the account does once it exists. ### Sign-in methods BuildBase ships email and password, magic links, email codes, phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, one OpenID Connect or OAuth 2.0 provider of your own, and Ethereum and Solana wallets. Phone sign-in uses text-message codes through your own Twilio account or a signed webhook. Around those sit Google One Tap, usernames, guest users and device code sign-in for CLIs and televisions. Two-step sign-in is an authenticator app with single-use backup codes, or text-message codes through that same provider, under one policy for the organization that is off, optional or required, and an authenticator app or a passkey is the stronger choice. Separately, every app is an OAuth 2.0 authorization server, which is how agents and third-party apps get access. SuperTokens covers the same ground at the sign-in box and goes further past it, with step-up authentication and an attack protection suite. The difference is not the list. It is that multi-factor sits behind a paid add-on there and inside the plan here. ### Pricing, verified 30 October 2026 SuperTokens publishes two ways to run it. **Self-hosted** is free and open source with no limit on monthly active users. **SuperTokens Cloud** is $0.02 per monthly active user, free under 5,000 MAU, and past that threshold the rate applies to every active user rather than only the ones above the line, which their own worked example confirms. Then the add-ons, which apply to both: - Multi-factor authentication, $0.01 per MAU, minimum billing $100 a month - Account linking, $0.005 per MAU, minimum billing $100 a month - Dashboard users, 3 free, then $20 per user per month - Multi-tenancy and organisation support, priced on request Unified login across domains, machine-to-machine auth, multi-availability-zone infrastructure with uptime SLAs, the attack protection suite and implementation help are all contact-only. Read that $100 as a floor under the bill rather than a charge per add-on. The worked example on their pricing page puts 5,000 MAU with account linking at $125 a month, which is the per-user rates added together and compared against the floor, not stacked on top of it. Below 5,000 users the same example lands on a flat $100. BuildBase publishes four plans: **Free** at $0 with 10,000 monthly active users, **Launch** at $19 a month with 25,000, **Grow** at $49 with 100,000, and **Scale** at $99 with 500,000. Free stops at its allowance rather than billing. The paid plans start with a 7-day trial that does not ask for a card, and yearly billing is ten months for twelve. At list price, with multi-factor sign-in switched on in both: | Monthly active users | SuperTokens Cloud, core only | Cloud plus the MFA add-on | BuildBase | | -------------------- | ---------------------------- | ------------------------- | ------------ | | 2,500 | $0 | $100 (the floor) | $0 (Free) | | 5,000 | $100 | $150 | $0 (Free) | | 25,000 | $500 | $750 | $19 (Launch) | | 100,000 | $2,000 | $3,000 | $49 (Grow) | Three things keep that table honest. The MFA column is only the right column if you actually need a second factor, and plenty of products do not. The rows above 10,000 MAU are list price before any discount, and SuperTokens openly invites a conversation there, so treat $2,000 as an opening number rather than a bill. And self-hosting moves the core to $0 at every row, at the cost of running it, though the add-on rows do not move at all. That last point is the one worth sitting with. Self-hosting is free; the features a B2B product reaches for are not. A team on a self-hosted install with 800 users and a second factor is paying the $100 minimum for MFA on top of infrastructure they maintain themselves. | Feature | BuildBase | SuperTokens | | --- | --- | --- | | Free tier | Free plan to 10,000 MAU; 7-day trial on paid plans | Self-hosted core free at any scale; cloud free under 5,000 MAU | | At 25,000 MAU, core only | $19/mo (Launch) | $500/mo (cloud) or $0 self-hosted | | Second factor | Authenticator app, backup codes or text-message codes, in the plan | Add-on at $0.01/MAU, minimum $100/mo | | SAML and enterprise SSO | Not available | Via multi-tenancy, a paid add-on, price on request | | Where the data lives | Our instance, or a per-organization database | Your database if self-hosted, theirs if cloud | | Backend languages | JavaScript and TypeScript | Node.js, Python and Go | | Front-end coverage | Next.js, Vite, React Router / Remix, TanStack Start | React, plus a framework-agnostic web-js package | | Billing, workspaces, email, workflows | Included, 20 modules in one instance | Not part of the product | > **Where SuperTokens wins:** SuperTokens wins several of these outright, and if one of them is on your list > the comparison is already settled. > > **You can run it yourself, for nothing.** The core is Apache 2.0 and the > self-hosted tier has no user ceiling. No vendor can take that away from you, > and no pricing change next year can either. We have nothing equivalent to > offer, and for a team whose first requirement is owning the deployment, that is > the end of the conversation. > > **SAML and per-tenant user pools.** Enterprise login lives inside SuperTokens' > multi-tenancy feature: tenants created from your own backend with a few API > calls, isolated user pools, optional separate databases per tenant, and > providers including Okta, Active Directory, Google Workspaces, GitLab and > Bitbucket alongside a generic SAML option. We do not ship SAML. If a security > review asks for it, pick them. > > **Python and Go.** Their backend SDKs cover all three major server languages. > Ours is for JavaScript and TypeScript backends. A Django or Go API is a > straightforward SuperTokens install and not a BuildBase one. > > **Free at any scale, if you host it.** The self-hosted core costs nothing > however many people sign in. Our Free plan stops at 10,000 monthly active > users and 50 workspaces, and past that you pay for a plan. > > **Machine-to-machine tokens and unified login.** OAuth2 client credentials for > service-to-service calls, and one login shared across web, mobile and desktop > apps, are documented products there. ### How to decide Ask what you are optimising for, because the two answers barely overlap. If it is control, cost at scale, or a server language that is not JavaScript, SuperTokens is the better instrument, and the self-hosted tier is as free as it claims to be. Budget for the add-ons you will actually switch on, since that is where the published price and the real one diverge. The same reasoning applies to any vendor in this shape, which is what [self-hosted vs open source](/blog/self-hosted-vs-open-source) and [the real cost of self-hosting against a managed service](/blog/self-host-vs-managed-cost) both work through in more detail. If what you are really buying is the account system behind the login - teams that invite colleagues, plans that run out, invoices that have to agree with entitlements - then the auth decision is the small half, and a free auth server does not help with the big half. That is the case BuildBase is built for. [Best auth for B2B SaaS](/compare/best-auth-for-b2b-saas) sorts the field by whether you need SSO yet, and the [Clerk](/compare/clerk-vs-buildbase) and [WorkOS](/compare/workos-vs-buildbase) comparisons make the same trade from the managed side. And if you are weighing either against writing it yourself, [the cost of building auth yourself](/blog/cost-of-building-auth-yourself) has that arithmetic. ### Sources SuperTokens figures verified 30 October 2026 on SuperTokens' own pages: [supertokens.com/pricing](https://supertokens.com/pricing) (the self-hosted and cloud tiers, the $0.02 per MAU rate, the free allowance under 5,000 MAU, the MFA and account linking add-ons with their $100 minimums, dashboard users at $20, and the volume-discount invitation above 10,000 MAU), [the enterprise login overview](https://supertokens.com/docs/authentication/enterprise/overview) (SAML and OIDC, tenant creation from your backend, isolated user pools and the built-in providers), [the backend SDK reference](https://supertokens.com/docs/references/backend-sdks/reference) (Node.js, Python and Go) and [supertokens-core on GitHub](https://github.com/supertokens/supertokens-core) (Apache 2.0, with the `ee/` directory under a separate licence). BuildBase plans are our published pricing, last checked against the pricing page on 31 October 2026 (PLAN_FACTS). --- ## Stytch vs BuildBase: the auth decision you cannot reverse cheaply > Stytch is an auth vendor you add to a stack. BuildBase is a backend that includes auth. The difference that matters is what it costs to change your mind later. - Source: https://www.buildbase.app/compare/stytch-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-21 - Updated: 2026-10-22 ### In short Stytch sells auth on its own, with organizations, RBAC, SSO and MFA and 10,000 users free. BuildBase includes auth as one of 20 modules beside billing, email and workflows, with SSO on Enterprise only and a Free plan to 10,000 users. Pick Stytch if your backend works. Pick BuildBase if it does not. Most comparisons in this category argue about features, and features are the part you can change. Here is the thing that does not change: whichever vendor holds your users' identities is the one you cannot leave on a quiet afternoon. Billing you can swap. Email you can swap in a day. Auth holds the records every other table in your product joins against, and the password hashes may not be yours to export. Ask any auth vendor, us included, how you get your users out before you put them in. Stytch answers that question on its own pricing page, which is more than most do. That asymmetry, not the feature grid, is what this decision is actually about. ### The one-paragraph answer Pick Stytch if your backend exists and works and the missing piece is authentication. Adding a dedicated auth vendor to a working stack is an additive change, and additive changes are reversible in a way that architectural ones are not. Pick BuildBase if you are standing up the backend itself - if auth, workspaces, roles and billing are all still on the list - because those four systems have to agree about who a user is and what an organization is, and having them agree by default is worth more than any single one of them being best in class. ### What each one is Stytch sells authentication as its own product. You keep your database, your billing and your application code, and Stytch holds the identity layer and the flows around it. For B2B that layer is not thin: organizations, role-based access control, SSO and per-organization MFA controls are all part of it. BuildBase includes auth as one of 20 modules on a single instance. A user belongs to a workspace, the workspace has roles, the roles gate permissions, and the subscription that defines what the workspace can do lives in the same system. None of those four things have to be taught about each other. So the difference is not who has organizations and roles. Both do. It shows up at the join between identity and everything that is not identity. With Stytch, their organization is the tenant and your application owns the mapping from it to the subscription, the usage quota and the emails that tenant receives. You maintain that mapping for as long as the product lives. With a bundle, the workspace that signs in is the same record that gets billed, and there is no mapping because there are not two systems. That is the same trade every bundle makes, and it cuts both ways. Fewer agreements to maintain, less freedom to replace one part. ### Pricing Stytch figures verified 19 October 2026 against [stytch.com/pricing](https://stytch.com/pricing). Stytch starts at $0. The always-free tier covers 10,000 monthly active users, unlimited organizations, 5 SSO or SCIM connections and 1,000 machine-to-machine tokens. Past that you pay for what you use, and their page is explicit that there are no hard caps and no pricing cliffs. An additional SSO or SCIM connection is $125. Removing their branding from emails and the login experience is $99. Enterprise is custom. The per-user rate past 10,000 sits behind a calculator rather than a published number, so it is not quoted here. Our side, which does not need re-verifying because it comes from our own published plans, verified 31 October 2026: a Free plan at $0 with 10,000 monthly active users, 50 workspaces, 1 GB of storage and 2 team seats, which stops at its allowance rather than billing. Launch is $19 a month and includes 25,000 monthly active users, 1,000 workspaces, 10 GB of storage and 3 team seats, after a 7-day trial that does not ask for a card. Grow is $49 and Scale is $99. On the paid plans, workflow runs, web analytics events and storage bill over the allowance (storage at $0.10 per GB-month); everything else is a hard allowance. Put those side by side honestly. Up to 10,000 users both cost $0, but Stytch's free tier gives away unlimited organizations and five SSO connections, where ours stops at 50 workspaces and has no SSO. Past 10,000, we cost $19 a month for Launch. That $19 is not buying auth. It is buying the other 19 modules, and if you do not need them it is the wrong $19 to spend. | Feature | BuildBase | Stytch | | --- | --- | --- | | Scope | Auth inside a 20-module backend | Authentication as its own product | | Free tier | Free plan: 10,000 MAU, 50 workspaces | 10,000 MAU, unlimited organizations | | Entry paid plan | $19/mo (Launch), 25,000 MAU, 7-day trial | $0 base, usage billed past the free tier | | Auth methods | 8, dashboard toggles (SSO on Enterprise) | Magic links, OTP, passwords, OAuth, SSO | | SAML and MFA | SAML on the Enterprise plan only, via your own WorkOS account. MFA by authenticator app | Both. 5 SSO or SCIM connections free, then $125 each | | Billing, email, workflows | Included, same system as auth | Not part of the product | | Organizations and RBAC | Included, same system as billing | Included, unlimited organizations | ### What you get on our side of the table User-facing sign-in methods, all toggled from the dashboard rather than configured in code: Email/Password, Magic Link, Email Code, Phone Code, Passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, Custom OIDC, Ethereum Wallet, Solana Wallet and, on the Enterprise plan, Enterprise SSO through your own WorkOS account. Turning one on is a switch, not a deploy, which means [adding magic link](/guides/magic-link-login-nextjs) does not touch your Next.js code at all. [Adding passkeys](/guides/passkeys-nextjs) does not either, though it does make you settle your auth domain first. Sessions run 30 days by default, configurable per session and capped at 180 days. A role change in the dashboard is enforced on the next request, and changing someone's org role signs them out so they return with the new one. When a change seems not to apply, the cause is usually an open tab or a cached API key, and [that has its own guide](/guides/permission-change-not-taking-effect). Every BuildBase app is also a full OAuth 2.0 authorization server, with dynamic client registration, token introspection, revocation and PKCE. That matters more than it used to, because it is what lets an AI agent hold scoped access to a user's account without holding their credentials. > **Where Stytch wins:** **Their SSO starts free, and ours does not.** That is the honest headline > here. Stytch includes five SSO or SCIM connections on its free tier, and its > MFA has per-organization controls, where ours is an authenticator app under > one policy for the whole app. Our SSO is on the Enterprise plan only, through > a WorkOS account you pay per connection. If your buyer is an IT department > with a security questionnaire, SSO is on it, and without the Enterprise plan > we lose that deal on the first page. Check their current list against your > requirement before you read anything else on this page. > > **For auth alone their free tier gives more away.** Both are free to ten > thousand users, but theirs includes unlimited organizations and SSO, and ours > stops at 50 workspaces. If authentication is the only thing you are shopping > for, that decides it. > > **Adopting them is reversible; adopting us is not.** Bolting an auth vendor onto > a working stack changes one layer. Moving to a bundled backend changes the shape > of your application. If your stack already works, the bundle is asking you to > pay an architectural cost to solve a component-sized problem, and that is a bad > trade whoever is selling it. > > **We have a ceiling and they do not have ours.** Our connection-pool architecture > tops out at roughly 1,000 organizations before it becomes the constraint, which > is [documented rather than > hidden](/guides/connection-pool-exhausted-multi-tenant). A dedicated auth > service is not carrying our multi-tenant database model, so it does not inherit > that particular wall. ### When each one is wrong Stytch is the wrong call if authentication is one of several backend systems you still have to build. It will give you users, organizations and roles, and give you them well. You would still be writing subscriptions, usage metering, transactional email and the automation around all three, and then keeping each of them in agreement with an organization that lives in someone else's system. [The cost of building auth yourself](/blog/cost-of-building-auth-yourself) works through that arithmetic, and auth is rarely the expensive line. BuildBase is the wrong call if your backend is built and running. Replacing a working identity layer to get bundled workspaces is the same mistake in the other direction. The bundle pays off while you are choosing the pieces, not after you have chosen them. And both are the wrong call if the real question is enterprise identity. Neither a mid-market auth vendor comparison nor this post answers "what do we do when the buyer's IT team sends a questionnaire", and choosing on price when that is the actual requirement is how teams end up migrating twice. ### If you are choosing more broadly This is a two-name comparison, and the auth field is wider than two names. [Best auth for B2B SaaS](/compare/best-auth-for-b2b-saas) sorts the field by whether enterprise single sign-on is on your path yet, which is the question that actually splits it. If the shortlist is really about the whole backend rather than auth alone, [best multi-tenant backend](/compare/best-multi-tenant-backend) is the closer comparison. --- ## The best Clerk and Stripe combination, and when to skip it > Clerk plus Stripe is two vendors and three jobs. Which combination fits which app, what the seam between them costs you to own, and when a bundled backend is the better call. - Source: https://www.buildbase.app/compare/clerk-stripe-combination - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-10 - Updated: 2026-10-22 ### In short Clerk plus Stripe is two vendors and three jobs. Auth knows who the user is, Stripe knows who paid, and the layer deciding what a paying user can actually do is the one you end up owning. Take the pairing when your pricing is flat and stable. Skip it when quotas, credits or metered usage are the product. The reflex answer to "how do I charge for this" is Clerk plus Stripe, and it holds up until the first customer downgrades mid-cycle. Clerk knows who the user is. Stripe knows who paid. The part in between is yours: you write it, and then you own it for as long as the product exists. ### The short answer Take the pairing if you are selling seats at a price that does not move. The integration is short, and each vendor stays replaceable: swap one and the other never notices. Skip it if what you sell is measured rather than counted: credits, API calls, per-run charges, per-workspace quotas. In that shape the glue between the two vendors stops being an afternoon of webhook handling and becomes a reconciliation job you own for the life of the product. And if you are picking a stack from scratch rather than migrating off one, the first question is not which two vendors. It is whether you want to own the seam between them at all. ### The seam you end up owning A card declined at 2am is the whole problem in one event. Stripe knows within seconds. Your auth vendor does not, because in the two-vendor shape nobody tells it. Your app does not either, until a webhook lands and something in your database changes. So you write a webhook receiver. Then a plan-state table, because reading subscription status from Stripe on every request is too slow. Then gating checks that read that table. Then a reconciliation job, because webhooks get missed and a customer sitting on a plan they stopped paying for is a bug nobody reports. None of that is difficult. All of it is yours forever, and none of it was in the estimate. We put building auth alone at 3 to 6 weeks. The seam is smaller than that, and unlike auth it never finishes. > **Key takeaway:** Auth is identity. A processor is money movement. The layer that turns "this person paid" into "this workspace can create another project" is the one you end up owning, and it is where the maintenance actually lives. ### Two ways to combine them, and they are not the same decision Both shapes work. They differ in one thing, which is where your plan catalog lives, and that is what sets the price of leaving. The first shape is the one most people mean: auth vendor for auth, Stripe Billing for subscriptions, your app in the middle holding plan state. You own the webhooks. In exchange, your plan catalog lives in Stripe, where most tools you will ever buy can read it, and leaving either vendor is a bounded piece of work. The second shape is a billing layer sold by the auth vendor, pitched as riding on top of your own Stripe account and buying away the webhook work by holding the plan catalog for you. The question to ask before you take that trade is where the catalog physically lives, because if the vendor holds it and Stripe never sees it, the saving on day one is a bill on the day you leave: a catalog Stripe never saw is one you recreate by hand, subscription by subscription. If it is mirrored into your Stripe account, the trade is close to free. Clerk Billing is the second shape, and Clerk's own docs answer the question without being asked: "Clerk Billing is a separate product from Stripe Billing; Plans and Subscriptions made in Clerk are not synced to Stripe." Your Stripe account moves the money and holds nothing else. The plan catalog and every subscription against it live in Clerk, which is exactly what makes the webhook work disappear, and exactly what you rebuild if you leave. Clerk charges 0.7% of billing volume for that, on top of processing. Its answer on metered billing is equally direct: "Not yet, but usage-based billing is a top priority on our roadmap." Per-seat plans did ship, in June 2026, so the roadmap is moving - just not on the axis this section is about. (Both quotes still live on Clerk's own pages, verified 12 October 2026.) So pick by how permanent your pricing is. Selling the same three plans in two years? Take the convenience. Expecting to keep changing what you charge for, and how, and to whom? Hold the catalog where the most tools can read it, and pay the webhook tax. ### Where each fits | Feature | BuildBase | Clerk + Stripe | | --- | --- | --- | | Vendors on the critical path | One instance, 20 modules | Two, plus the glue code you write between them | | Entitlement state | Feature flags with workspace, user and audience targeting; toggles without a deploy | A table in your database, kept in sync by your webhooks | | Quotas and credits | Credit ledgers, per-plan quota limits, overage billing, balance alerts | Whatever your processor records, mapping it to in-app limits is your code | | Webhook handling | Delivery logs, retries and HMAC verification, 5-minute max age | Yours to build, monitor and replay | | Stripe account | Your own keys, per organization; we take no cut of revenue | Your own account | | Auth methods | Built in: email/password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, Ethereum and Solana wallets, enterprise SSO (Enterprise plan) | Email code, email link, SMS code, password, passkeys, social OAuth connections, enterprise SSO and Web3 wallets | | SSO against a customer identity provider | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | Yes. Pro ($25/mo) and Business ($300/mo) each include one SSO and one directory sync connection; $75/mo each for connections 2-15, $60/mo to 100 | | Free tier | Free plan: 10,000 MAU. Launch is $19/mo, after a 7-day trial with no card | Hobby is free to 50,000 monthly retained users per app. Pro is $25/mo | Our side of that table is not a pitch, it is the constants file. Free is $0 and includes 10,000 monthly active users, 50 workspaces, 1 GB of storage and 2 team seats. Launch is $19 a month and includes 25,000 monthly active users, 1,000 workspaces, 10 GB of storage and 3 team seats. Grow is $49 with 100,000 users and 8 seats. Scale is $99 with 500,000 and 50. Three quotas bill over on the paid plans: workflow runs at $0.25, $0.15 or $0.10 per 1,000 on Launch, Grow and Scale, web analytics events at $2 per 100,000, and storage at $0.10 per GB-month. Everything else is a hard allowance, on purpose, and Free never bills over at all, so nobody gets a surprise invoice. Yearly is ten months for twelve. (Verified against the live plans 31 October 2026.) One row matters more than any of the price rows: you connect your own Stripe keys, per organization. We are not a merchant of record and we take no percentage of what you bill. Clerk Billing takes 0.7% of billing volume, and Stripe Billing takes the same 0.7% if you run subscriptions through it directly, so the two-vendor route costs a slice of revenue whichever way you assemble it. That is the axis worth checking hardest, because a percentage of revenue is the one line on a bill that grows with your success rather than your usage. At $50,000 billed in a month it is $350, and it keeps going. ### Where the pairing genuinely wins > **Where Clerk wins:** Four things, and none of them are small. > > **Enterprise SSO is cheaper to reach on Clerk.** If a buyer's security review asks you to authenticate their staff against their own identity provider, that is not offered on our Launch, Grow or Scale plans. It is on our Enterprise plan, and it runs through your own WorkOS account, so it is a second vendor relationship either way. Clerk includes one enterprise connection over SAML or OIDC on Pro at $25 a month, then $75 a month each for connections 2 to 15 and $60 a month from 16 to 100. Pro bundles a directory sync connection at the same price, which is the other half of that security review; ours sits on the same Enterprise plan and the same WorkOS account. For a team closing its first enterprise deal on a small budget, that is the clearest reason on this page to keep auth with a specialist. > > **Two vendors means two independent replacements.** If billing stops working for you, you swap billing. Auth never notices. A bundled backend gives you one vendor, one release cadence and one outage window, and buying it is a bet that it stays good at both halves. > > **Clerk's free tier is bigger.** Our Free plan covers 10,000 monthly active users, and paid plans start at $19 a month with a 7-day trial that never asks for a card. Clerk's Hobby tier is free to 50,000 monthly retained users per app, five times ours and more free users than most products ever reach. Before you have revenue that is the number that decides, and it does not decide our way. > > **Our SDK covers a fixed list of web frameworks:** [Next.js](/guides/buildbase-on-nextjs), [Vite](/guides/buildbase-on-vite), [React Router / Remix](/guides/buildbase-on-react-router), [TanStack Start](/guides/buildbase-on-tanstack-start), [Express](/guides/buildbase-on-express), [NestJS](/guides/buildbase-on-nestjs), [Fastify](/guides/buildbase-on-fastify), [Hono](/guides/buildbase-on-hono) and [Astro](/guides/buildbase-on-astro). If you are outside that list, this is a hard stop rather than a trade-off. ### When to skip both Your invoice line decides this, not your architecture diagram. "5 seats x $20" and the two-vendor split is fine. Seats change rarely, and a stale entitlement is the kind of bug a human spots before a customer does. "1,847 API calls" or "312 credits consumed" and you should look harder. Every request now has to check a balance, decrement it, and hold up when two of them land at once. That check cannot cross a vendor boundary on every call, so it lives in your database, which makes your database and your billing vendor two copies of one number. Reconciling two copies of a number that moves thousands of times a day is the job. A bundled backend deletes the job by keeping one copy. That is what our credits and billing modules are for: ledgers, per-plan limits on any metric, overage, and metered usage synced to Stripe from the same place that enforces the limit. Our own defaults are written down rather than discovered in production: a session re-reads its user every hour, and a webhook signature older than 5 minutes is rejected. The other signal is how many products sit on one account. One product with one pricing model? Two vendors is a fine trade, and the glue stays small enough that one engineer holds all of it in their head. Five products sharing one identity and one balance is five copies of that glue, drifting apart at different speeds. ### If you are already on Clerk Do not rip it out because a post told you to. Migrating auth is the highest-risk change you can make to a live product, and "we consolidated our vendors" is not a feature any customer noticed. The honest trigger is pricing pressure or a shape change: you are moving from seats to usage, or you have started writing reconciliation jobs, or the entitlement table has grown a special case per plan. If none of that is true, the pairing is doing its job. Worth reading alongside this: [Clerk vs BuildBase](/compare/clerk-vs-buildbase) for the head-to-head with figures, [Clerk alternatives](/compare/clerk-alternatives) for which complaint each option actually fixes, and [the real cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost) for what the stack costs once it is four vendors instead of two. --- ## The best way to add billing to a Next.js app depends on where entitlements live > Four ways to add billing to a Next.js app, compared on what you still have to build after checkout works: entitlements, quota enforcement and seats. - Source: https://www.buildbase.app/compare/best-way-to-add-billing-nextjs - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-09 - Updated: 2026-10-22 ### In short Four ways to add billing to a Next.js app: wire Stripe yourself, start from a template, bundle it with your auth provider, or use a platform that enforces limits. The transaction fee is not the deciding variable. Where entitlement state lives is, because a webhook-fed table is stale right when a customer upgrades. Every guide to adding billing to a Next.js app finishes in the same place. Checkout works, the webhook fires, a row in your database flips to `active`, and the tutorial ends. That is the easy half. The half that shapes your codebase starts on the very next request, when some route handler has to decide whether this workspace is allowed to do the thing it just asked for. ### The one-paragraph answer If your pricing is one flat amount per interval and you want money moving this week, take `nextjs/saas-starter` and stop reading. Already on Clerk for auth? Clerk Billing bolts plans and per-seat pricing onto gating you have already written. If you sell into the EU and tax is the thing keeping you awake, wire Stripe yourself and add Stripe Tax, because nothing bundled comes close to its coverage. And if what you need is a limit that refuses a request rather than a flag that permits one, none of those three do that. Comparing them on transaction fee will never tell you so. ### Four routes, and what each one leaves you holding **Wire Stripe yourself.** A Checkout session, a webhook handler, a subscriptions table, and a `hasPro` check that ends up written three times: once in `middleware.ts`, once in a server component, once in the route handler you forgot. Stripe has since added Entitlements, which removes some of that bookkeeping: when a subscription becomes active, Stripe creates an active entitlement for each feature attached to the product. Read the object before you plan around it. Its fields are `id`, `object`, `feature`, `lookup_key` and `livemode`. No quantity, no counter, no balance. Provisioning is by webhook plus a list API, which Stripe's own guidance describes as the way to execute feature provisioning. **Start from a template.** The current one is `nextjs/saas-starter`, which replaced Vercel's `nextjs-subscription-payments` when that repo was sunset. Check which you are looking at, because the old one still ranks. The new template gives you a pricing page wired to Stripe Checkout, subscription management through the Stripe Customer Portal, Owner and Member roles, and a webhook handling two subscription events: `customer.subscription.updated` and `customer.subscription.deleted`. Its README calls it "intentionally minimal and to be used as a learning resource", which is the most honest sentence in this entire category. The template it replaced was blunter about where the ceiling is: Stripe Checkout "currently supports pricing that bills a predefined amount at a specific interval", and "more complex plans (e.g., different pricing tiers or seats) are not yet supported". Lemon Squeezy's `nextjs-billing` sits in the same place, handling `subscription_created` and `subscription_updated`, which its README says are "enough to get a billing system in place". Both are good starting points. Neither has a concept of a limit. **Bundle it with your auth provider.** Clerk Billing adds plans, per-seat pricing with seat limits, a base fee and free trials, and gates on them with the same `has()` helper and `` component you already use for roles. Clerk's docs describe that helper as checking whether the user has been granted a role, permission, feature or plan, and returning a boolean. Which is the point: it is the Stripe Entitlements shape with a nicer developer experience on top. One thing to be clear about, because the naming invites the mistake: Clerk Billing is its own product, not a wrapper over Stripe Billing. Clerk's docs say plans and subscriptions created in Clerk are not synced to Stripe, which is only used for payment processing. Clerk charges 0.7% of billing volume for it, on top of Stripe's processing fees paid directly to Stripe. **Use something that holds the counter.** This is where BuildBase sits, and it is worth being precise about what that means, because we are not an alternative to Stripe. The billing module runs on your own Stripe account. What it adds is the piece none of the three routes above ship: `bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1 })` returns the remaining balance in the same response, and on a plan without overage enabled the call fails rather than recording the increment. One await, inside the request that has to answer. Metering and enforcement are one operation, which is the only arrangement in which they cannot drift apart. ### An entitlement is a boolean. A quota is a counter. These are two different questions and the industry has quietly agreed to only answer one of them. "Is this customer on Pro" is a boolean. It changes a handful of times in a customer's life, it is cheap to cache, and a webhook is a perfectly reasonable way to learn about it. Stripe Entitlements answers it. Clerk's `has()` answers it. Every `hasPro` check in every SaaS codebase answers it. It is worth being clear that this boolean is [not a feature flag](/blog/entitlements-are-not-feature-flags), even where the same component renders both, because the two have different owners and fail in opposite directions. "Has this workspace used its 10,000 API calls" is a counter. It changes on every request, it is worthless the moment it is stale, and no webhook will ever deliver it to you in time. Stripe is explicit that its meters are eventually consistent: meter events are processed asynchronously and may not be immediately reflected in aggregates, and meter event summaries are described in the API reference as an eventually consistent view of reported usage. That is the correct design for producing an accurate invoice. It is the wrong design for a route handler deciding, right now, whether to return a 429. > **Key takeaway:** Every billing provider will answer "is this customer entitled". Almost none of > them will answer "how much do they have left" in time to act on it. If your > pricing has a limit in it, that gap is your code, whichever provider you pick. So the real question for a Next.js codebase is not which provider takes the money. It is whether a counter lives somewhere your route handler can read and decrement in one round trip, or whether you are going to [build that yourself](/blog/cost-of-building-usage-metering-yourself) on top of a table a webhook fills in. ### Where Next.js makes the staleness visible Here is the bug, and it always arrives the same way. A customer upgrades. Stripe redirects them back to your success page. That page is a server component, so it renders on the server, reads your database, and finds the row the webhook has not written yet. Your happiest customer of the week sees the free plan. You can fix it, and the fixes are all fine: read the subscription from Stripe directly on the success path instead of from your own table, or render that page from a pending state and let the client poll, or make the success route the one place that does not trust the cache. The first of those is what `nextjs/saas-starter` quietly does, and it is the best thing in the template: its Checkout `success_url` points at a route that fetches the session and writes the subscription before the page renders, so the happy path never waits on a webhook at all. What you cannot do is not decide. Every route in your app that reads plan state from a webhook-fed table has a window where it is wrong, and the App Router makes that window most visible on exactly the page a customer is most excited to be looking at. I should be straight about where we have a version of the same problem. The per-metric quota check described above is synchronous and has no webhook in it, so it does not have this window. Our org-level check, the separate question of whether an organization is entitled to the platform at all, is a different code path with a short-lived cache in front of it, and it is not instant after a payment lands. Two questions, two mechanisms. Only one of them sits in the request path with nothing cached in front of it, and anyone claiming their billing state is globally instant is describing a design they have not shipped. | Feature | BuildBase | Stripe | | --- | --- | --- | | Entitlement shape | Counter with a remaining balance | Boolean feature grant, no quantity field | | Delivery to your app | Read and decremented in the request | Webhook plus a list API | | Behavior at the limit | Fails unless overage is on; trials always cap | Meters it; the block is yours to write | | Tax determination | Stripe Tax on your own Stripe account, switched on per organization; checkout collects the address and tax ID | Stripe Tax, calculated and collected | | Languages and frameworks | Next.js, Vite, React Router / Remix, TanStack Start, Express, NestJS, Fastify, Hono, Astro | Any language with an HTTP client | | Scope | 20 modules including auth, workspaces and RBAC | Payments and billing | > **Where Stripe wins:** Stripe Tax is not a feature we have a smaller version of. It is Stripe's > product, and we have no tax engine of our own. Stripe calculates and collects > tax across the EU, the UK, Norway, Switzerland, every US state, Australia, > Japan, Singapore, the UAE and more. What we add is the switch: Stripe Tax runs > on your own Stripe account, turned on per organization in the console, and > checkout then collects the billing address and tax ID and every invoice shows > its tax. So the honest version is that we have no tax engine of our own, not > that using us costs you Stripe Tax. Revenue Recognition is the same story for > accrual-basis reporting. Stripe is also language-agnostic. Our SDK covers six > JavaScript frameworks, so a Django or Rails team can use Stripe Billing today > and cannot use BuildBase at all. ### How to actually decide Write down your pricing page first, then read it back as questions your code has to answer. If every line is a flat monthly amount, all four routes work and you should take the fastest one, which is the template. If a line says "up to 10,000 API calls", you have a counter, and you should decide now where it lives rather than discovering in month four that it lives in four places. Decide at the same time whether that counter is [an allowance that resets or a balance the customer bought](/blog/quotas-are-not-credits), because the two carry different behavior at renewal. If a line says "per seat", you need a seat count checked against a plan limit on every invite, which is app-layer work no matter who processes the card. And if a line mentions VAT, start from Stripe Tax and fit the rest around it. Our own pricing starts with a Free plan at $0, then $19 a month for Launch, with 25,000 MAU included, and every paid plan carries a 7-day trial that does not ask for a card. Three quotas bill past their limit on the paid plans: workflow runs (from $0.25 per 1,000 on Launch), web analytics events ($2 per 100,000) and storage ($0.10 per GB-month). Free and everything else hard-stops, which is the whole argument above applied to ourselves. Card details are handled entirely by Stripe and never stored on our servers. Once you have picked a route, the implementation posts are the next stop: [charging per seat in Next.js](/guides/charge-per-seat-nextjs) covers the invite-button case in code, and [charging per API call in Next.js](/guides/charge-per-api-call-nextjs) covers the meter-and-enforce loop in a single route handler. If the question underneath all this was really which metering vendor to buy, [best usage-based billing tools](/compare/best-usage-based-billing-tools) argues that one on its own terms. And if your pricing page opens with a trial rather than a plan, [running one without a credit card](/guides/free-trial-without-a-card-nextjs) is the case where the entitlement check has to admit a status that is not `active`. A note on sourcing. Stripe's Entitlements object shape, the webhook-plus-list-API provisioning guidance and the eventual consistency of meters all come from Stripe's own documentation, checked on 9 September 2026. The `nextjs/saas-starter`, `nextjs-subscription-payments` and `nextjs-billing` quotes were read directly from each repository on the same day, as were the Clerk lines, from Clerk's own docs and pricing page. No Stripe Billing rate appears above, and that is deliberate: the figure could not be read off Stripe's pricing page today, and Clerk's 0.7% is Clerk's own fee for a separate product rather than a second reading of Stripe's. Base Stripe processing fees and Clerk's plan pricing are absent for the same reason. A stale fee is worse than no fee. BuildBase figures come from `PLANS` and `PLAN_FACTS` in `packages/shared/src/constants/platform-stats.ts`, verified 31 October 2026 against the live plans, and the enforcement behavior from the metered-usage service in `server/src/payment/`. --- ## Best backend for an API product > Supabase, Firebase and Hasura are built for apps with a database behind them. An API product needs API-key auth and usage-based billing per call - here's what each actually gives you. - Source: https://www.buildbase.app/compare/best-backend-for-an-api-product - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-08 - Updated: 2026-10-12 ### In short The best backend for an API product isn't decided by database or auth alone - it's whether API-key auth and usage-based billing work as one system. Supabase, Firebase and Hasura give you a database or a GraphQL layer, but none bills your own downstream customers per call. That part stays DIY on every one of them. Ask what the best backend for an API product is, and every roundup answers with the same three names: Supabase, Firebase, Hasura. All three are good backends. None of them is built for a product that is itself an API - one where a customer signs up, gets a key, and pays you by the call. That's a narrower problem than "pick a database," and it's the one this comparison actually answers. ### The one-paragraph answer If your product exposes a database or a GraphQL layer to end users through your own app, Supabase, Firebase or Hasura are still the right shortlist, and the decision comes down to SQL versus document store versus a generated GraphQL API over what you already run. If your product _is_ the API - customers call it directly, get a key, and get billed by volume - none of the three meters or bills that for you. You wire together an auth layer for issuing keys, a counter for usage, and Stripe for the invoice yourself, on all three of them. BuildBase ships API tokens, per-call usage tracking and Stripe billing as one module, at the cost of a database you never touch directly. ### What "backend" means once your product is the API Every BaaS in this comparison was designed to sit behind an app: a mobile client, a web dashboard, something with a logged-in user clicking around. Auth in that world means a session - a cookie or a JWT that says who's currently looking at the screen. An API product flips that. There's no screen. A customer's server calls your server, presents a key instead of a login, and does that thousands of times a month. The question isn't "who is this user" so much as "which customer issued this key, what plan are they on, and have they used their quota this cycle?" Session auth answers the first question fine. It has nothing to say about the other two. > **Key takeaway:** A BaaS built for logged-in users gives you session auth. An API product needs > key-scoped auth tied to a plan and a running usage count - a different > problem, and one that Supabase, Firebase and Hasura all leave unsolved. ### Where each one fits **Supabase - Postgres, open, and DIY on the metering.** [Supabase vs BuildBase](/compare/buildbase-vs-supabase) already covers Supabase's database, storage and auth in full; the part that matters here is the keys. Supabase issues project-level publishable and secret keys, plus a separate end-user JWT layer from Supabase Auth. A publishable key maps to the `anon` or `authenticated` Postgres role and is governed by row-level security; a secret key maps to `service_role`, which carries `BYPASSRLS` and skips policies entirely. Supabase's own docs draw the line this post is about: "An API key doesn't distinguish between users but between applications." Neither key is a per-customer credential you'd hand to someone paying you by the call, and nothing in Supabase counts a request against a plan or reports it to Stripe. Full SQL, extensions like pgvector, and a free tier to start on are genuine strengths - just not ones that touch billing. **Firebase - the same gap, on Google's infrastructure.** Firebase Auth is built for end users signing into an app, and Blaze's pay-as-you-go pricing meters _Firebase's own_ services against you, not your customers' usage of your API against them. If Firestore and Cloud Functions are already your stack, staying there is reasonable. Monetizing calls to your own API on top of it is a separate build either way. **Hasura - a GraphQL layer, not an auth or billing decision.** Hasura doesn't authenticate anyone itself. It runs in JWT mode or webhook mode, where some other service validates the request and hands Hasura session variables to enforce permissions with. Clean separation of concerns for a GraphQL API over an existing database - and it means the auth-plus-billing question this post is about gets punted somewhere else, not answered. **An auth provider plus Stripe, wired by hand - the default everyone assembles.** Most teams don't pick a single vendor for this. They add an auth provider to issue keys, a counter or a Redis key for usage, and Stripe's metered billing API for the invoice, then maintain the glue between all three for as long as the product exists. [The cost of building usage metering yourself](/blog/cost-of-building-usage-metering-yourself) puts a number on that maintenance load, and it doesn't shrink after launch - a new plan tier touches all three systems again. **BuildBase - tokens, metering and billing as one module.** API tokens are scoped to an org, named, and can be activated or revoked, and the billing module tracks usage against any metric - API calls included - tracked in real time and synced to Stripe, billing overage automatically once a plan's allowance runs out. Imejis, one of the six products running on BuildBase, is itself an API product: a template-based image generation API for marketers, built on BuildBase's user auth, API token management, billing and team collaboration - the same pieces this post is about, not a bolt-on. The trade is the one you'd expect: no direct database access. Pricing starts with a Free plan you can build the first version on, and Launch is $19 a month with a 7-day trial that doesn't ask for a card. | Feature | BuildBase | Supabase | | --- | --- | --- | | API key model | Scoped tokens, per org, named and revocable | Project-level publishable/secret keys scoped to an app, not a customer, plus separate end-user JWTs | | Per-call metering | Built in - any metric, tracked in real time and synced to Stripe | None - counting requests against your own customers is DIY | | Billing your customers | Overage billed automatically once a plan allowance is used | Not provided - wire Stripe yourself against your own counter | | Database access | None - API and SDK only | Full Postgres, SQL, extensions like pgvector | | Pricing | Free plan, then $19/mo flat (Launch), published | Free tier, then usage-based | > **Where Supabase wins:** If your API product needs a real database underneath it rather than access > through a fixed set of endpoints - vector search with pgvector for an AI > product, full-text search, or just SQL you can query directly while you build > - Supabase gives you that and BuildBase does not. BuildBase's self-hosted > stack runs on MongoDB, not Postgres, and even there you work through the API > and SDK rather than a database console. Supabase is also open source with a > real free tier, so you can build and test the whole metering-and-billing layer > yourself before paying anyone. BuildBase has a Free plan too, but open source > is a different kind of free: you can read, fork and self-host every line. > That's a genuine advantage early on, even though building that layer is the > exact work this comparison is about avoiding. ### The one honest gap BuildBase's usage metering is per workspace plan, not per API key. Tokens are scoped to an org, not to an individual key, while usage limits and overage belong to each workspace's plan. If two of your own customers need different limits, that isn't a dial on a single key - it means putting each customer in a separate workspace, on its own plan. Worth knowing before the shape of your data model depends on it. ### How to actually decide Start with what your product actually is. If people click through screens in something you built and a database happens to sit behind it, Supabase, Firebase or Hasura are still the right shortlist - nothing above changes that. If people, or their servers, call your API directly, get a key, and pay by volume, the real question is whether key auth and billing exist as one system or three you maintain yourself. [Best metered-billing tools for AI products](/compare/best-metered-billing-tools-for-ai-products) goes deeper on the metering half alone, if billing infrastructure - not the backend around it - turns out to be the actual gap. A note on sourcing. Every BuildBase figure above - the token model, the metering behavior, the Free plan, the $19/mo Launch price and the 7-day trial on paid plans - comes from `PLANS` and `PLAN_FACTS`, re-read 31 October 2026, plus the authentication and billing module entries in `packages/shared/src/constants/`. The competitor claims were re-read off the vendors' own pages on 12 October 2026: supabase.com/pricing and Supabase's API keys guide, firebase.google.com/pricing, and Hasura's authentication docs. Nothing in the shape of any of the three had moved since the previous check: Supabase still ships publishable and secret keys over `anon`, `authenticated` and `service_role`, Firebase still splits a no-cost Spark plan from pay-as-you-go Blaze, and Hasura still states that "actual authentication is handled outside Hasura", in JWT mode or webhook mode. No competitor dollar figure appears above by choice, not by accident - all three meter something above the headline plan, so a single monthly number would be a floor rather than a price, and the shape of each model moves less often than its numbers do. Check the vendor's own page before you budget against any of them. --- ## Best metered-billing tools for AI products, sorted by what the meter actually counts > Metronome, Orb, Lago and Stripe Billing compared for AI products on what the billing unit actually is: a token, a credit, or an event nobody dimensioned for AI. - Source: https://www.buildbase.app/compare/best-metered-billing-tools-for-ai-products - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-07 ### In short For AI products, the best metered-billing tool depends on what the meter counts. Orb prices tokens, seats and outcomes in one config. Lago ships an SDK that wraps your LLM client and streams token usage. BuildBase enforces a credit balance synchronously, but the unit is a flat credit, not a token. Ask Stigg, Orb or any of the other vendors ranking for "AI billing software" what stops a runaway session from blowing through a customer's budget, and the honest answer buried in most of their own posts is: nothing in the billing tool itself. [The general version of that gap](/compare/best-usage-based-billing-tools) - metering tells you what happened, enforcement stops what's about to happen - already has its own comparison. This one is narrower: for an AI product specifically, what does the meter actually count? A token, a credit, a seat, or an event nobody bothered to dimension for AI at all? ### The one-paragraph answer If the cost driver is genuinely multi-dimensional - input tokens, output tokens, seats and an outcome-based fee all in the same invoice - Orb is the one built for exactly that shape, with fractional per-token rates as a native pricing primitive. If the product already calls an LLM directly and wants usage pushed to billing with minimal glue code, Lago's Agent SDK wraps that call and streams token counts on its own, on top of a self-hosted edition that costs nothing. Want accurate per-token billing before a request even runs? None of Metronome, Orb or Stripe's Meters API do that natively today. They price and invoice usage; they don't gate it. And if the requirement is a balance that gets checked and decremented before the operation completes, a credit ledger like BuildBase's does that, with an honest caveat: it enforces a number, not specifically a token. ### Where each tool's AI story actually differs **Metronome, the one that metered OpenAI before Stripe bought it.** Before its acquisition, Metronome was the metering layer behind OpenAI's and Databricks' own billing, which is real pedigree for extreme-scale usage ingestion. Stripe now owns Metronome outright and separately runs its own waitlisted per-token pricing preview inside Stripe Billing (more on that below), so evaluating Metronome today means evaluating two overlapping products from the same company, not one. **Orb, dimensioned for AI specifically.** Orb markets itself explicitly around AI billing, and the pitch holds up past the marketing page: it supports fractional, sub-cent per-token rates and names four billing units built for this category - tokens, agent runs, outcomes and credits - combinable in one pricing config. That is a genuinely different shape from a generic per-unit metering engine bolted onto an AI use case after the fact. **Lago, the one with an SDK for your LLM call.** [Lago's Agent SDK](/compare/lago-vs-buildbase), published for Python and TypeScript, wraps an LLM client and pushes token usage to Lago as it happens, which is a concrete integration convenience none of the others on this list ship. It sits on top of Lago's usual model: the Community edition is open source and free to self-host, with Premium features like dunning and a customer portal sold separately, quote-only. **Stripe Billing, generic today with an AI feature in preview.** The base Meters API aggregates usage events for an end-of-cycle invoice and has no AI-specific primitive of its own. Stripe has previewed a feature that auto-syncs per-token pricing for major model providers, but it's waitlist-gated as of this writing, not something every Stripe Billing account can turn on. > **Key takeaway:** Every vendor here can invoice AI usage accurately. What actually differs is > the unit: Orb and Lago's SDK price and track tokens directly, while BuildBase > enforces a balance before it's spent but counts a generic credit, not a token. > Nobody on this list does both today. ### BuildBase's honest limit here BuildBase's credit module enforces synchronously: consuming credits checks the balance and fails closed, before the calling operation completes, so two concurrent requests can't overdraw the same balance. That part is real and it's the piece missing from Metronome, Orb and Stripe Billing's own descriptions of themselves. But the unit BuildBase enforces is [a flat credit](/blog/quotas-are-not-credits), not a token or a specific model's rate. Wiring a token-denominated LLM cost into that ledger means deciding your own conversion rate from tokens to credits, then updating it yourself every time a model's price changes. [That upkeep is exactly the line item building usage metering in-house costs you](/blog/cost-of-building-usage-metering-yourself) - BuildBase does not track per-model token pricing the way Orb's native units do. | Feature | BuildBase | Orb | | --- | --- | --- | | Native AI billing units | One flat credit unit | Tokens, agent runs, outcomes, credits, combinable | | Request-time enforcement | Synchronous balance check, fails closed | Meters and invoices; no native pre-request gate | | Per-token rate tracking | Not built in; convert tokens to credits yourself | Native fractional per-token pricing | | Pricing | Free plan, then $19/mo flat (Launch), published | Custom quote, no public price list | | Scope | 20 modules: billing, auth, workspaces, RBAC, one instance | Metering and billing only | > **Where Orb wins:** If tokens, seats and an outcome fee genuinely need to live in one pricing > config, Orb's native support for that shape is a real advantage BuildBase does > not match - BuildBase's credit ledger has one dimension, not several > combinable ones. For a product whose entire cost structure is multi-input AI > usage, that specialization is worth the tradeoff of a quote-only price and a > metering-only scope. ### How to actually decide Start with what the invoice actually needs to reflect. Genuinely multi-dimensional AI usage points to Orb - its native units save you from building that pricing logic yourself. If the product already talks to an LLM client directly, Lago's SDK removes a real integration step. And if the whole point is stopping a request before a customer's balance runs out, check for synchronous enforcement specifically: most of the vendors here don't have it, and the ones that do usually don't tie it to a token. Nobody on this list yet does both a token-native unit and pre-request enforcement in the same product; treat that gap as the actual open problem, not a solved one, whichever tool you pick. A note on sourcing. BuildBase's figures and the credit-enforcement description come from `PLANS`, `PLAN_FACTS` and the credits module in `packages/shared/src/constants/` plus the credit-balance service in `server/src/services/credit/`, read today. Metronome's OpenAI and Databricks history, Orb's four AI billing units, Lago's Agent SDK and Stripe's per-token preview all trace to each company's own product pages and announcements, also read today - but none of their dollar pricing appears above as a number, because none of those pricing pages could be reached to re-verify a figure for this edition. This edition still owes a re-verification of Metronome, Orb, Lago Premium and Stripe Billing's current published rates against their own pages once network access allows it, rather than quoting a number nobody checked today. --- ## Best SaaS starter for solo founders: boilerplate you own, or platform you call > Every "best SaaS starter" roundup compares boilerplates against each other. Here is when a fork-and-own kit is the right pick for a solo founder, and when a hosted SDK is. - Source: https://www.buildbase.app/compare/best-saas-starter-solo-founders - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-06 - Updated: 2026-11-02 ### In short Boilerplates like ShipFast and MakerKit hand a solo founder code to own and maintain forever. A hosted SDK trades that ownership for zero ongoing integration upkeep. The right pick depends on whether solo means you want full control, or you never want to touch auth again. Type "best SaaS starter for solo founders" into Google and every result compares the same handful of boilerplates against each other: ShipFast, MakerKit, Supastarter, TurboStarter. Different feature checkboxes, same starting assumption - a starter kit means a repo you fork. Nobody asks who keeps that repo's auth and billing integrations working eighteen months in, when there is still only one of you - the same buy-vs-build question that runs across [every module a SaaS needs](/blog/buy-vs-build-saas-infrastructure), just framed here as a whole starter kit instead of a single line item. ### The one-paragraph answer A boilerplate like MakerKit is still the right call if you want to own every line of code, plan to heavily customize or eventually flip the product, or are shipping something simple enough that you will never need per-tenant roles. A hosted SDK is the better call if "solo" specifically means you do not want a second job patching an auth library or a Stripe webhook every time one of them changes. BuildBase is built for that second answer. Auth, workspaces, RBAC and billing already run as a service, on a Free plan at $0 and then Launch at $19 a month, with a 7-day trial on the paid plans that does not ask for a card. ### Where each fits MakerKit, ShipFast and Supastarter are the boilerplate field. Buy one and you get a GitHub repo already wired to a database, an auth library and Stripe, plus, in MakerKit's case, B2B multi-tenancy in the kit itself: workspaces, email invitations and role-based access for products that need per-organization accounts. The code is yours outright. So is every future decision about it. The day the auth library ships a breaking change, or Stripe deprecates a webhook version, that pull request has your name on it. There is no vendor behind the fork to write it for you. MakerKit also ships a free kit called Lite, which is worth knowing about before you spend $299. It is Next.js and Supabase only, and it leaves out the three things that make the paid kits interesting for a B2B product: billing, team accounts with roles, and the admin panel. As a way to read the code before buying, it is a genuinely good offer. As a starting point for a product with paying teams, it stops exactly where the hard part starts. BuildBase is the opposite trade. Twenty modules, including [workspaces and role-based access](/guides/multi-tenant-workspaces-in-an-afternoon), run as a hosted service behind one SDK. You never see the code that handles a Stripe webhook or a magic-link email, which means you also never patch it. What you give up is the boilerplate's biggest asset: if BuildBase disappeared tomorrow, your app would stop working. A forked repo has no such dependency on anyone. | Feature | BuildBase | MakerKit | | --- | --- | --- | | What it is | 20 modules on one hosted instance: auth, workspaces, RBAC, billing, workflows | A Next.js or TanStack Start boilerplate repo you fork and deploy yourself | | Code ownership | You call the SDK; BuildBase operates the service behind it | You own every file, including the auth and billing wiring | | Ongoing maintenance | Integration patches and security updates are ours to ship | Yours - the next auth CVE or Stripe API bump is your pull request | | Multi-tenancy and roles | Workspaces plus org- and workspace-level roles, built in | MakerKit ships workspaces, invitations and RBAC in every paid tier. Not universal across the category - check before you buy | | Pricing | Free plan at $0, then Launch $19/mo with a 7-day trial and no card required | One-time: $299 Pro or $599 Teams (up to 5 collaborators), lifetime updates. A free Lite kit drops billing and team accounts | | Infrastructure | Hosted by default, or self-hosted on the same SDK | Your infrastructure from day one, and your choice of database on the Drizzle and Prisma kits | > **Where MakerKit wins:** Three things a boilerplate genuinely does better, and none of them are close calls. > > **Full ownership.** The repo is yours, including the auth and billing code most SDKs hide behind an API call. Read it, fork it, rip out the parts you do not need. Nothing we run sits in the path of your login screen, and nothing about your product depends on us staying in business. > > **No recurring platform fee.** Past the one-time purchase, you are not paying a monthly charge for the wiring itself. You still pay Stripe, your database and your host directly, but there is no SDK subscription stacked on top of them. > > **Infrastructure freedom from day one.** You pick the host, the framework version and, on the Drizzle and Prisma kits, the database itself - both are explicitly bring-your-own. The Supabase kit is the one exception worth knowing, since it builds on Supabase Auth, Storage and RLS, so that variant does assume a vendor, and Supabase can change its own terms. What nobody can change is the licence on the repo you bought. ### When the boilerplate is still the right call Buy MakerKit, ShipFast or Supastarter if the code is close to the product itself and you want to keep making the decisions about how auth or billing actually work. Planning to sell the codebase later? Same call - a buyer wants a repo, not an account on someone else's platform. And if the product is a simple, single-user app with no organizations or team seats in its future, a lighter boilerplate is less machinery than workspaces and RBAC you will never touch. None of that changes once revenue shows up. A boilerplate does not get more expensive to own as the product grows - it gets more expensive to _maintain_, and that cost is time, not a bigger invoice. [What building auth yourself actually costs in hours](/blog/cost-of-building-auth-yourself) puts a number on the maintenance side of that trade, and [the full ShipFast comparison](/compare/shipfast-vs-buildbase) works through the exact one-time-versus-subscription arithmetic for one specific kit. ### Which one to pick Pick a boilerplate if ownership, resale value, or a genuinely simple product are the actual priorities - the field is real and MakerKit ships B2B workspaces and roles in the kit itself, so it is worth a look if you expect organizations later. Pick a hosted SDK if the honest answer to "what do you want to be doing in eighteen months" is your product, not a patched dependency tree. A note on sourcing: MakerKit's prices and stack come from makerkit.dev and its pricing page, re-verified 2 November 2026 - $299 Pro and $599 Teams (up to 5 collaborators), still one-time with lifetime updates and still no subscription. Both prices moved since the October check, and down: Pro was $349 and Teams $649. The page now prints each tier as a pair, $349 beside $299 and $649 beside $599, with "/lifetime" attached to the lower figure and no "was" or "sale" label on either, so read the higher number as an anchor and the lower as what you pay. Two other things changed earlier and still hold. MakerKit now sells three kit variants, so the framework list is per kit rather than flat: Next.js and TanStack Start across all three, React Router on the Supabase kit only. And the free Lite kit was not covered the first time round. Multi-tenancy is still in every paid tier, which is why the table now says paid - Lite sits outside that list, as a separate free kit rather than a cheaper tier. Every BuildBase price comes from `PLANS` and `PLAN_FACTS` in `packages/shared/src/constants/platform-stats.ts`, and the module count from `MODULE_COUNT` in `modules.ts` beside it. --- ## Best multi-tenant backend, sorted by who maintains the isolation policy > Multi-tenant backend options compared by who keeps tenant isolation correct after launch - a row-level security policy you write, or a workspace model that ships it. - Source: https://www.buildbase.app/compare/best-multi-tenant-backend - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-05 - Updated: 2026-10-12 ### In short Multi-tenant backend comparisons usually stop at shared schema versus database-per-tenant. The real cost is who maintains the isolation policy: Supabase hands you row-level security and the ongoing upkeep, while BuildBase's workspace module ships tenant isolation as a feature you don't write. Every multi-tenant backend comparison turns into the same argument: row-level security in a shared schema, or a separate database per tenant. That's a real decision, and [shared schema versus database-per-tenant](/blog/database-per-tenant-vs-shared-schema) already works through it in detail. What it skips is the question that actually costs you time after launch - once you've picked a model, who keeps the isolation policy correct as you add tables, ship features, and onboard tenant number two hundred? ### The one-paragraph answer If you want tenancy enforced by a database you already know, and you're fine writing, testing and re-verifying a row-level security policy for every table you add, Supabase or a self-managed Postgres instance is the honest pick - especially if raw SQL and extensions like pgvector matter to you. If you'd rather isolation ship as a feature you don't maintain, with per-workspace quotas and billing built in and no policy of your own to get wrong, BuildBase's workspaces module is built for exactly that trade, at the cost of never touching the database directly. Appwrite sits in between: its Teams primitive gets you a tenant boundary without hand-rolled RLS, but you're still running or paying for the surrounding infrastructure yourself, and there is no billing or per-tenant subscription layer in it. ### Row-level security is a primitive, not a finished layer Ask anyone who has shipped multi-tenant SaaS on Supabase what breaks first, and the answer is usually a query that forgot the tenant filter. RLS pushes authorization into Postgres itself: you write a policy and Postgres appends it to every query as an implicit `WHERE` clause. Two states get confused here, and the difference decides how bad a mistake is. Turn RLS **on** and write no policy, and the table is closed: "no data is accessible through the API when using a publishable key, until you create policies." That is the safe failure. The dangerous one is a table where RLS was never enabled at all, sitting in a schema the API exposes. Supabase's own wording: such a table is "readable and writable by any role with a grant on it." And on an existing project, "a new table in `public` starts with every privilege already granted to all three roles" - `anon`, `authenticated` and `service_role`. So the grant is usually already there. Not just your authenticated users, and not just reads. There is a subtler version that survives even a correct policy. Grants and policies are separate mechanisms, and a table "protected only by policies still hands `anon` an insert path if you never revoke the grant." Writing the policy is the famous half of the job. Revoking the grant is the half people skip. Supabase has closed most of this gap, and the honest version of the argument has to say so. Create a table through the dashboard and the Table Editor enables RLS for you. Miss one anyway and Security Advisor raises `0013_rls_disabled_in_public` at ERROR level, in plain language: "Anyone with your project URL can read, edit, and delete all data in this table because Row-Level Security is not enabled." It surfaces in Studio, in `supabase db advisors`, through the Management API and over MCP. An earlier version of this post said the database won't warn you. It does now. What is left is narrower and still real, and this part is our reading rather than anything Supabase states. The advisor is a report you have to go and read, not a build that fails. The Table Editor's default is documented for tables created in the dashboard, which leaves tables created by a migration or a raw `CREATE TABLE`. And lint `0013` is scoped to RLS being disabled, so the revoked-grant case sits outside it: RLS is enabled there, so it looks correct and reports clean. So the maintenance job survives, just smaller than it was: someone owns writing a policy for every new table, testing it as two different tenants, revoking the grants policies don't cover, and reading the advisor often enough for it to count. That doesn't go away. It moves from a backend module to your own team's checklist. > **Key takeaway:** Row-level security is enforcement Postgres runs once you've written the > policy. Supabase now flags the table you forgot - at ERROR level, in Studio > and on the CLI - so the old "silent by default" story is out of date. What > that lint does not look at, as far as we can tell, is a table whose policy > looks right and whose grants were never revoked. ### Where each one fits **Supabase - Postgres, plus the responsibility.** Supabase pairs a managed Postgres database with auth, storage and edge functions, and RLS is the standard way to isolate tenants inside it. You get direct SQL, the full range of Postgres extensions, and a free tier to build against before you pay anything. What you don't get is a tenancy primitive - "tenant" is a column and a policy you design yourself, and whether that boundary is the user or the organization is a decision Supabase leaves entirely to you. **Appwrite - Teams, which you can use as a tenant boundary.** Appwrite's Teams feature gets you a tenant boundary without writing RLS-equivalent policies by hand: a team per tenant, roles on the membership, and `Role.team()` to grant every member access to a resource. Worth being precise about whose framing that is - Appwrite documents Teams as memberships and permissions and never calls it a multi-tenancy layer. Reading it as one is our inference, and a reasonable one, but you won't find a vendor multi-tenancy guide to follow. Appwrite is BSD 3-Clause licensed, and self-hosting is documented as running "the same features found on Appwrite Cloud" - with the caveat they add themselves, that compliance features and dedicated support route to an enterprise conversation. What it doesn't ship is the billing half: no subscriptions, no per-tenant plans, no workspace-level quotas you can charge against. Its product surface is wider than data and auth, though. Functions, Messaging, Sites, Domains and a firewall are all in there. **Self-managed Postgres - the same trade as Supabase, without the managed layer.** If you're running your own Postgres instance rather than Supabase's hosted one, the isolation story is identical: RLS policies you write and maintain. You also take on the database operations Supabase would otherwise run for you - backups, upgrades, connection pooling - which is exactly the ops load [database-per-tenant cost math](/blog/database-per-tenant-cost) puts a number on once you're managing more than a handful of instances. **BuildBase - isolation as a module, not a policy.** The [workspaces module](/guides/multi-tenant-workspaces-in-an-afternoon) isolates data, feature flags, billing and members per workspace as a shipped feature: `bb.workspace.create()` gives you the boundary, and every read the SDK makes is already scoped to it. Per-plan workspace limits are published rather than architectural guesswork - 1,000 on Launch, 25,000 on Grow, 100,000 on Scale - and role permissions run through the separate RBAC module at both the org and workspace level. AgentCenter, one of the six products built on BuildBase, runs its multi-project tenancy on this exact module rather than a hand-rolled RLS layer. The trade is real: there's no SQL console, no direct database connection, and no free plan - every plan carries a 7-day trial that doesn't ask for a card, with Launch starting at $49 a month. | Feature | BuildBase | Supabase | | --- | --- | --- | | Isolation model | Isolated per workspace, shipped as a feature | Shared Postgres tables, enforced by your own RLS policy | | Tenant limits | 1,000 to 100,000 workspaces by plan, published | No tenant primitive - defined entirely by your schema | | Database access | None - API and SDK only | Full Postgres, SQL, extensions like pgvector | | Pricing | Free plan, then $19/mo flat (Launch), published | Plan fee, plus hourly per-project compute, plus overages | | Scope | 20 modules: auth, billing, RBAC, workflows, one instance | Database, auth, storage, functions - no billing layer | > **Where Supabase wins:** **You can assert an RLS policy in CI. You cannot assert our isolation.** Because a policy is just SQL, it is testable: `supabase test new` scaffolds a pgTAP test, `supabase test db` runs it, and their docs ship a GitHub Actions workflow that runs it on every pull request. So you can write a test that authenticates as an owner, a non-member and an outsider, and fail the build the day someone widens the boundary. We have no equivalent. Our isolation is enforced inside the module, which means you cannot write an assertion against it that breaks your build - you are trusting our tests rather than running your own. If proving the isolation boundary is the thing you need, to an auditor or to yourself, that is a real argument for the policy you maintain. > > **Raw SQL and extensions.** Supabase wins both and it isn't close. Our workspace isolation is enforced partly by never exposing the database at all, so you can't query it directly, run your own migrations against it, or reach for an extension we don't support. That's the same decision that removes the policy-maintenance job. ### How to actually decide Start with who is going to own the isolation policy once you ship. If that's a team that already knows Postgres and wants direct SQL access badly enough to write and maintain RLS policies as the schema grows, Supabase is the right tool and the free tier means you can try it before committing to anything. If nobody on the team wants that job, or you'd rather it not exist, a workspace model where isolation, quotas and billing already ship together removes it - at the cost of database access you'll never get back without migrating off. Tenant count matters too. Under a few hundred tenants, either model works fine on its own merits. Past roughly 1,000 tenants, the constraint that decides it stops being which backend you picked and starts being the connection-pool ceiling both [what database-per-tenant actually costs](/blog/database-per-tenant-cost) and [buy vs build for SaaS infrastructure](/blog/buy-vs-build-saas-infrastructure) already put a number on. If the actual gap is auth and workspace roles rather than the database layer itself, [Supabase alternatives](/compare/supabase-alternatives) covers Firebase, Appwrite, Nhost and PocketBase as direct database-first swaps, none of which add billing or tenancy roles either. A note on sourcing, since roundups are where stale numbers sneak in. Every BuildBase figure above - workspace limits, plan prices, the trial terms - comes from `PLANS` and `PLAN_FACTS` in `packages/shared/src/constants/platform-stats.ts`, re-read 31 October 2026, and the workspaces module entry in `modules.ts`. The Supabase claims - the free tier and the plan-plus-compute pricing shape - came off supabase.com/pricing, and the RLS behavior with and without a policy, the Security Advisor lint and the pgTAP workflow off the Supabase row-level-security, database-advisors, tables and local-testing docs. The Appwrite claims - Teams roles, the absent billing layer and self-hosted parity - came off the Appwrite products, Teams and self-hosting docs, and the BSD 3-Clause licence off their repository. All verified 12 October 2026. Appwrite's pricing page is deliberately not in that list: it would not render on the day of checking, so no claim above rests on it. No competitor dollar figure appears above on purpose: neither vendor's price decides this comparison, and a number that nobody re-checks is exactly how a roundup goes stale. This pass corrected two things rather than just moving the date. The post used to say an unprotected table is open to any authenticated user, which conflated RLS-on-no-policy with RLS-never-enabled and understated the second case. And it used to say nothing warns you, which stopped being true when Security Advisor started flagging it at ERROR level. Both are fixed above. Recording the correction rather than quietly editing it is the point of carrying a verification date at all. --- ## Best auth for B2B SaaS, sorted by whether you need SSO yet > Best auth for B2B SaaS compared by the question that actually decides it: do you need enterprise SSO this quarter, or organizations and roles first. - Source: https://www.buildbase.app/compare/best-auth-for-b2b-saas - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-04 - Updated: 2026-10-22 ### In short Most 'best auth for B2B SaaS' roundups assume day-one enterprise SSO. Most early B2B teams don't have that buyer yet - they need organizations, roles and workspace isolation. Auth0, Clerk, WorkOS and Kinde sell SSO self-serve; BuildBase keeps it for its Enterprise plan. Here is which tool fits which stage. Every "best auth for B2B SaaS" roundup on page one was written by a company that sells enterprise SSO. Naturally, they all rank providers on how well each does enterprise SSO. Fine axis, if a security questionnaire is already on your desk. Wrong one if you're still building the product and don't have an enterprise buyer yet. ### The one-paragraph answer If an enterprise buyer's security review already has SAML or SSO on it, pick Auth0, Clerk, WorkOS or Kinde - all four sell it self-serve, and arguing around that wastes a sales cycle. If you're earlier than that - shipping organizations, roles and workspace isolation for a B2B product that hasn't fielded an enterprise security review yet - BuildBase covers that shape on its Launch, Grow and Scale plans, and none of them include SSO. When the buyer does arrive, BuildBase's Enterprise plan adds SAML and OIDC sign-in and SCIM through your own WorkOS account, which bills each connection to you. Two vendors and a conversation, not a toggle. ### Two different jobs wearing the same label "B2B SaaS auth" gets used for two things that aren't the same problem. One is multi-tenancy: organizing customers into isolated accounts, each with its own members and permissions, so a support rep at Acme can't see Widgets Inc's data. The other is enterprise SSO: letting a customer's own identity provider, Okta or Entra ID or Google Workspace, authenticate its employees into your app on the customer's terms. Every B2B SaaS product needs the first one on day one. Most don't need the second until an enterprise deal is already in motion - and by then, whether SSO is a checkbox you have or a checkbox you're missing is usually decided already, months earlier, by which auth provider got wired in first. > **Key takeaway:** Multi-tenancy (organizations, roles, isolated data) is a day-one requirement > for B2B SaaS. Enterprise SSO is usually a later one, tied to a specific > buyer's security review, not to launch. Sorting the field by which stage each > tool actually serves beats sorting by SSO depth alone. ### Where each one fits **Auth0 - the deepest identity platform, if SSO is already the ask.** [Auth0](/compare/auth0-vs-buildbase) is the most protocol-complete option here: SAML, OIDC, and a B2B product line with per-connection enterprise pricing. It's priced by monthly active users starting on a free tier, with B2C and B2B tiers priced separately. If identity itself is the product's hard problem, Auth0's depth shows. **Clerk - fast to ship, SSO from the first paid tier.** [Clerk](/compare/clerk-vs-buildbase) pairs a polished, framework-native SDK (including React Native and Vue, which BuildBase does not support) with an Organizations product for B2B membership. One enterprise SSO connection is included starting on its Pro plan, with additional connections billed per connection. Clerk also added a Stripe-backed billing product this year, though it remains an add-on rather than a bundled quota-and-metering system. **WorkOS - narrow, and built for exactly this.** [WorkOS](/compare/workos-vs-buildbase) does one thing: enterprise identity. SSO, SCIM directory sync, audit logs, and a self-serve Admin Portal a customer's own IT admin can configure without your team in the loop. Its free User Management product covers a large free tier of monthly active users before the enterprise-connection pricing kicks in. It has no billing and no workspace model beyond its organizations, though AuthKit does support custom roles and permissions scoped to an organization. Billing and anything workspace-shaped stay separate vendor problems. **Kinde - SSO included earlier than most.** [Kinde](/compare/buildbase-vs-kinde) is an auth provider with subscription billing features bolted on, priced on the monthly active users you authenticate through it. It includes one enterprise SSO connection on its free and Pro tiers - unusually early compared to the field - with unlimited connections on its higher paid tier. If the roadmap includes both SSO and basic subscription billing without adding a third vendor for either, Kinde is worth a closer look before reaching for a bundle the size of BuildBase. **BuildBase - organizations and roles first, SSO on Enterprise.** BuildBase ships sign-in by email and password, magic links, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO, alongside multi-tenant workspaces and role-based access control with org-level and workspace-level roles, custom permissions and API token scoping - one piece of a 20-module bundle that also covers billing, workflows and email in the same instance. Enterprise SSO is the catch. Enterprise SSO (SAML and OIDC) and Directory Sync (SCIM) are on the Enterprise plan only, and they run through your own WorkOS account: the customer's IT admin connects their identity provider from a setup link, verified domains send each person to their company's sign-in, and WorkOS bills each connection to you on top of the BuildBase plan. If SSO is the next problem on your list and a custom plan isn't, one of the four above gets you there with one vendor. | Feature | BuildBase | WorkOS | | --- | --- | --- | | Enterprise SSO / SAML | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | Core product, self-serve Admin Portal for customer IT admins | | Organizations / workspaces | Built in, isolated data, billing and settings per workspace | Basic "Organizations" concept, not a full workspace model | | Role-based permissions | Built in, org- and workspace-scoped roles | Custom roles and permissions, org-scoped | | Subscription billing | Built in: plans, credits, usage quotas | Not included, bring your own Stripe | | Sign-in methods | Password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, Ethereum and Solana wallets, enterprise SSO (Enterprise plan) | Email/social sign-in via User Management, plus SSO | | Pricing shape | Flat: Free $0, Launch $19/mo, Grow $49/mo, Scale $99/mo | Free to a large MAU ceiling, then priced per SSO/SCIM connection | > **Where WorkOS wins:** **Enterprise SSO, SCIM and a self-serve Admin Portal, done by specialists.** WorkOS, and to a lesser extent Auth0, Clerk and Kinde, all sell SAML or enterprise SSO connections self-serve. BuildBase's own enterprise SSO is WorkOS underneath: it runs through your WorkOS account, hands the customer's IT admin WorkOS's Admin Portal, and is only on BuildBase's Enterprise plan. So if a buyer's security team has SSO on a questionnaire this quarter and you are on Launch, Grow or Scale, every one of the other four gets you there with one vendor and no plan change, and there is no way to argue around that. ### How to actually decide Don't start from the feature list. Start from whether an enterprise security review is already scheduled. If it is, the choice is between Auth0, Clerk, WorkOS and Kinde on how they each price and package SSO, or BuildBase's Enterprise plan with a WorkOS account of your own - not whether to buy it at all - and [Auth0 vs BuildBase](/compare/auth0-vs-buildbase), [Clerk vs BuildBase](/compare/clerk-vs-buildbase) and [WorkOS vs BuildBase](/compare/workos-vs-buildbase) each carry the current published figures for that comparison, re-verified against the vendor's own page on the date each was written. If no enterprise buyer has asked yet, the more useful question is how many other systems you're about to wire together around whichever auth provider you pick - billing, workspace isolation, role permissions, [quota enforcement](/guides/enforcing-quotas-in-react). Auth0, Clerk, WorkOS and Kinde each answer identity well and leave some or all of the rest to other vendors. BuildBase answers the rest, and leaves SSO to its Enterprise plan and your own WorkOS account. Whichever gap you'd rather have on your desk twelve months from now is the actual decision, not which provider's login screen looks best today. A note on sourcing: no dollar figure for Auth0, Clerk, WorkOS or Kinde appears above - only the shape of each plan, which was re-checked against each vendor's own pricing page on 24 September 2026. Each vendor's actual numbers are re-verified on the date printed on its own comparison post - 20 August 2026 for Auth0, 14 August 2026 for Clerk and Kinde, 6 October 2026 for WorkOS - and quoted there, not repeated here. Check the linked post, or the vendor's own page, before budgeting against any of them. BuildBase's own figures come from `PLANS` and `PLAN_FACTS` in `packages/shared/src/constants/platform-stats.ts`, verified 9 September 2026. --- ## Best usage-based billing tools, sorted by what happens at the limit > Usage-based billing tools compared by what actually differs now: real-time enforcement versus invoice-only metering, not the charge-model checklist. - Source: https://www.buildbase.app/compare/best-usage-based-billing-tools - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-09-03 ### In short Usage-based billing tools mostly support the same charge models now, so that is not the real choice. What differs is whether a tool only invoices after usage, like Metronome, Orb and Stripe Billing, or enforces limits at request time, the way BuildBase does for every metric but storage. Every "best usage-based billing tools" roundup ranks the same five names on the same axis: which charge models does each one support. Per-unit, tiered, graduated, package pricing - by now nearly all of them check every box. That axis stopped deciding anything. The question that actually separates these tools is what happens the moment a customer's usage crosses a limit: does the tool just note it and bill later, or does it stop the request? ### The one-paragraph answer If you are metering hundreds of millions of events a day and raw ingestion throughput is the whole problem, Metronome is still the deepest tool built specifically for that job - just know you are evaluating a Stripe product now, not an independent vendor. If the cheapest possible metering with code you can read matters more, Lago's self-hosted edition is free. If a public rate card matters more than raw depth, Stripe Billing and Chargebee both publish one, tied to a percentage of what you bill. And if you actually need enforcement, not just invoicing - stopping a request at the limit instead of surprising a customer with an overage line next month - most of the big names here do not do that natively. Metronome and Stripe Billing both meter and bill after the fact; neither stops a request at your app layer without a separate entitlements product bolted on. ### Metering and enforcement are different jobs Ask any of these vendors whether they do "real-time usage tracking" and they will say yes, and mean it. What they mean is that a usage event shows up in your dashboard within seconds, not that anything stopped a request. A metering engine counts what happened and produces an accurate bill. An enforcement layer decides, before your API returns a response, whether this specific request is even allowed to happen. Most usage-based billing tools are metering engines, and that is not a knock. Metering at Metronome's or Orb's throughput is genuinely hard, and getting the invoice right matters more to plenty of teams than blocking a request ever will. But if your actual problem is a free-tier user about to burn through ten times their allowance before the invoice even generates, a metering engine alone does not solve it. Something has to check the balance synchronously, in the request path. That is the part of BuildBase's billing module that does not show up on a feature-checklist comparison. The quota is checked synchronously, in the same call that records the usage. Overage is on by default, so usage past the plan's included allowance is billed as overage rather than refused. Turn overage off for a quota, or put the workspace on a trial, and the record call fails at the limit instead - a hard stop in the request path, not a line on next month's invoice. > **Key takeaway:** Metering tells you what happened. Enforcement stops what is about to happen. > Most usage-based billing tools do metering well; check separately whether the > one you are picking also enforces at request time, because most of the big > names do not. ### Where each tool fits **Metronome - the deepest metering engine, now inside Stripe.** Metronome built its reputation ingesting usage at extreme scale for companies like OpenAI, Anthropic and Nvidia, and Confluent's own case study on Metronome's infrastructure describes it streaming billions of events a day and processing more than 10,000 invoices per second. Stripe completed its acquisition of Metronome in January 2026, so you are evaluating a Stripe product now, not an independent vendor. Pricing is quote-only; there is no public rate card to check today. Per Stigg's published analysis of Metronome, it tracks usage balances but does not enforce them at the request level - you would add a separate entitlements layer for that. **Orb - a similar pitch, a different acquirer.** Orb's story runs parallel to Metronome's: a dedicated usage-metering and billing engine, also quote-only, also no longer independent. Adyen closed its acquisition of Orb in mid-2026 and runs it today as a subsidiary. [Lago alternatives](/compare/lago-alternatives) has the fuller rundown of both acquisitions and what they mean for a metering-engine buyer. **Lago - the free, source-published option.** Lago's self-hosted Community edition costs nothing and its code is public under AGPLv3 - genuinely free, not free-until-you-need-a-feature. What that edition drops (customer portal, automatic dunning, tax integrations) sits behind Lago Premium, priced by conversation rather than a published number. [Lago vs BuildBase](/compare/lago-vs-buildbase) covers it in more depth, including where it beats BuildBase outright. **Stripe Billing - if you already live on Stripe.** Stripe's own subscription and invoicing layer charges a percentage of billing volume on top of standard processing fees, with a Meters API for usage-based charges. It is metering and invoicing, not enforcement - nothing in Stripe Billing stops a request at your app layer on its own. [Stripe Billing alternatives](/compare/stripe-billing-alternatives) has the current published rate, verified there rather than repeated here, since percentage pricing moves and that post checks it independently. **Chargebee - subscription and dunning maturity.** Chargebee leans harder into revenue recovery than anything else on this list: automated dunning sequences, retry logic and quote-to-cash tooling built out over years of subscription-billing specialization. Pricing runs on a published rate card tied to billing volume, with an enterprise tier quoted by conversation. If the actual pain is failed payments and recovery rather than usage enforcement, Chargebee's depth there is real. **BuildBase - billing as one module, not one vendor.** The billing module runs on your own Stripe account and adds subscription plans with versioning, trials, usage-based and seat-based billing, a credit ledger, and the hard-stop enforcement described above. It is one of 20 modules in the same instance as auth, workspaces and RBAC, not a standalone billing product. There is a Free plan at $0 for 10,000 MAU, and Launch is $19 a month for 25,000 MAU; every paid plan carries a 7-day trial that does not ask for a card. | Feature | BuildBase | Metronome | | --- | --- | --- | | Limit behavior | Hard-caps at request time (all quotas but storage) | Meters and invoices; enforcement needs a separate layer | | Pricing | Free plan, then $19/mo flat (Launch), published | Custom quote, no public price list | | Event throughput | Not built for extreme-scale ingestion | Billions of events/day, 10k+ invoices/sec | | Scope | 20 modules: billing, auth, workspaces, RBAC, one instance | Metering and billing only | | Ownership | Independent (Jagodana LLC) | Part of Stripe since January 2026 | > **Where Metronome wins:** If you are metering at the volume OpenAI, Anthropic or Nvidia-scale customers > do, Metronome is built for exactly that in a way a bundled billing module is > not. Confluent's own case study on Metronome's infrastructure describes it > streaming billions of events a day and processing more than 10,000 invoices > per second - the ceiling of a system whose only job is metering, not one of 20 > modules sharing a database with auth and workspaces. If your metering volume > is anywhere near that scale, the specialization is real, and it is the honest > reason to pick Metronome over a general-purpose platform. ### How to actually decide Start with what actually breaks today, not the feature list. If a free-tier user blowing through their quota before the invoice even generates is a support ticket you have gotten, you need enforcement, and that narrows the field to tools that check the request path, not just the event log. If the problem is closer to accurate bills but messy dunning and recovery, that is Chargebee's actual strength, not a metering engine's. And if the honest answer is that billing was never the only integration you needed to replace, that is the case for a bundled platform, priced against [what building the pieces yourself costs](/blog/cost-of-building-usage-metering-yourself) rather than against a metering specialist's rate card. If entitlements and packaging experiments are the real axis, not raw metering throughput, that is a closer fit for [Stigg vs BuildBase](/compare/buildbase-vs-stigg) than for anything on this page. A note on sourcing, because roundups like this one are where stale numbers sneak in. Every BuildBase figure and the enforcement behavior above come from `PLANS`, `PLAN_FACTS` and the metered-usage service in `packages/shared/src/constants/platform-stats.ts` and `server/src/payment/stripe/services/metered-usage.service.ts`, checked 3 September 2026, with the plan prices re-read 31 October 2026. Metronome's acquisition date traces to Stripe's own announcement, and the throughput figure to Confluent's own case study on Metronome's infrastructure, both checked today. One gap remains, and it is worth naming rather than papering over. Metronome, Orb and Chargebee's current dollar pricing is not quoted anywhere above, because their pages could not be reached to re-verify it for this edition. That is deliberate: this post describes each one's pricing model rather than printing a number nobody checked today. [Lago alternatives](/compare/lago-alternatives) and [Stripe Billing alternatives](/compare/stripe-billing-alternatives) carry the rates each of them verified on their own publish day. --- ## Outseta alternatives: what actually replaces the CRM and the help desk > Most "Outseta alternatives" lists drift into HubSpot and Salesforce, tools Outseta never competed with. Here is what actually replaces its no-code login, paywall and help desk. - Source: https://www.buildbase.app/compare/outseta-alternatives - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-25 - Updated: 2026-10-22 ### In short Most Outseta alternatives lists mix in generic CRMs like HubSpot, never really what Outseta replaced. The closer no-code peers are MemberSpace and Memberstack, paywall and membership tools for Webflow-style sites without a bundled CRM or help desk. BuildBase fits once the product is a real codebase, not a page builder. Search "outseta alternatives" and roughly half the results point to HubSpot, Salesforce and Pipedrive. Those are real CRMs, and they are not what anyone paying for Outseta is actually trying to replace. ### The one-paragraph answer Cost is the most common complaint, and the fix sits close by: MemberSpace and Memberstack gate content and collect payments the same way Outseta does, minus the CRM and help desk, which is also why they tend to read cheaper against a small contact list. A thin CRM is a different complaint entirely. Pair a simpler paywall tool with a real CRM instead - nothing in this post replaces Outseta and HubSpot at once. And if the site has quietly turned into a product with a codebase behind it, BuildBase is built for that shape, though it drops the CRM and help desk too. ### What "Outseta alternative" actually means Outseta's own pitch is one login for a handful of jobs a no-code SaaS or membership site needs: gated content, subscription billing, a lightweight CRM, email, and a help desk with live chat and tickets, wired into Webflow, Squarespace and Framer through embeddable forms. Most alternatives content ignores that bundle and ranks by whatever review site happens to list Outseta under "CRM software," which is how a search for a no-code paywall tool ends up recommending Salesforce. The two tools that actually compete for the same reader are MemberSpace and Memberstack. Both live in the same "gate a Webflow site and take payments" category Outseta does. Neither ships a CRM or a help desk, which is the trade every reader leaving Outseta for one of them is making, whether or not the comparison says so out loud. ### Where each one fits **MemberSpace - the simplest swap for pure content gating.** It plugs into Webflow, Squarespace and other builders the same way Outseta does, and its whole job is member accounts and paywalled pages rather than a wider business toolkit. If the only Outseta features actually in use are the login and the paywall, MemberSpace does that narrower job without the CRM and support-desk weight sitting unused behind it. **Memberstack - more control over the login itself.** Memberstack leans further into letting a Webflow Designer own the styling of the signup and login modals directly, plus supports more custom logic around gated content than a simpler paywall tool. It is a closer fit for someone who wants member accounts to feel native to their site's design rather than dropped in as a widget. **BuildBase - once the page builder is the constraint, not the destination.** [Outseta vs BuildBase](/compare/outseta-vs-buildbase) covers this trade in more depth, but the short version: BuildBase assumes code from the start. Auth, subscription billing, [multi-tenant workspaces](/guides/multi-tenant-workspaces-in-an-afternoon) and role-based access ship as `@buildbase/sdk`, called from inside an app you are writing rather than a page you are building. It has no CRM module and no help desk module across its 20 modules - the same gap MemberSpace and Memberstack leave, just on the other side of the no-code line. | Feature | BuildBase | Outseta | | --- | --- | --- | | Integration model | SDK called from your own codebase | Embeddable JS forms plus a REST API | | No-code page builder support | Not the target use case | Native Webflow integration, works with Squarespace and Framer | | CRM | Not a module - user and audience management only | Built in, tracks contacts and deals | | Help desk / support tickets | Not a module | Built in, live chat and tickets | | Team memberships | Workspaces with per-member roles - a core module | Team mode - multiple users share one membership | | Auth methods | Built in: email/password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, Ethereum and Solana wallets, enterprise SSO (Enterprise plan, through your own WorkOS account) | Email/password and social sign-in via embedded forms | > **Where Outseta wins:** The bundle itself is the genuine advantage, and none of the three alternatives in this post fully replace it. Outseta is the only one of the four that ships a CRM and a help desk behind the same login as billing and content gating - MemberSpace and Memberstack skip both, and BuildBase has neither in its 20-module catalog either. It also supports Team mode, where several people share one membership, which is closer to how a small B2B customer actually buys than an individual paywall account. If the CRM and the support desk are pulling their weight already, replacing Outseta means adding two more vendors back, not fewer. ### Pricing, as far as it can be verified today Every price quoted for Outseta, MemberSpace or Memberstack in third-party roundups disagreed with at least one other source we checked while researching this post - not by a rounding error, but by whole tiers. That is the sign to describe the shape instead of a number nobody re-verified against the vendor's own page today. Outseta prices by contact-list size rather than by seat: a handful of tiers, unlimited team members on each, and a transaction fee that falls as the tier goes up. MemberSpace and Memberstack both price by member count with a similar declining-transaction-fee shape as an account grows. Exact tier prices and fee percentages are deliberately left out here rather than repeated from a roundup: each vendor's own pricing page is the only source current enough to quote. BuildBase prices differently again: a flat monthly fee against monthly active users rather than contacts or members, with no transaction fee. Free is $0 for 10,000 MAU, Launch is $19/mo for 25,000 MAU, Grow is $49/mo for 100,000 MAU, and Scale is $99/mo for 500,000 MAU - full detail, including workspace and storage allowances, at [/pricing](/pricing). Free has no trial and stops at its allowance; every paid plan starts with a 7-day trial that does not ask for a card. On the paid plans three quotas bill overage: workflow runs at $0.25, $0.15 or $0.10 per 1,000 on Launch, Grow and Scale, web analytics events at $2 per 100,000, and storage at $0.10 per GB-month beyond the plan allowance. Contact-based or member-based pricing and flat MAU pricing are not comparable line by line. A list-heavy, revenue-light product reads cheaper on the MAU model; a high-revenue product with a short contact list can read cheaper on a percentage-of-revenue model. Whichever shape you are actually comparing against, check the vendor's own pricing page the day you decide - the discrepancies we hit researching this post are the reason, not a hedge. ### How to actually decide Ask what is actually being used today. If it is the login and the paywall and nothing else, MemberSpace or Memberstack does that narrower job without paying for CRM and help-desk weight sitting idle. If the CRM and the support inbox are load-bearing, none of the three alternatives here are a real swap - the honest move is pairing a simpler paywall tool with a dedicated CRM, which is close to rebuilding what Outseta already bundles, just from separate vendors. And if the site has turned into a product with real users, teams and roles rather than a page with a login on it, that is the point BuildBase starts from, not Outseta's. We priced what assembling a stack from separate point tools costs in [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost) - the arithmetic holds whether the vendor list starts with Outseta or something else. Our own numbers live at [/pricing](/pricing); Outseta's, MemberSpace's and Memberstack's live on their own sites, and are worth checking before any of them go into a budget. --- ## Lago alternatives, sorted by what you are actually trying to avoid > Lago alternatives compared by what they replace: a metering engine now owned by Stripe or Adyen, a subscription specialist, or billing bundled into your own backend. - Source: https://www.buildbase.app/compare/lago-alternatives - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-24 - Updated: 2026-10-26 ### In short Leaving Lago usually means picking a replacement: Metronome and Orb, now owned by Stripe and Adyen, for deeper usage metering; Chargebee for subscription and dunning maturity; or a bundled platform like BuildBase if billing was never the only integration you needed to replace. Search "Lago alternatives" and the same five names come back on every list: Stripe Billing, Chargebee, Metronome, Orb, maybe Recurly. What none of those lists mention is that two of the five just changed hands. Stripe closed its purchase of Metronome in January. Adyen closed its purchase of Orb in July. If part of why you are leaving Lago is not wanting your metering engine's roadmap decided by someone else's acquisition, half of the standard answer just became exactly that. ### The one-paragraph answer If raw metering depth and event throughput is the whole problem, Metronome and Orb are still the deepest tools for it. Just know you are now evaluating a Stripe product and an Adyen subsidiary, not an independent vendor either way. If subscription maturity and dunning tooling at scale is the actual gap, Chargebee is built for that specifically. And if the real reason billing felt like a second job is that you were also going to need auth, workspaces and role permissions from somewhere else anyway, BuildBase bundles all of it into one instance, at the cost of the metering depth a specialist engine gives you. ### What Lago actually is Lago is an open-core usage-metering and billing engine. The self-hosted open-source edition is free and published under AGPLv3, and it handles event ingestion and seven charge models: standard, graduated, graduated percentage, package, percentage, volume and dynamic, which is the full `charge_model` enum in Lago's own API reference. What it does not include for free is the customer portal or credit notes - those sit behind Lago Premium, and automatic dunning, tax integrations and progressive billing are add-ons on top of it. Premium is sold as managed cloud or self-hosted and priced by talking to sales rather than a public rate card. See [Lago vs BuildBase](/compare/lago-vs-buildbase) if you want the full side-by-side rather than the roundup version here. ### Where each alternative fits **Metronome - deep metering, now inside Stripe.** Metronome built its name on orchestrating billing for complex usage models, with customers including OpenAI, Anthropic and Nvidia by Stripe's own account. Stripe completed the acquisition on 14 January 2026, reportedly near $1B, and Metronome now operates as part of Stripe rather than as a standalone company. The metering capability has not gone anywhere. What has changed is who owns the roadmap and, eventually, how it gets bundled with Stripe's own Billing product. **Orb - deep metering, now inside Adyen.** Orb's pitch was similar to Metronome's: a dedicated engine for translating complex usage contracts into invoices, used by companies like Vercel and Replit. Adyen announced the deal in June 2026 at $335 million in cash and closed it on 1 July. Orb runs today as an Adyen subsidiary under what Adyen calls an incubator model. Pricing for both Metronome and Orb is quote-only across every tier, so there is no public number to compare here even before the acquisitions - that part has not changed. **Chargebee - subscription and dunning maturity.** Chargebee's Flow plan is priced against the billing volume you run through it, and unlike Lago Premium the rate card is public: $0 platform fee plus 0.80% of monthly billing value pay-as-you-go, or $99/mo plus 0.65% if you commit monthly, both including 100M usage events a month. Enterprise is quoted by conversation. The percentage is the part that scales against you. What it buys is depth: Chargebee's dunning and revenue-recovery tooling, plus its quote-to-cash add-ons, go further than anything Lago, BuildBase or a from-scratch Stripe integration ships out of the box. **Stripe Billing - if you already live on Stripe.** Stripe's own subscription and invoicing layer charges 0.7% of billing volume on top of standard processing fees, with a Meters API for usage-based charges and Smart Retries for automated dunning. The percentage applies to recurring volume billed on and off Stripe, and one-off invoices are excluded. See [Stripe Billing alternatives](/compare/stripe-billing-alternatives) for the fuller breakdown of that side of the field. **BuildBase - billing as one module, not one vendor.** The billing module runs on the org's own Stripe account and adds subscription plans with versioning, trials, usage-based and seat-based billing, a credit system with ledger tracking, and per-workspace invoicing - it is not a standalone metering product, it is one of 20 modules in the same instance as auth, workspaces and RBAC. There is a Free plan with 10,000 MAU that stops at its allowance, and paid plans from $19/mo: Launch covers 25,000 MAU, and Grow and Scale raise every ceiling from there. Every paid plan starts with a 7-day trial that does not ask for a card. | Feature | BuildBase | Lago | | --- | --- | --- | | Self-hosted, free tier | Not free - Docker self-host on a paid plan | Free under AGPLv3, self-hosted | | Entry paid plan | $19/mo (Launch), flat | Lago Premium, quote-only | | Charge models | Usage and seats with graduated or volume tiers, add-ons (one-time, lifetime, recurring) and credits, on your own Stripe | Seven models: standard, graduated, package, volume, and more | | Ownership | Independent (Jagodana LLC) | Independent - unlike Metronome (Stripe) and Orb (Adyen) | | Scope | 20 modules: billing, auth, workspaces, RBAC, one instance | Billing and metering only | > **Where Lago wins:** Two things Lago does better, and neither is close. > > **Metering throughput.** ClickHouse's own case study on Lago's migration to ClickHouse Cloud describes one customer's ingestion needs approaching a million events per second. Read the top figure as a demonstrated ceiling for one customer rather than a guarantee, but the shape is real - a bundled billing module is not going to out-throughput a system built for exactly this job. > > **A genuinely free, source-published self-hosted tier.** Lago's self-hosted edition costs nothing and the code is public under AGPLv3 on GitHub. Lago has stopped branding it the "Community edition" on its own pricing page, but the free self-hosted route is still there, as a "Deploy open source" link straight to the repository. BuildBase's self-hosted option runs on your own infrastructure too, but it is not free and it is not published under an open license - you are paying for the platform either way. ### How to actually decide Ask what you were actually leaving Lago for. If the honest answer is "I need Premium features and don't want a quote-only price," Metronome and Orb hand you the same problem under a different logo now that both are quote-only subsidiaries of larger payment companies. Chargebee and Stripe Billing at least publish a number, and both of those numbers are a percentage of what you bill - run that rate against [the crossover point where it costs more than a flat plan](/blog/billing-platform-revenue-tax) before assuming either one is cheap at your revenue level. If the honest answer is "billing was never the only integration I needed," that's the case for a bundled platform, and the tradeoff is giving up the metering depth a dedicated engine gives you in exchange for not building auth, workspaces and RBAC as three more vendor relationships. We priced what that separate-vendor stack costs in [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost), and what wiring workspaces and RBAC looks like on its own in [multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon). And if the honest answer is "entitlements and packaging experiments are the actual axis, not raw metering throughput," that's a closer fit for [Stigg vs BuildBase](/compare/buildbase-vs-stigg) than for anything else on this page. Both completion dates above trace to the acquirer's own announcement: Stripe's newsroom post for Metronome, Adyen's press release for Orb. Adyen states its $335 million figure directly; Stripe has not officially disclosed Metronome's deal size, so the ~$1B figure here is a widely reported estimate, not a vendor-confirmed one. Every BuildBase figure comes from `PLANS` and `PLAN_FACTS` in `packages/shared/src/constants/platform-stats.ts`, verified 9 September 2026. The Chargebee and Stripe Billing rates were read off chargebee.com/pricing and stripe.com/billing/pricing, verified 26 October 2026, and neither had moved. Lago's licence was read off its GitHub repository and its charge models off its own API reference on the same date. Percentage pricing moves, so check both before budgeting against them. --- ## Stripe Billing alternatives, sorted by what they actually replace > Stripe Billing alternatives compared by what they replace: a metering engine like Lago or Orb, a merchant of record like Paddle, or billing bundled into the rest of your backend. - Source: https://www.buildbase.app/compare/stripe-billing-alternatives - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-23 - Updated: 2026-11-02 ### In short Stripe Billing alternatives split into three shapes: metering engines like Lago and Orb where you stay merchant of record, platforms like Paddle that take over tax and compliance as merchant of record, and bundled options where billing rides on your own Stripe account alongside auth and workspaces. Every "Stripe Billing alternatives" list on the first page is written by a billing vendor putting itself near the top of its own roundup. That's a conflict of interest hiding in plain sight, and it also skips the question that actually decides which alternative fits: are you replacing the billing engine, or replacing who is legally selling to your customer? Those are different problems, and most of what ranks answers only the first one. ### The one-paragraph answer Complex usage-based pricing - dimensional charges, prepaid credits - points to Lago or Orb, both billing-layer tools built for exactly that, with your own Stripe account still underneath. Tax and compliance overhead across regions is Paddle's job: it and similar merchant-of-record platforms take that off your plate entirely, at the cost of becoming the seller of record instead of you. Dunning and revenue-recovery sophistication for a subscription business at scale is where Chargebee's add-ons live. And if the real gap was never billing alone - if auth, workspaces and role permissions were always going to be separate purchases too - BuildBase bundles billing into the same instance, running on the Stripe account you already have. It has none of the automated dunning or revenue-recognition tooling the billing specialists sell as their core product, though. ### What Stripe Billing actually is Stripe Billing is the subscription and invoicing layer Stripe added on top of its payment processing: recurring plans, usage-based pricing via its Meters API, a customer portal, and automated dunning with machine-learning-optimized retry timing. Its default shape is 0.7% of billing volume on top of standard card-processing fees, so the cost of the billing layer alone scales with how much you invoice - [the crossover math for when that kind of fee costs more than a flat plan](/blog/billing-platform-revenue-tax) shows how fast that scaling adds up. There is a flat-fee escape, but it is a sales conversation rather than a self-serve toggle: a one-year contract at $620, $1,500, $2,950 or $5,750 a month covering up to $100,000, $250,000, $500,000 or $1,000,000 of monthly billing volume, with 0.67% above the cap. If you are reading this page you are almost certainly on the 0.7%. Stripe has changed this pricing shape before, so check stripe.com/billing/pricing before you budget against it. ### Where each alternative fits **Lago - the open-core metering engine.** Lago's self-hosted edition is free and published under AGPLv3 on GitHub. It handles usage-based billing and event ingestion in more depth than a bundled module attempts, but Lago Premium, offered as managed cloud or self-hosted, is priced by talking to sales rather than a public rate card. See [Lago vs BuildBase](/compare/lago-vs-buildbase) for the full breakdown - that comparison is worth reading directly before assuming a quoted Premium number holds today - or [Lago alternatives](/compare/lago-alternatives) if Lago itself is what you're trying to replace. **Orb - built for complex usage pricing.** Orb has started publishing a number, which it did not do when this post first ran. Its page now shows two tiers rather than three: Business, self-serve at $6.00 per credit with volume discounts and 100 free credits to test on, and Enterprise by quote. A credit is not a billing-volume percentage, it is consumed across dimensions - billings processed, events ingested - and the page's own FAQ puts one credit at "0.60% of billing volume, plus event ingestion and other metered dimensions" without reconciling that against the $6.00, so the headline is a starting point rather than a bill you can compute. What is public either way is the shape: volume discounts, multi-axis pricing, prepaid credits and threshold billing, aimed at products whose pricing model is itself complicated enough to need a dedicated engine. If Lago's open-core model doesn't fit your deployment preference, Orb is the other name that comes up for the same underlying problem. **Chargebee - dunning and quote-to-cash at scale.** Chargebee's self-serve billing plan, now named Flow, is priced two ways: pay-as-you-go at 0.80% of monthly billing value with no platform fee, or $99/mo plus 0.65% of monthly billing value. Its own slider marks the crossover at $66,000 of monthly billing value, which is where the platform fee starts paying for itself. Revenue recognition and the growth tooling are separate products with their own quotes, aimed at more complex, contract-heavy billing than a startup's first pricing page. That specialization is real, and it's also the fairness beat below - it's a capability neither BuildBase nor a from-scratch Stripe integration ships out of the box. **Paddle - merchant of record, tax handled.** Paddle takes over as the legal seller of your product, which means it also takes over sales tax, VAT and GST compliance across every region it operates in, along with fraud protection and chargeback handling. The tradeoff for handing over that surface area is 5% + 50¢ per checkout transaction rather than a flat subscription price, which is the most expensive shape on this page per dollar collected and the only one that buys you out of filing tax returns. **BuildBase - billing as one module, not one vendor.** BuildBase's billing module runs on the org's own Stripe account and adds subscription plans with versioning, free trials, usage-based and seat-based billing with graduated or volume tiers, add-ons (one-time, lifetime or recurring), a credit system with ledger tracking, and per-workspace invoicing - see [charging per API call in Next.js](/guides/charge-per-api-call-nextjs) for what the usage-based half looks like in a route handler. It's built to replace hand-rolled Stripe wrapper code, not Stripe itself. There's a Free plan at $0 that stops at its allowance rather than billing, and paid plans start at $19/mo for Launch with 25,000 MAU; Grow and Scale raise every ceiling from there. The paid plans open with a 7-day trial that doesn't ask for a card. The tradeoff for the bundle is depth: none of Stripe's Smart Retries, no dedicated revenue-recognition module, no merchant-of-record option. If billing was the only system you needed replaced, a specialist on this page beats us on that dimension specifically. | Feature | BuildBase | Stripe Billing | | --- | --- | --- | | Scope | 20 modules: billing, auth, workspaces, RBAC, one instance | Billing and invoicing only, part of the Stripe payments platform | | Payment processor | Runs on the org's own Stripe account | Is the payment processor | | Pricing shape | Flat monthly/yearly/quarterly plan price | 0.7% of billing volume, plus processing fees | | Failed-payment recovery | Owner notices and Workflows on a failed payment, a warning 30 days before a card expires, and a retention offer or pause at cancel | Smart Retries - ML-optimized automatic retry timing | | Auth and workspace RBAC | Included | Not provided - Stripe Billing is billing only | > **Where Stripe Billing wins:** Stripe Billing ships Smart Retries and automated revenue recognition as part of the same product, and BuildBase has neither. A failed payment in BuildBase fires a workflow event you can react to - send an email, start a dunning sequence yourself - but there's no built-in machine-learning model deciding when to retry a declined card, and no revenue-recognition reporting for teams that need ASC 606-style numbers. If failed-payment recovery at scale or accounting-grade revenue recognition is the actual requirement, that's a real gap in the bundle, not a missing feature we'd frame as a non-issue. ### How to actually decide The three buckets above are three different maintenance burdens, and picking one means naming which you're actually stuck with. Metering depth means pricing out [Lago vs BuildBase](/compare/lago-vs-buildbase) or getting Orb on a call. If entitlements and packaging experiments are the actual axis rather than raw event throughput, [Stigg vs BuildBase](/compare/buildbase-vs-stigg) is the more relevant comparison. Tax and compliance load means Paddle - no billing-layer tool on this page, BuildBase included, takes that off your plate. And if auth, workspace roles and a workflow engine were always going to be separate purchases too, [the real cost of wiring a stack together yourself](/blog/auth-billing-stack-cost) prices out what that adds up to. Every vendor figure on this page was read off the vendor's own pricing page and verified 2 November 2026: Stripe Billing at 0.7% of billing volume pay-as-you-go, Chargebee Flow at 0.80% pay-as-you-go or $99/mo plus 0.65%, Paddle at 5% + 50¢ per checkout transaction, and Lago free to self-host under AGPLv3 with Premium quote-only. One figure moved and it moved into existence: Orb published a self-serve price for the first time, $6.00 per credit on a Business tier, where this post previously recorded no public number at all. Percentages move without an announcement, so re-check before you budget. Our own numbers come from `PLANS` in `packages/shared/src/constants/platform-stats.ts`, verified 31 October 2026. --- ## Supabase alternatives: Firebase, Appwrite, Nhost, PocketBase and when none of them are the fix > Supabase alternatives compared by what they actually replace - the database, the auth layer, or the billing and workspace layer Supabase never had in the first place. - Source: https://www.buildbase.app/compare/supabase-alternatives - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-22 - Updated: 2026-11-02 ### In short Firebase, Appwrite, Nhost and PocketBase are the direct Supabase swaps - same category, different database tradeoffs, none with built-in billing or workspace roles. If that is the actual gap, BuildBase bundles billing, RBAC and workflows alongside auth in one SDK, against a database you never touch directly. Every "Supabase alternatives" list sorts by the same axis: relational versus document store, managed versus self-hosted, SQL versus GraphQL. That question matters if the database is what's bothering you. It says nothing if what's bothering you is that Supabase, like every name on these lists, never shipped a billing product or a workspace. ### The one-paragraph answer Leaving Supabase for a different database shape? Firebase, PocketBase and Appwrite are the honest picks, each trading Postgres for something else - Firestore, embedded SQLite, or a fuller self-hosted stack. Nhost keeps you on Postgres and swaps in Hasura's GraphQL layer instead, which is a narrower bet worth making only if GraphQL was already the plan. None of the four add subscription billing or workspace roles. They replace the database, not what sits above it. If that layer is the actual gap, BuildBase is worth a look for the same reason it belongs on the [Firebase alternatives](/compare/firebase-alternatives) list: 20 modules including billing and per-workspace RBAC, bundled into `@buildbase/sdk`, against a database you never touch directly. ### What Supabase actually leaves you to build Supabase leaves you to build billing and workspace roles entirely on your own, and every alternative on this list does too. Supabase itself is a managed Postgres instance with auto-generated REST and GraphQL APIs, realtime subscriptions on table changes, and its own auth, storage and edge functions on top. The database is the product - everything else exists to make it easier to reach from a client app. Every alternative here inherits that gap. None of them are SaaS platforms, so a Postgres row has no idea what a subscription plan is. You model billing and workspace membership yourself, then keep that logic in sync by hand, every time the product changes, which is more of a maintenance job than anyone signs up for. See [Supabase vs BuildBase](/compare/buildbase-vs-supabase) for the full breakdown, feature by feature. ### Where each alternative fits **Firebase - the mobile-first swap.** Firestore trades Postgres rows for a document store, paired with Firebase Auth, Cloud Functions and native client SDKs across iOS, Android, Flutter and Unity. If mobile reach or offline-first sync is the actual requirement, this is the only name on this list built for it - see [the full Firebase comparison](/compare/firebase-vs-buildbase) and the [Firebase alternatives roundup](/compare/firebase-alternatives) for where it sits against the others. Pricing is the Spark free tier or Blaze, which is pure pay-as-you-go metered against Google Cloud rates rather than a monthly plan. It carries the same absence of billing and workspace RBAC that sent you looking in the first place. **Appwrite - open source, self-hosted from day one.** Appwrite covers database, auth, storage and functions, and its managed cloud runs the same code you'd run on your own servers. That's a direct answer to vendor lock-in - self-host the exact stack you'd otherwise rent, and the hosting bill is whatever your own servers cost. On the cloud side there's a free tier and a paid Pro plan; check appwrite.io for its current price, which its pricing page did not state when we last looked. RBAC and billing don't disappear either way, though. Appwrite hands you the primitives, not the feature. **Nhost - Postgres plus GraphQL, if that's the stack.** Nhost is the closest like-for-like Supabase swap on this list: managed Postgres, auth, storage and serverless functions, with Hasura's GraphQL layer sitting in front instead of Supabase's own API generator. There's a free Starter tier, and Pro is from $25/mo with $15 of compute credits included and the excess billed per vCPU on top, so the headline price is a floor rather than the bill. Worth choosing over Supabase itself mainly if GraphQL specifically, not REST, is what the team already wants. **PocketBase - the single-binary option.** PocketBase is a different shape entirely: one self-hosted binary with embedded SQLite, built-in auth, realtime subscriptions and an admin UI, and no managed cloud product at all. It's free because there's no vendor charging for it - your only cost is wherever you run the binary. That also means no roadmap to depend on, and no support line to call when something breaks at 2am. It is still pre-1.0, on v0.41.1 as of 2 November 2026, which is worth knowing before it goes under something that has to stay up. **BuildBase - when the SaaS layer was the actual gap.** If none of the four above solves the real problem - a paying customer needs a workspace, a workspace needs members, a member needs a role, and a plan change has to update all three at once - that's the layer none of them sell. BuildBase bundles [subscription billing and credit metering](/guides/charge-per-api-call-nextjs), [workspaces with RBAC](/guides/multi-tenant-workspaces-in-an-afternoon), workflow automation and user-facing sign-in by email/password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO on the Enterprise plan through your own WorkOS account, plus API tokens for server-to-server calls, into `@buildbase/sdk`. There's a Free plan at $0 for 10,000 MAU, 50 workspaces and 1GB storage, which stops at its allowance rather than billing. Paid plans start at $19/mo for Launch, with 25,000 MAU, 1,000 workspaces and 10GB storage, after a 7-day trial that doesn't ask for a card; Grow and Scale raise every one of those ceilings. PocketBase still costs nothing at all, at any size you can host. Current numbers live at [/pricing](/pricing). | Feature | BuildBase | Supabase | | --- | --- | --- | | Entry price | Free plan, then Launch at $19/mo - 7-day trial without a card | Free tier, then Pro at $25/mo with MAU, disk and storage metered above the included allowance | | Database | Not a product feature - bring your own | Managed Postgres, direct SQL access | | Subscription billing | Built in, credit metering included | Not provided - wired to your own Stripe account | | Workspace RBAC | Built in, roles and permissions per workspace | Not a feature - modeled in your own schema | | Self-hostable | Proprietary SaaS, self-hosted deployment available | Self-hostable end to end (see Fairness note below) | | Realtime | Real-time Slack alerts on events; audience segments update periodically | Realtime subscriptions on raw table changes | | Auth methods | Built in: email/password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, Ethereum and Solana wallets, enterprise SSO (Enterprise plan, through your own WorkOS account) | Email, magic links and social providers on your own Postgres row | > **Where Supabase wins:** Three things Supabase does that BuildBase genuinely does not, and none are close calls. Supabase gives you a real Postgres instance you can run arbitrary SQL against, install extensions on and connect any Postgres client to. BuildBase exposes no database to query directly - everything goes through the SDK instead. Self-hosting is the second one. Supabase is open source and self-hostable from the ground up, database included. BuildBase offers a self-hosted deployment instead, but the platform itself stays proprietary. Realtime is the third: Supabase streams row-level changes straight from Postgres to a client, where BuildBase's realtime story is event-based Slack alerts, not a live feed of your data. Want any of those three? Supabase is built for it and we are not. ### How to actually decide Match the alternative to the gap you actually hit, not the one every roundup assumes. Want a different database shape - document store, embedded SQLite, or GraphQL over Postgres? Firebase, PocketBase and Nhost answer that directly, and Appwrite adds a fuller self-hosted stack to the same question. Want to remove the vendor entirely and own the infrastructure? Appwrite or PocketBase, depending on how much stack you want to run yourself. And if the real gap was never the database - if it was that a paying customer needed a workspace, a role, and a subscription that stayed in sync, and Supabase was never going to give you any of the three - that's what [Supabase vs BuildBase](/compare/buildbase-vs-supabase) and [the real cost of stitching a stack together yourself](/blog/auth-billing-stack-cost) go into in more detail than a roundup like this one can. Every competitor figure above was read off the vendor's own pricing page and verified 2 November 2026: supabase.com/pricing, firebase.google.com/pricing, appwrite.io/pricing and nhost.io/pricing. Nothing this post leans on had moved: Supabase Pro still starts at $25/mo, Nhost Pro still at $25/mo with compute on top, Appwrite still prints no price for the Pro plan its own FAQ refers to, and Firebase still splits into the no-cost Spark tier and pay-as-you-go Blaze. PocketBase publishes no pricing at all, because it ships as a self-hosted binary rather than a paid product; it was on v0.41.1 the day this was checked, still short of 1.0. All four of the paid ones meter something above the headline plan - MAU, compute, storage or egress - so treat the monthly number as a floor and check the page yourself before you budget against it. Supabase in full detail is in [Supabase vs BuildBase](/compare/buildbase-vs-supabase), and Firebase in [Firebase vs BuildBase](/compare/firebase-vs-buildbase). --- ## Firebase alternatives, sorted by what you are actually replacing > Firebase alternatives compared by what they actually replace - the database, the auth layer, or the SaaS layer Firebase never had in the first place. - Source: https://www.buildbase.app/compare/firebase-alternatives - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-21 - Updated: 2026-11-02 ### In short Supabase replaces Firestore with Postgres; Appwrite self-hosts the stack and now offers Postgres too. Neither adds subscription billing or workspace RBAC, because Firebase never had those either. If that is the gap, the shortlist changes: BuildBase bundles billing and per-workspace roles alongside auth in one SDK. Most "Firebase alternatives" lists sort by database. Document store or Postgres, managed or self-hosted, and then a feature grid comparing reads and writes. That sorts for the wrong question if the reason you are looking is not Firestore at all - it is that Firebase never shipped a billing product, never modeled a workspace, and never had a concept of a role. ### The one-paragraph answer If you are leaving Firebase because you want a relational database, self-hosting, or a more open license, Supabase and Appwrite are the honest picks - both replace Firestore and Firebase Auth directly, one managed on Postgres and one self-hostable end to end. But if the client SDK reach or realtime sync was never the point, and what you actually needed was subscription billing, per-workspace roles and a workflow engine wired to the same auth, that is a different shortlist - and it is one Supabase and Appwrite do not answer either. They replace the database, not the SaaS layer sitting above it. BuildBase belongs on that second list, not as a Firebase clone but as a narrower, more opinionated bet: 20 modules including billing and RBAC, in one SDK, against a data model that already knows what a workspace is. ### What Firebase actually leaves you to build Firebase is Google's mobile and web backend: Firestore for data, Firebase Auth for identity, Cloud Functions for logic, Hosting for static assets, with Crashlytics, Google Analytics and Remote Config bundled in. Every one of the alternatives below inherits the same shape of gap, because none of them are SaaS platforms either - they are backend-as-a-service, the same category Firebase made mainstream. Firestore has no concept of a subscription plan or a workspace member. You model both yourself, in security rules and Cloud Functions, and you keep that logic in sync by hand every time the product changes. See [Firebase vs BuildBase](/compare/firebase-vs-buildbase) for the full breakdown of what that costs against a bundled SDK, feature by feature. ### Where each alternative fits **Supabase - the direct Firestore-and-Auth swap.** Supabase pairs a real Postgres database with its own auth service, storage and realtime layer, on a free tier that includes 50,000 monthly active users, plus paid plans that scale with MAU and compute. If the appeal of leaving Firebase is a relational database you can query with SQL instead of security-rule gymnastics, or infrastructure you can eventually self-host, this is the closest like-for-like swap on this list. It still has no native subscription billing or workspace RBAC - see [Supabase vs BuildBase](/compare/buildbase-vs-supabase) for the pricing detail and where that gap shows up in practice. Leaving Supabase itself rather than Firebase? The [Supabase alternatives roundup](/compare/supabase-alternatives) covers the same ground - Firebase, Appwrite, Nhost and PocketBase - from the other direction. **Appwrite - open source, self-hosted from day one.** Appwrite covers the same ground as Firestore and Firebase Auth - database, auth, storage, functions - and its managed cloud runs the same software you would run on your own servers. That is a direct answer to the complaint Firebase itself invites: if you are worried about being tied to one vendor's pricing and roadmap, self-hosting the exact stack you would otherwise pay for removes the question entirely. Its serverless tier carries no fixed fee and bills per use. One allowance is now printed, $10 of compute credits a month for database usage, but the read and write quotas are still shown as a plan limit with an overage and no number attached, including in the compare-plans table. Since this post first ran, Appwrite has added a managed Postgres product you reach over the ordinary Postgres wire protocol with psql or an ORM, rather than through an Appwrite SDK, which retires the neat shorthand that Supabase is the relational pick and Appwrite the document one. How finished it is depends which Appwrite page you read: the databases overview labels PostgreSQL beta, while the Postgres product page prints no stage at all. Treat it as beta and confirm before you build on it. The tradeoff is that subscription billing and workspace roles are no more a product here than they are in Firebase - Appwrite gives you the primitives to build them, not the feature itself. **Nhost - Postgres plus GraphQL, if that is the stack.** Nhost bundles a managed Postgres database behind Hasura's GraphQL layer, with auth, CDN-backed storage, and functions alongside it. It is a narrower bet than Supabase - you are opting into GraphQL as the query interface rather than choosing it later - but for a team that already wants Hasura, it collapses "database plus GraphQL API plus auth" into one bill instead of three. **BuildBase - when the SaaS layer was the actual gap.** If none of the above solves the real problem - a paying customer needs a workspace, a workspace needs members, a member needs a role, and a plan change needs to update all three at once - that is the layer none of these tools sell, ourselves included in the "database" sense, since we are not one. BuildBase bundles [subscription billing and credit metering](/guides/charge-per-api-call-nextjs), [workspaces with RBAC](/guides/multi-tenant-workspaces-in-an-afternoon), workflow automation and user-facing sign-in by email/password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO on the Enterprise plan through your own WorkOS account, plus API tokens for server-to-server calls, into `@buildbase/sdk`. There is a Free plan with 10,000 MAU, and paid plans from $19/mo: Launch covers 25,000 MAU, 1,000 workspaces and 10GB storage, and Grow and Scale raise every one of those ceilings. The paid plans start with a 7-day trial that does not ask for a card. Current numbers live at [/pricing](/pricing). | Feature | BuildBase | Firebase | | --- | --- | --- | | Database | No general-purpose database - Collections stores custom schemas, read by slug over a token-authenticated REST API | Firestore, document store with realtime listeners | | Subscription billing | Built in, credit metering included | Not provided - you wire up your own payment provider | | Workspace RBAC | Built in, roles and permissions per workspace | Not a feature - modeled in Firestore security rules | | Self-hostable | Proprietary SaaS, self-hosted deployment available | Not currently - Google-managed only | | Mobile / native client SDKs | Web-focused: Next.js, Vite, React Router / Remix, TanStack Start, Express, NestJS, Fastify, Hono, Astro | iOS, Android, Flutter, Unity, C++, Web | | Realtime data sync | Not a product feature | Firestore realtime listeners with offline support | > **Where Firebase wins:** Two things Firebase does better than every alternative on this page, BuildBase included, and neither is small. Its client SDKs cover Apple, Android, Flutter, Unity and C++ on top of the web - if you are shipping a mobile app or a game, that platform reach is not something a Postgres swap or a bundled SaaS SDK replicates. And on Apple, Android and web, Firestore caches the data your app is actively using so the app keeps working offline, then syncs local changes back when the device reconnects. Worth being precise there, because the offline story is easy to read more into than Firebase actually claims. The docs say persistence is supported "only in Android, Apple, and web apps", so it follows the platform rather than the framework: a Flutter app gets it on Apple, Android and web, and the offline pages say nothing at all about Unity or C++. On the web it runs in Chrome, Safari and Firefox only. And when two clients edit the same document, Firebase's own words are "last write wins", with no merge strategy on offer. Even so, that is the part of offline-first software most teams get wrong on a first attempt. If your product's core value is mobile reach or live collaborative data, stay on Firebase - this post is about what to reach for once that is no longer the deciding factor. ### How to actually decide Match the alternative to the gap you actually hit, not the one every roundup assumes. If it is the database - you want SQL, or you want the option to self-host - Supabase or Appwrite replace Firestore directly, and now that both can put Postgres under you, the choice between them is how much of the stack you want to run yourself rather than relational versus document. Want GraphQL specifically? Nhost is worth a look before the other two. And if the real gap was never the database at all - if it was that a paying customer needed a workspace, a role and a subscription that stayed in sync, and Firebase was never going to give you any of the three - that is the question [Firebase vs BuildBase](/compare/firebase-vs-buildbase) and [the real cost of stitching a stack together yourself](/blog/auth-billing-stack-cost) answer in more detail than a roundup like this one can. Exact dollar figures for Firebase and Supabase are deliberately left out of the body above - re-check them in [the full Firebase comparison](/compare/firebase-vs-buildbase) and [Supabase vs BuildBase](/compare/buildbase-vs-supabase), each of which carries its own verification date against the vendor's own pricing page. Every competitor figure in this post was read off the vendor's own pricing page and verified 2 November 2026: supabase.com/pricing, appwrite.io/pricing, nhost.io/pricing and firebase.google.com/pricing. No price or quota this post leans on had moved: Supabase still includes 50,000 monthly active users on its free plan, Firebase Auth still includes 50,000 on Spark, Appwrite's dedicated databases still read from $10/mo per database, Appwrite still prints the $10 monthly compute credit for database usage, and Appwrite still does not print a price for the Pro plan its own FAQ refers to. The PostgreSQL stage is unresolved: the databases overview says beta, the product page says nothing. Firebase's page splits Firestore into Standard and Enterprise editions, so a quota you look up there has to be read against the right one. Nhost prints Pro as from $25/mo with $15 in compute credits included and the excess billed past them, so treat the headline as a floor rather than the bill, and note that compute is priced separately per vCPU core, $15 a month shared or $50 dedicated. Read appwrite.io/pricing and nhost.io/pricing directly before you budget against either. Firestore's per-operation rate is not on Firebase's own pricing page even in the linked comparison, since it defers to Google Cloud pricing, which sets reads, writes, deletes and storage by location - Firebase's own billing doc says exactly that, which is why no per-operation figure appears anywhere in this post. --- ## Auth0 alternatives: the point-solution trap nobody mentions > Every Auth0 alternatives list compares login boxes. The cost nobody counts is the three or four other tools you still have to stitch on separately. - Source: https://www.buildbase.app/compare/auth0-alternatives - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-20 - Updated: 2026-10-22 ### In short Most Auth0 alternatives - WorkOS, Clerk, SuperTokens, Kinde - are just other identity providers, swapping one login box for another. The harder question is whether you also need separate billing, workspace and workflow tools, or whether one platform can replace more of the stack at once. Search "auth0 alternatives" and every result compares the same thing: login boxes. Okta versus Cognito versus Clerk versus WorkOS, ranked by MAU pricing and SSO connectors. Nobody asks the question that actually decides it for most teams leaving Auth0, which is whether auth was ever the only tool they were paying for separately. ### The one-paragraph answer If your complaint is that enterprise SSO pricing punishes you for having customer volume rather than enterprise customers, look at WorkOS - it separates the free consumer-scale tier from a per-connection charge for SSO and directory sync, so you pay for the enterprise buyers you actually have. If the complaint is that Auth0's integration surface means weeks of custom sign-in UI, Clerk's prebuilt components are the direct answer. If the real objection is vendor lock-in and unpredictable per-user cost as you scale, SuperTokens' open-source core lets you self-host the same code that runs in its managed cloud. If you want the free tier that includes the most rather than the one with the highest ceiling, with MFA and B2B organizations in the box rather than gated behind a paid plan, that's Kinde. And if the honest answer is that auth was never the only separate tool - that billing, workspaces and workflow automation were always going to be their own line items too - BuildBase replaces more of that stack in one instance, though its MFA is not the range of factors Auth0 ships, and its enterprise SSO (SAML and OIDC) is on its Enterprise plan only, through your own WorkOS account, where Auth0 includes a connection on its free plan. ### What actually drives people to look Auth0's pricing runs on monthly active users, and the jump from the free tier to the first paid plan is where most complaints start. The free plan covers 25,000 monthly active users, but the paid ladder does not begin where it ends - paid plans are quoted from 500 MAU, at $35 a month for B2C Essentials and $150 for B2B Essentials. What that same plan costs at your real user count is a different number entirely, and it is the one worth checking before you plan around the free tier. The features a growing SaaS needs next sit behind that jump too: MFA factors are not on the free plan at all, enhanced attack protection starts at Professional, and enterprise connections beyond the first one included free are a paid tier or a per-connection charge. A private cloud deployment goes further still, into a custom-quoted enterprise tier with no published number. None of that is unique to Auth0. It's the standard shape of MAU-metered identity pricing, and every alternative in this post prices some version of the same trade-off differently. The difference is _where_ each one draws the line between what's free, what's metered, and what's a separate add-on - and that is the actual comparison, not "which vendor is cheaper." The numbers in this post were checked against each vendor's page on the day it shipped, and they will move; the shape of the trade is the part that lasts. ### Where each alternative fits **WorkOS - unbundling the enterprise-SSO tax.** WorkOS's core auth product (AuthKit) is free for the first 1M monthly active users, and enterprise features are priced separately, at $125 per SSO or directory-sync connection per month for the first fifteen, rather than folded into a single MAU-based jump. The shape is the point: a team serving a handful of enterprise customers pays for a handful of connections, not for crossing a company-wide user threshold. This is the pick if your actual complaint is that Auth0 charges you for total user volume when the feature you need is really about a small number of enterprise buyers. **Clerk - the integration-time complaint, directly.** Clerk ships prebuilt, brandable sign-in, sign-up and user-management components, plus an organizations model with SAML and OIDC enterprise connections. The free Hobby plan covers 50,000 monthly retained users and Pro is $25 a month carrying the same 50,000, with one enterprise connection included and additional ones from $75 a month each. If the actual cost you're trying to cut is engineering weeks spent building custom auth UI around Auth0's APIs, this is the alternative that answers it, at the cost of being more opinionated about how your frontend is structured. **SuperTokens - the lock-in complaint.** SuperTokens' core, covering email/password, passwordless, social login and session management with token rotation, is open source. The managed cloud and a self-hosted deployment run the same code, so choosing managed now doesn't forfeit the option to self-host later. Some features are metered add-ons even when self-hosted: MFA is $0.01 per monthly active user against a $100 monthly minimum, and multi-tenancy is quoted rather than published. Read that line before assuming self-hosting removes cost entirely rather than shifting it to infrastructure and add-on fees. **Kinde - the most included on the free plan.** Kinde's free ceiling is the lowest of the four here at 10,500 monthly active users, with Pro at $25 a month above that. What it bundles into that plan is the point: MFA and B2B organizations are both in it rather than gated behind a paid tier, which is a direct answer to the complaint that Auth0's free and early paid plans hold back the security features a growing product actually needs. Kinde also includes subscription billing in the same product, which is worth noting for the next section. | Feature | BuildBase | Auth0 | | --- | --- | --- | | Scope | 20 modules: auth, billing, workspaces, workflows, RBAC, one instance | Identity and access management, plus adjacent security tooling | | Enterprise SSO / SAML | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | 1 free, 3 from B2B Essentials, none on B2C paid | | MFA | Authenticator app with backup codes, or text-message codes | Available - not on the free plan, paid tiers only | | Compliance certification | GDPR-ready, CCPA-ready (not independently certified) | Audited SOC 2 and ISO 27001, via parent Okta | | Free plan | Free up to 10,000 monthly active users; paid plans have a 7-day trial, no card | Free up to 25,000 monthly active users | | Billing and workspaces | Included as separate modules in the same instance | Not offered - a separate purchase | ### The point-solution trap Every option above, Auth0 included, is still answering one question: who logs in. None of them touch what happens after that - how you bill the account, how you isolate one customer's data from another's, what fires when a trial converts or a payment fails. Teams on Auth0 are usually also running a separate billing integration, a homemade or third-party multi-tenancy layer, and some workflow tool stitching the two together, because none of the identity-focused alternatives above are trying to be those things either. That's a real trade, not a knock on any of them - a team that only needs identity gets a more focused product from a specialist. But if the reason you're evaluating alternatives is a broader one, that auth was never the only separate vendor relationship you were maintaining, it's worth pricing the consolidated option alongside the identity swap, not after it. [The real cost of stitching Clerk, Stripe and Lago together](/blog/auth-billing-stack-cost) walks through what that math looks like when you count every tool, not just the login box. And if the alternative on the table is skipping every vendor and building login yourself, [what that costs in engineer-hours](/blog/cost-of-building-auth-yourself) is the other side of the same math. > **Where Auth0 wins:** Auth0 is covered by Okta's SOC 2 and ISO 27001 certifications, audited by a third party and listed on Okta's security trust page. BuildBase has neither audit; it is GDPR-ready and CCPA-ready, which are readiness claims, not certifications. Auth0 also ships enterprise SSO and SAML on its self-serve plans. BuildBase has SSO only on its Enterprise plan, through your own WorkOS account, and its MFA is an authenticator app with backup codes, with text-message codes as a weaker option. If your buyer's security team requires an audited certificate on file, or your product needs SAML-based enterprise sign-in today without a custom plan, use Auth0 or WorkOS, which is built specifically around that connection model. ### How to actually decide Match the alternative to the complaint you actually have, not the one most "Auth0 alternatives" posts assume. If it's the enterprise-SSO pricing shape, [WorkOS vs BuildBase](/compare/workos-vs-buildbase) covers WorkOS's per-connection model against a bundled instance in more depth. If integration time on the UI side is the real cost, Clerk's prebuilt components are worth pricing against the engineering weeks they save - see [Clerk alternatives](/compare/clerk-alternatives) for how Clerk itself gets evaluated by people leaving other providers. And if the honest answer is that auth, billing and workspaces were always going to be three separate purchases, not one, [Auth0 vs BuildBase](/compare/auth0-vs-buildbase) is the direct head-to-head rather than the roundup. Every figure above was read off each vendor's own pricing page and verified 19 October 2026: auth0.com/pricing, workos.com/pricing, clerk.com/pricing, supertokens.com/pricing and kinde.com/pricing. Identity pricing moves faster than most software pricing - Auth0 put SCIM and a first enterprise connection on its free plan partway through writing this - so check the source page before you commit a budget to any of them. --- ## Clerk alternatives: which complaint each one actually fixes > Clerk's 2026 pricing raised the free tier, added per-organization metering to the B2B add-on and left the UI lock-in alone. Which alternative fixes which complaint, and where BuildBase fits. - Source: https://www.buildbase.app/compare/clerk-alternatives - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-19 - Updated: 2026-10-26 ### In short Clerk raised its 2026 free tier but left the real complaints standing: a B2B bill that grows with every customer org past 100, and UI components wired deep enough into your app that leaving means a rewrite. WorkOS, Supabase, SuperTokens and Kinde each fix one specifically; this covers which and where BuildBase fits. Clerk raised its free tier to 50,000 monthly retained users this year. Every "Clerk alternatives" post written before that update is now arguing against a version of Clerk that does not exist anymore - which means the shortlist most people are reading is answering the wrong complaint. ### The one-paragraph answer If your complaint is what Clerk charges for B2B organizations, look at WorkOS - AuthKit is free to the first million monthly active users, and enterprise features are priced per connection, so you pay for the enterprise customers you have rather than for every customer org you sign up. If your complaint is that Clerk's prebuilt UI components and middleware are wired too deep into your app to leave easily, SuperTokens is the direct answer, because the same code runs self-hosted. If you want auth bundled with the Postgres database you are probably already running, that is Supabase. If you want the most generous free tier with billing and B2B orgs already included, that is Kinde. And if the real gap was never just auth - if it was auth plus billing plus workflows plus RBAC all needing to agree with each other - BuildBase replaces more of the stack at once, though it does not ship the UI kit Clerk is known for, and its SSO is on its Enterprise plan only, through your own WorkOS account. ### What actually changed Most "Clerk alternatives" content still argues from the old pricing shape: a low free-user ceiling that made Clerk feel expensive the moment a product got real traction. That argument does not hold anymore. As of our last check on Clerk's own pricing (verified 26 October 2026, see [the full breakdown](/compare/clerk-vs-buildbase)), the free Hobby plan covers 50,000 monthly retained users, Pro is $25 a month and Business $300 a month, all three carrying the same 50,000 included before overage kicks in at $0.02 per extra user. What changed for B2B is the part that actually drives people to look elsewhere. The enhanced B2B add-on is still $100 a month ($85 billed annually), now covering all of your applications, and Clerk also meters organizations: 100 monthly retained organizations are included per app, and each one after that is $1 a month. A team serving five customer orgs pays the add-on and nothing more; a team serving five hundred pays the add-on plus about $400 a month. Enterprise connections are billed on top of both - one included per app on Pro and Business, $75 a month each for connections 2 to 15, $60 each from 16 to 100, and a conversation past that. And Clerk's UI components and session middleware are genuinely good, which is exactly why they are hard to leave - the sign-in flow, the org switcher, the session handling are all wired into your app in a way a simple SDK swap does not undo. ### Where each alternative fits **WorkOS - the B2B organizations tax.** WorkOS unbundles "enterprise readiness" from the core product. AuthKit is free for the first 1M monthly active users, then $2,500 a month per additional million, and the enterprise pieces are metered as you turn them on: SSO and directory sync are each $125 per connection per month for the first 15, sliding to $100 at 16-30, $80 at 31-50 and $65 at 51-100, with custom pricing past that, and audit log streaming is $125 a month per SIEM connection. The shape is the point. You pay for the enterprise customers you actually have, where Clerk charges for every customer organization past the first 100, enterprise or not. **Supabase - "I already have Postgres."** Supabase treats auth as one feature of a full backend: database, storage, realtime and edge functions on the same plan. The free plan covers 50,000 monthly active users, Pro is $25 a month with 100,000 included and $0.00325 per MAU after that, and Team is $599 with the same allowance. If the appeal of leaving Clerk is consolidating onto infrastructure you already run rather than adding another point vendor, this is the shape that fits, and it is open enough to self-host if that matters later. If Postgres itself is not the settled part yet, the [Supabase alternatives roundup](/compare/supabase-alternatives) is worth reading before you commit to it as the destination. **SuperTokens - the lock-in complaint, directly.** SuperTokens' core is open source. The managed cloud and the self-hosted version run the same code, so choosing the managed option now does not forfeit the option to self-host later if the pricing or the relationship stops working. Managed cloud is free to 5,000 MAUs and $0.02 per MAU beyond that; self-hosting the core carries no MAU ceiling and no licence cost. Read the add-on line before you assume self-hosting is free, though: MFA is $0.01 per MAU and account linking $0.005 per MAU, each with a $100 monthly minimum, which is a real floor at small scale. This is the pick for the reader whose actual objection to Clerk is "I do not want my auth logic living inside someone else's components again." **Kinde - the generous-free-tier pick.** Kinde's free plan includes 10,500 MAUs, B2B organizations and subscription billing, rather than charging a separate add-on for either, which is a direct answer to Clerk's organizations charges. It takes a cut of each transaction if you bill customers through it: 0.7% on Free and Pro, 0.6% on Plus and 0.5% on Scale. Paid plans are Pro at $25, Plus at $75 and Scale at $250, all with the same 10,500 MAUs included. The unbundled-SSO claim holds up on Kinde's own page: enterprise connections are capped at one on Free and Pro, then unlimited at no additional cost from Plus ($75) upward. That is the sharpest single contrast in this post, because on Clerk every connection after the first is billed on its own, from $75 a month. See [Kinde vs BuildBase](/compare/buildbase-vs-kinde) for how it compares to a bundled SDK rather than to Clerk specifically. | Feature | BuildBase | Clerk | | --- | --- | --- | | Scope | 20 modules: auth, billing, workflows, RBAC, one instance | Auth and user management, billing via your own Stripe account | | B2B organizations | Included | $100/mo enhanced B2B add-on, plus $1/mo per organization past 100 per app | | Enterprise SSO / SAML | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | 1 connection included per app on Pro and Business, then from $75/mo each | | Prebuilt UI components | Not a focus - bring your own UI against the SDK | Extensive prebuilt React/Next.js components | | Framework support | Next.js, Vite, React Router / Remix, TanStack Start, Express, NestJS, Fastify, Hono, Astro | Next.js, React, Vue, Nuxt, Expo/React Native, and more | > **Where Clerk wins:** Clerk's prebuilt UI components are the best in this category, and that is not a small thing. The sign-in and sign-up flows, the org switcher, the user profile screen - they drop into a Next.js app in minutes and look finished immediately, which is a real head start every one of the alternatives in this post, BuildBase included, asks you to build more of yourself. If fastest time-to-first-login is what you are optimizing for and you are not yet running into the organizations pricing or the lock-in it creates, Clerk is still a genuinely good choice, and this post is not an argument that everyone should leave. ### How to actually decide Match the alternative to the complaint you actually have, not the one everyone else is writing about. If it is cost at your current B2B shape, price out [WorkOS vs BuildBase](/compare/workos-vs-buildbase) side by side with WorkOS's own connection-based model. If it is "I don't want to be locked into anyone's components again," SuperTokens' open-source core solves that more directly than any hosted vendor can. If the honest answer is that auth was never the only piece you were short - that billing and workspaces and workflow automation were always going to be separate purchases too - [Clerk vs BuildBase](/compare/clerk-vs-buildbase) and [Supabase vs BuildBase](/compare/buildbase-vs-supabase) cover that comparison from two different starting points, Clerk's and Supabase's. Every figure above was read off each vendor's own pricing page and verified 26 October 2026: clerk.com/pricing, workos.com/pricing, supabase.com/pricing, supertokens.com/pricing and kinde.com/pricing. Nothing had moved since the September check; the only correction was to how this post described Clerk's own SSO connection tiers, which step from $75 to $60 at 16 connections and go to a quote past 100. Auth pricing moves faster than most software pricing, and Clerk's own 2026 change is the proof, so check the source page before you commit a budget to any of these. --- ## Outseta vs BuildBase: no-code toolkit or an SDK you own > Outseta bundles no-code signup, billing, CRM and a help desk for Webflow and Squarespace sites. BuildBase is an SDK for auth, billing, workspaces and RBAC inside your own product. Where each one fits. - Source: https://www.buildbase.app/compare/outseta-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-18 - Updated: 2026-10-26 ### In short Outseta bundles signup, billing, a CRM and a help desk into one no-code login for Webflow, Squarespace and Framer sites, with no first-party SDK. BuildBase is an SDK: auth, billing, workspaces, RBAC and workflows as code in your own product, with no bundled CRM. Pick by page builder or codebase. Outseta and BuildBase both promise to replace a pile of vendors with one login. They are not competing for the same reader. Outseta is built for someone assembling a site in Webflow or Squarespace who needs signup, billing and a CRM without writing a line of backend code. BuildBase is built for someone already writing a product who wants auth, billing, workspaces and permissions to be code they own, not forms embedded on top of a page. Confuse the two and you land in one of two bad spots. Either you pay for a no-code layer you will fight to customize, or you write your own auth from scratch when a form embed would have shipped the same afternoon. ### The one-paragraph answer If you are launching on Webflow, Squarespace or Framer and want gated content, subscriptions and a lightweight CRM live today, use Outseta. It is purpose-built for exactly that, and no amount of custom code beats an embed you can drop into a page builder this afternoon. If you are already writing a product in Next.js or another React web framework and want auth, billing, RBAC and workflows as part of your own codebase, not a widget sitting on top of it, that is what BuildBase is for. Neither one is trying to be the other. ### Where each one fits Outseta replaces the stack a no-code founder would otherwise stitch together by hand: a payment page, a members-only content gate, an email tool, and a lightweight CRM to track who signed up and why. It plugs into Webflow directly and hands you embeddable JavaScript forms for everything else, which is the right shape for a team that is not writing backend code at all. BuildBase replaces the stack a developer would otherwise wire together: OAuth and session handling, Stripe subscriptions and [usage metering](/guides/charge-per-api-call-nextjs), multi-tenant workspaces, and role-based permissions, shipped as `@buildbase/sdk` and called from inside your own app. Nothing renders on your page unless you build the component that calls it. That is slower on day one and it is also why AgentCenter and PlugNode, two of our own products, can add a new billing rule or a new role without touching a third-party embed anywhere in the flow. ### Feature comparison | Feature | BuildBase | Outseta | | --- | --- | --- | | Integration model | SDK called from your own codebase | Embeddable JS forms plus a REST API | | No-code page builder support | Not the target use case | Native Webflow integration, works with Squarespace and Framer | | CRM | Not a module - user and audience management only | Built in, tracks contacts and deals | | Help desk / support tickets | Not a module | Built in, live chat and tickets | | Email marketing | Email Campaigns module, drip sequences via Workflow Automation | Built in, part of the same login | | Auth methods | Built in: email/password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, Ethereum and Solana wallets, enterprise SSO (Enterprise plan, through your own WorkOS account) | Email/password and social sign-in via embedded forms | | Multi-tenant workspaces and RBAC | Workspaces is a core module, RBAC an additional one - both built in | Not the product - single-account CRM model | > **Key takeaway:** Outseta and BuildBase overlap on almost nothing except the pitch. On one side, > a no-code site gets a CRM, a help desk and a payment form in one login. On the > other, a real codebase gets auth, billing, workspaces and RBAC it can extend. > Where they overlap - billing and basic sign-in - is a small slice of what > either product actually does. ### Pricing, verified 26 October 2026 BuildBase has four published plans: Free at $0, Launch at $19/mo, Grow at $49/mo and Scale at $99/mo, plus a custom Enterprise tier. Free covers 10,000 monthly active users, has no trial and stops at its allowance. Every paid plan starts with a 7-day trial, and none of them require a card. On the paid plans three quotas bill overage: workflow runs at $0.25, $0.15 or $0.10 per 1,000 on Launch, Grow and Scale, web analytics events at $2 per 100,000, and storage at $0.10 per GB-month beyond the plan allowance. Outseta prices by contact-list size rather than by seat, with unlimited team members on every tier and a transaction fee that falls as you move up. It renamed and rebuilt its tiers since this post first ran, so the shape below is worth re-reading even if you priced it earlier in the year. Start is $47/mo for up to 1,000 contacts at a 2% transaction fee. Scale is $127/mo for 10,000 and Pro $247/mo for 25,000, both at 1%, and Max is $897/mo for 100,000 contacts with no transaction fee at all. Billing yearly brings those to $37, $97, $197 and $697 a month, which the page advertises as around 25% off. The two models are not comparable line by line, and that is the useful part. Outseta bills against how many contacts you hold and, on every tier but the largest, takes a cut of what you charge them. We bill a flat monthly fee against monthly active users, with no transaction fee, so what you charge your customers is not our business. Which is cheaper depends entirely on whether your list is big and your revenue small, or the reverse. Check outseta.com/pricing before you commit either way, because a screenshot of a pricing page is stale the moment a vendor changes it - the tier rename above is exactly that happening. > **Where Outseta wins:** Two things Outseta does that BuildBase flatly does not. > > **A built-in CRM and help desk.** Outseta tracks contacts and deals and handles support tickets and live chat, all behind the same login as billing and content gating. BuildBase has no CRM module and no ticketing module in its 20-module catalog - if you need those, you are adding a separate tool either way. > > **Zero-code deployment on a page builder.** Native Webflow integration plus forms that work on Squarespace and Framer mean a non-developer can have paid membership live on a marketing site in an afternoon. BuildBase assumes you are writing code from the first step; there is no page-builder path at all. ### How to actually decide Ask where your product lives. If it is a Webflow site and the person building it is not writing backend code, Outseta's embed-and-go model wins outright - you would be reinventing a CRM and a payment gate to compete with it, and that is a bad trade. If Outseta itself is the problem rather than the no-code approach, [the wider Outseta alternatives roundup](/compare/outseta-alternatives) covers MemberSpace and Memberstack, both closer no-code peers than BuildBase is. Flip the scenario and the answer flips too. When your product is a real codebase and the reader signing up needs a role, a workspace and a permission set that means something to your application logic, an embedded form cannot express any of it - you are back to writing the glue code yourself the moment you outgrow it. We priced what that glue code costs when you assemble it from point tools instead in [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost) - the same math applies whether the vendor list starts with Outseta or something else. And if workspaces and role-based access are the part you are trying to avoid building by hand, [here is what that looks like wired up in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon). Our numbers live at [/pricing](/pricing). Outseta's live on their own site - check both before you commit, because a bundled tool changes its tiers about as often as we change ours. --- ## Lago vs BuildBase: a billing engine or the whole backend? > Lago is a deep, open-source usage-metering and billing engine. BuildBase bundles billing with auth, RBAC and workspaces. Where each one actually fits. - Source: https://www.buildbase.app/compare/lago-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-17 - Updated: 2026-10-26 ### In short Lago is an open-source billing engine: free to self-host, seven charge models, built for real scale. BuildBase bundles billing with auth, RBAC and workspaces as one instance. If metering depth is the whole problem, Lago wins it. If billing is one of several systems you still have to build, the bundle is cheaper. Every "Lago alternatives" post on the first page compares Lago against [Stripe Billing](/compare/stripe-billing-alternatives), Chargebee, Orb, Metronome, the rest of the metered-billing field. We ran our own pass at that same field, including the two acquisitions most of those lists still haven't caught up to, in [Lago alternatives](/compare/lago-alternatives). None of them ask the question that actually matters to a team wiring billing into a new product: are you buying a billing engine, or trying to avoid building the four systems that sit next to it? Lago answers the first question extremely well. BuildBase is built around the second. ### The one-paragraph answer Lago is a dedicated billing and metering engine, open source, and free to self-host. If usage metering is your hard problem - complex charge models, high-volume event ingestion, invoicing you want full control over - Lago is built for exactly that and does it deeper than a bundled module ever will. If your actual problem is that billing is the fourth or fifth vendor you're about to add next to auth, workspaces and RBAC, BuildBase ships all of it as one instance, and the cost of stitching those pieces together is what you're really paying when you pick point solutions one at a time. ### What each one replaces Lago replaces the billing engine specifically: Stripe's usage-based limits, or a hand-rolled events table and a cron job that reconciles it monthly. Nothing else. You still bring your own auth, your own workspace model, your own RBAC. BuildBase replaces more of the stack around billing, not instead of it. Subscriptions, trials, credits and usage metering sync to Stripe the same way Lago's does, but it sits inside a platform that also ships authentication (from passwords and passkeys to social, phone and wallet sign-in, and enterprise SSO on the Enterprise plan), multi-tenant workspaces, role-based permissions and workflow automation. Twenty modules, one SDK, one instance - a quota belongs to a workspace, a workspace has members, and that relationship is not glue code you write yourself. ### Pricing and openness, verified 26 October 2026 Lago's open-source edition is free, self-hosted, and published under AGPLv3 on GitHub. The paid product is Lago Premium, offered as managed cloud or self-hosted, and priced by talking to sales rather than by a public rate card. | Feature | BuildBase | Lago | | --- | --- | --- | | Self-hosted, free tier | Not free - Docker self-host on a paid plan | Free under AGPLv3 | | Entry paid plan | $19/mo (Launch) | Lago Premium, quote-only | | Trial | 7 days on paid plans, no card required | Not published for Lago Premium | | Charge models | Usage and seats with graduated or volume tiers, add-ons (one-time, lifetime, recurring) and credits, on your own Stripe | Seven models: standard, graduated, package, volume, and more | | Scope | 20 modules, one instance | Billing and metering only | BuildBase has a Free plan now: $0, 10,000 monthly active users, and it stops at its allowance rather than billing. The paid plans start with a seven-day trial with no card needed. Neither is the same offer as Lago's free self-hosted edition, which has no allowance to stop at: you run it, you pay for the servers. ### Where the models actually diverge Lago exists to be the best possible billing engine, full stop, and that focus shows in the charge-model list. Standard, graduated, graduated percentage, package, percentage, volume and dynamic - seven ways to shape a price, as the `charge_model` enum in Lago's own API reference lists them, versus BuildBase's usage-based and seat-based billing riding on top of Stripe's own pricing primitives. If your pricing model is genuinely unusual, Lago gives you more knobs. The same question shows up one comparison over: if entitlements and packaging experiments are the actual hard part rather than raw metering throughput, [Stigg's pricing layer goes deeper on that specific slice](/compare/buildbase-vs-stigg) than either of us. What Lago does not give you is the rest of the product. Metering has to know who the user is, which workspace they belong to, and whether their role even allows the action being metered. That's three systems Lago assumes you already have. We built [the metering module](/guides/charge-per-api-call-nextjs) to answer straight into [workspaces and RBAC](/guides/multi-tenant-workspaces-in-an-afternoon) for exactly this reason. PlugNode, one of our own products, runs its usage-based credit metering on top of BuildBase auth and team workspaces with RBAC already in place - the meter never has to ask a second system who the user is or what they're allowed to do. Bolt a metering engine on after the fact and you're wiring that question yourself, every time, for every product. > **Where Lago wins:** Two things Lago does better, and they're not close. > > **Metering depth and scale.** ClickHouse's March 2026 case study on Lago's > migration to ClickHouse Cloud describes moving from 10,000-20,000 events per > second to a claimed one million. It is a vendor case study, so read the top > number as a ceiling rather than a guarantee - but the shape is real. That is a > purpose-built ingestion pipeline, and a bundled billing module is not going to > out-throughput a system whose entire job is ingesting metering events. > > **A genuinely free tier with the source published.** Lago's self-hosted > edition costs nothing and the code is public under AGPLv3. BuildBase's > self-hosted option runs on your own infrastructure too, but it does not ship > under an open license, and it is not free - you're paying for the platform > either way. ### How to actually decide Ask what breaks first. If it's "our pricing model is too complex for a standard usage-based charge," that's a Lago problem, and you should go build on the tool whose only job is solving it. If it's "we need billing, and also auth, and also workspaces, and also a way to tell who's allowed to see what," that's four separate integrations sitting behind four separate vendor relationships, and the cost of wiring them together is the number nobody puts on a pricing page. We priced one version of that stack in [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost). Our numbers live at [/pricing](/pricing). Lago's self-hosted edition lives on GitHub, and Lago Premium lives behind a sales conversation - check both before you commit, because neither one sits still for long. --- ## Firebase vs BuildBase: primitives or a SaaS backend > Firebase gives you auth, Firestore and hosting free to start. Here is what it does not bundle - billing, RBAC, workspaces - versus BuildBase. - Source: https://www.buildbase.app/compare/firebase-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-15 - Updated: 2026-10-22 ### In short Firebase is Google BaaS: Firestore, Auth, Cloud Functions and Hosting, free to start and strong for mobile and realtime apps. It has no built-in subscription billing, workspace RBAC, or workflow automation. BuildBase bundles those into one SDK, trading Firebase mobile reach for a backend already wired together. Firebase will get an app talking to a database in an afternoon. It will not tell you who owns that data once two people are paying for it. ### The one-paragraph answer If your app is mobile-first, needs offline sync, or you just want a database and auth working before lunch, Firebase is the right tool - its client SDKs cover iOS, Android, Flutter, Unity and the web, and Firestore's realtime listeners are a genuinely hard problem it has already solved. If your app is a SaaS product with paying customers, teams, and roles, Firebase hands you the primitives and leaves the SaaS part to you: no subscription billing, no workspace RBAC, no workflow engine. BuildBase starts one layer up, with those already wired to the same auth and data model. ### What each one actually is Firebase is Google's mobile and web app platform: Firestore for data, Firebase Auth for identity, Cloud Functions for backend logic, Hosting for static assets, plus Crashlytics, Analytics and Remote Config bundled in. It's infrastructure primitives with client SDKs across five platforms - the pitch is "build your backend out of these pieces," and for a huge range of apps that pitch works. BuildBase is narrower in scope and more opinionated about the shape of the result. It bundles user-facing sign-in by email/password, magic link, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO on the Enterprise plan through your own WorkOS account, plus API tokens for server-to-server calls, [workspaces with RBAC](/guides/multi-tenant-workspaces-in-an-afternoon), subscription billing and [credit metering](/guides/charge-per-api-call-nextjs), workflow automation, and transactional email - 20 modules total, running against `@buildbase/sdk` in one instance. A subscription belongs to a workspace, a workspace has members, a member has a role. That relationship is already modeled; in Firebase you write it. Where this actually bites: the day a Firebase app needs "team A pays for team A's usage, and team A's admin can invite team B's contractor with read-only access." Firestore has no concept of a workspace or a plan. You build both in security rules and Cloud Functions, and you keep them in sync by hand every time the product changes. ### Pricing, as far as it can be verified today Firebase is pay-as-you-go past a free tier; BuildBase is flat per plan. That's the shape of the difference, and it matters more than any single rate. Firebase's two tiers are Spark and Blaze. Spark is free, with fixed quotas: 1 GiB of Firestore storage, 50K document reads, 20K writes and 20K deletes per day, 50K monthly active users on Auth, and 10 GB of Hosting storage with 360 MB/day of transfer. Blaze keeps those allowances at no cost and bills only past them, Hosting at $0.026/GB stored and $0.15/GB transferred. There's no seat price. The bill scales with usage. One wrinkle on the Firestore line. Those read and write numbers are the Standard edition row, and Firebase now prints a second row for Enterprise edition that counts the same budget in units rather than documents: 40K write units and 50K read units per day, plus 50K real-time update units. So a Firestore quota you find quoted in an older comparison may not be the row your project is actually on. Check which edition you picked before trusting the number. File storage is the exception, and this post had it wrong in its first version: it listed 5 GB of Cloud Storage among the Spark quotas. That has not been true since September 2024, nearly two years before this post went up, so call it our error rather than a price change. Cloud Storage for Firebase requires Blaze even for a default bucket. A Spark project has no bucket access at all, and Firebase's own documentation is blunt about what that looks like in practice: calls return 402 or 403. So the moment your product stores a user avatar, you are on a billing plan, not on the free tier until you outgrow it. The rate depends on when the bucket was made. Buckets created before September 2024 (`PROJECT_ID.appspot.com`) keep their original no-cost level of 5 GB stored and 1 GB/day downloaded, then bill at $0.026/GB stored and $0.12/GB downloaded. Anything provisioned since (`PROJECT_ID.firebasestorage.app`) follows Google Cloud Storage rates, with 5 GB-months of storage and 100 GB/month of downloads at no cost. Read that second allowance twice before assuming the change was a downgrade: 100 GB a month is far more headroom than 1 GB a day, so a new project on a download-heavy app is better off than a legacy one. The catch is regional. Those no-cost quotas apply only in `us-central1`, `us-west1` and `us-east1`, so a bucket in Europe or Asia pays from the first byte. Firestore's per-operation rates are the one figure Firebase doesn't print on its own pricing page: it defers to Google Cloud pricing, where reads, writes, deletes and storage are priced per region. Check those for the region you'd actually deploy in rather than trusting a number from a blog post, this one included. (Quotas and rates above verified against firebase.google.com/pricing on 1 October 2026, and the Cloud Storage plan requirement against Firebase's own FAQ for the September 2024 storage changes.) Free is $0 (10,000 MAU, 50 workspaces, 1GB storage, 2 team members) with no trial, and it stops at its allowance rather than billing. Launch is $19/mo (25,000 MAU, 1,000 workspaces, 10GB storage, 3 team members), Grow is $49/mo (100,000 MAU, 25,000 workspaces, 50GB, 8 members), Scale is $99/mo (500,000 MAU, 100,000 workspaces, 200GB, 50 members), and the paid plans start with a 7-day trial that doesn't ask for a card. Three lines bill over on the paid plans: workflow runs at $0.25, $0.15 or $0.10 per 1,000 on Launch, Grow and Scale, web analytics events at $2 per 100,000, and storage at $0.10 per GB-month beyond the plan allowance - MAU, emails and webhook deliveries are hard allowances that don't bill over. Current numbers live at [/pricing](/pricing). Worth sitting with before the rest of this post: Spark's 50K free monthly active users is five times what our Free plan includes and twice what Launch includes. If MAU is the number that decides this for you, Firebase wins it outright and nothing below changes that. | Feature | BuildBase | Firebase | | --- | --- | --- | | Free tier | Free: 10,000 MAU; paid plans start with a 7-day trial, no card required | Spark: free - 50K MAU, 50K reads/day, 1 GiB Firestore | | Pricing model | Flat per-plan: a Free plan, paid plans from $19/mo (Launch) | Blaze: pay-as-you-go per operation past Spark quotas | | Subscription billing | Built in, credit metering included | Not provided - wired to your own Stripe account | | Workspace RBAC | Built in, roles and permissions per workspace | Not a feature - modeled in Firestore security rules | | Workflow automation | Built in workflow module | Not provided - built from Cloud Functions triggers | | Mobile / client SDKs | Web-focused: Next.js, Vite, React Router / Remix, TanStack Start, Express, NestJS, Fastify, Hono, Astro | iOS, Android, Flutter, Unity, Web | | Realtime data sync | Not a product feature | Firestore realtime listeners with offline support | > **Where Firebase wins:** Two things Firebase does better, and they're not small. > > **Client SDK and platform reach.** Firebase ships native SDKs for iOS, Android, Flutter and Unity, on top of the web. If you're shipping a mobile app or a game, that reach is not something you replicate by picking a different backend - our SDK is web-focused ([Next.js](/guides/buildbase-on-nextjs), [Vite](/guides/buildbase-on-vite), [React Router / Remix](/guides/buildbase-on-react-router), [TanStack Start](/guides/buildbase-on-tanstack-start), [Express](/guides/buildbase-on-express), [NestJS](/guides/buildbase-on-nestjs), [Fastify](/guides/buildbase-on-fastify), [Hono](/guides/buildbase-on-hono) and [Astro](/guides/buildbase-on-astro)) and we do not cover native mobile. > > **Realtime, offline-first data sync.** Firestore's realtime listeners handle conflict resolution and reconnect-sync automatically - the two parts of offline-first software most teams get wrong on the first attempt. We have no equivalent product. If your app's core feature is live collaborative data or offline-first sync, that's Firebase's problem to solve, not ours. ### How to actually decide If the product is mobile-native, or its core value is realtime or offline data sync, start with Firebase - fighting its strengths to get a SaaS shape out of it costs more than the SaaS features you'd be adding. If the product is a web SaaS app where customers pay for seats or usage, and you already know you'll need workspaces, roles and a workflow engine that reacts to billing events, those pieces cost real engineering time to build correctly on Firestore. BuildBase starts with them already connected. If Firestore itself isn't the deciding factor, [the wider Firebase alternatives roundup](/compare/firebase-alternatives) sorts Supabase, Appwrite and Nhost by what each one actually replaces. [Supabase vs BuildBase](/compare/buildbase-vs-supabase) is the closer comparison if a Postgres-backed BaaS is also on your list, and [the real monthly cost of stitching Clerk, Stripe, Lago and Knock together](/blog/auth-billing-stack-cost) is worth reading if you're pricing out what "just add billing to Firebase" actually costs once you count every piece. We keep our numbers in one place at [/pricing](/pricing). Check Firebase's own pricing page before you commit - usage-based pricing changes with load, not just with a vendor announcement. --- ## WorkOS vs BuildBase: what you still need to buy after SSO > WorkOS handles enterprise SSO and SCIM well, but leaves billing, workspaces and email to other vendors. Here is how BuildBase compares. - Source: https://www.buildbase.app/compare/workos-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-15 - Updated: 2026-10-23 ### In short WorkOS is a developer-focused identity platform built for enterprise SSO, SCIM sync and audit logs. It does not include billing, workspaces or email - teams pair it with Stripe. BuildBase bundles auth, billing, workspaces, RBAC, workflows and email in one SDK, and its own SSO runs on WorkOS, on its Enterprise plan. Most WorkOS comparisons stop at the login screen, because WorkOS is very good at exactly that screen. The question worth asking is what a B2B SaaS team is still assembling around it once SSO works. WorkOS answers one part of a SaaS backend better than almost anyone. It was never trying to answer the rest, and the rest is where a second, third and fourth vendor bill shows up. ### The one-paragraph answer Pick WorkOS on its own if an enterprise buyer is asking for SAML or SCIM this quarter and identity is the only system you are missing. Pick BuildBase if auth is one of several systems you still need - billing, workspaces, roles, quota enforcement - and you would rather run one instance than add WorkOS on top of Stripe on top of your own permissions code and [keep all of it in sync](/blog/auth-billing-stack-cost) by hand. On BuildBase's Enterprise plan the SSO is still WorkOS, connected to your own account, so the enterprise part of the bill is WorkOS's either way. ### What each one actually is WorkOS is a developer-focused identity platform built around one problem: getting a B2B app to enterprise-ready authentication fast. SSO, SCIM directory sync, audit logs, and a self-serve Admin Portal that lets a customer's own IT team configure their SSO connection without WorkOS or your team in the loop. It is narrow by design, and the depth shows in exactly the area it targets. BuildBase is the opposite shape. Twenty modules ship as one instance behind `@buildbase/sdk` - authentication, billing and subscriptions, workspaces, role-based access, workflow automation, email. Its sign-in methods are built in: email and password, magic links, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO, plus API tokens for server-to-server calls. If the full 20-module bundle is more than you want, [Kinde sits in between](/compare/buildbase-vs-kinde) - auth with billing bolted on, short of a whole backend. The eighth is where the two products meet. BuildBase's enterprise SSO (SAML and OIDC) and Directory Sync (SCIM) are on its Enterprise plan only, and they run through your own WorkOS account: BuildBase verifies the customer's domain, sends their IT admin a setup link into WorkOS's Admin Portal, signs their people in through WorkOS, and keeps workspaces and roles in step with their directory. WorkOS bills each connection to you, on top of the BuildBase plan. > **Key takeaway:** WorkOS optimizes for enterprise identity done right. BuildBase optimizes for > not needing five vendors to ship the rest of a SaaS product - and when you > need enterprise SSO on it, that part is WorkOS too. ### Where the two overlap, and where they do not Both handle sign-in for a B2B app. WorkOS's User Management product covers email and social sign-in the same way BuildBase's authentication module does, and both exist as one piece of a larger platform rather than the whole product. The overlap ends there, though less completely than it did in August. WorkOS still has no native subscription billing - the commonly reported pattern is pairing it with Stripe, and WorkOS now ships its own Stripe add-ons to make that pairing less manual. Seat counts and entitlements sync across; plans, invoicing, dunning and tax stay in Stripe. There is no multi-tenant workspace model past "Organizations", no workflow automation for your own application logic, and no transactional or campaign email beyond the auth flow itself. Each of those is a vendor you add, a bill that scales on its own axis, and an integration that has to agree with WorkOS about who the user is. Roles are the claim worth correcting. An earlier edition of this post said WorkOS stopped at organization membership. It does not. AuthKit ships custom roles scoped to an organization, with named permissions you reference in code by slug, assignable through SCIM or directory groups, plus a separate fine-grained authorization product alongside. If RBAC alone were the reason you were reading this, that gap has closed. That is not a flaw in WorkOS. It chose depth on one problem over breadth across many, the same tradeoff [Auth0](/compare/auth0-vs-buildbase) and [Clerk](/compare/clerk-vs-buildbase) make - WorkOS just specializes further, into the enterprise-SSO slice specifically rather than identity broadly. ### Comparing the shape of each product | Feature | BuildBase | WorkOS | | --- | --- | --- | | What you get | Auth, billing, workspaces, RBAC and workflows on one instance | Enterprise SSO, SCIM directory sync, audit logs, Admin Portal | | Enterprise SSO / SAML / SCIM | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | Core product, self-serve Admin Portal for customer IT admins | | Subscription billing | Built in: plans, credits, usage quotas | Not included; Stripe add-ons sync seats and entitlements | | Multi-tenant workspaces | Built in | Basic "Organizations" concept, not a full workspace model | | Permissions / RBAC | Built in, org- and workspace-scoped roles | Custom org-scoped roles and permissions | | Email | Built in: Google, Mailgun, custom SMTP | Not included | | Pricing | Free $0, Launch $19/mo, Grow $49/mo, Scale $99/mo | Free to 1M MAU; SSO/SCIM from $125/connection | ### Pricing Our numbers are published and simple: a Free plan at $0, then Launch at $19 a month, Grow at $49 and Scale at $99, each with more monthly active users, workspaces and storage than the last. The paid plans start with a 7-day trial that does not ask for a card. Full details are at [/pricing](/pricing). WorkOS's User Management product, AuthKit, is free for the first 1M monthly active users, and that includes email and password, social login, passkeys, MFA and magic auth. Worth stating without a hedge: at the scale most products actually run at, the auth line on a WorkOS bill is zero, and we have no answer to that number. Our Free plan stops at 10,000 MAU, and Launch is $19 a month for 25,000. The million is a cliff, not a slope. Cross it and AuthKit is $2,500/mo for each additional 1M MAU, which is worth modelling before you grow into it rather than after. What WorkOS mostly bills for is the enterprise part. SSO and SCIM directory sync are priced per customer connection, and the published bands step down with volume: $125 each for the first 15, $100 from 16 to 30, $80 from 31 to 50, then $65 from 51 to 100. Past a hundred connections it is quoted custom. Audit logs price separately again: $125/mo per SIEM streaming connection, and $99/mo per 1M events retained. There is still no published platform fee, though a custom domain runs $99/mo and the Scale support tier is $1,000/mo. (Every WorkOS figure on this page verified against workos.com/pricing on 6 October 2026.) So the bill tracks how many enterprise logos you land far more than how much your product is used - until the MAU line catches up with you. That is a reasonable trade if enterprise SSO is the thing selling the deal. Fifteen connections at $125 is $1,875 a month, and if those fifteen are enterprise contracts, that is not the line item anyone is arguing about. It is a stranger one if most of your customers never ask for SSO at all, because what you pay for is the connections you hold open, not what your product does. On BuildBase's Enterprise plan, SSO runs through your own WorkOS account, so WorkOS bills those connections to you directly. > **Where WorkOS wins:** **Enterprise SSO and SCIM, done by specialists.** This is WorkOS's entire > reason to exist, and it shows - which is why ours is built on it rather than > beside it. On BuildBase it is an Enterprise-plan feature that needs your own > WorkOS account as well. If a buyer's security team is asking for SSO or SCIM > this quarter and the rest of your stack is already settled, WorkOS on its own > is one vendor where we are two, and it wins that deal outright. > > **A self-serve Admin Portal, included free.** WorkOS gives a customer's own > IT admin a portal to configure their SSO or SCIM connection directly, without > your team or WorkOS's in the loop for routine setup. It ships in every > account at no extra charge, with setup paths written per identity provider - > Okta, Entra ID, ADFS, OneLogin, PingFederate, JumpCloud and a long tail > beyond them. That catalog is the part nobody mentions when they estimate > building this themselves. BuildBase did not rebuild it: its setup link opens > the same WorkOS portal, so the provider coverage is WorkOS's, not ours. ### If you are choosing between them The tell is whether an enterprise security questionnaire is already on your desk. If it is, and SAML or SCIM is a checkbox you cannot skip, WorkOS solves that specific problem either way - on its own, or under BuildBase's Enterprise plan with your own WorkOS account. The real question is whether you also want billing, workspaces and permissions from the same place. If you are earlier than that - building the product, still deciding on [workspaces](/guides/multi-tenant-workspaces-in-an-afternoon) and roles, not yet fielding enterprise security reviews - WorkOS gets you enterprise-ready identity you may not need for another year, and leaves billing, workspaces and permissions as separate problems regardless. [Charging per API call](/guides/charge-per-api-call-nextjs) or [enforcing usage quotas](/guides/enforcing-quotas-in-react) on top of WorkOS means building that layer from scratch either way. If you landed here comparing WorkOS against several options rather than just us, [Clerk alternatives](/compare/clerk-alternatives) covers WorkOS alongside Supabase, SuperTokens and Kinde, each mapped to the specific complaint it answers. --- ## Kinde vs BuildBase: which parts of the stack do you actually replace? > Kinde is auth with billing attached. BuildBase is a backend with auth attached. The difference decides which one fits. - Source: https://www.buildbase.app/compare/buildbase-vs-kinde - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-14 - Updated: 2026-10-19 ### In short Kinde replaces your auth provider and adds billing on top. BuildBase replaces auth, billing, metering, workspaces, RBAC and workflows as one instance. If you need SSO for an enterprise buyer this quarter without a custom plan, pick Kinde. If you are about to wire four vendors together, the bundle wins. Most "X vs Y" auth posts compare login screens. That is not the decision. The decision is how many vendors you are going to own the integration between, and for how long. Kinde and BuildBase both claim to be more than auth. They mean different things by it. ### The one-paragraph answer Kinde is an auth provider that added billing. BuildBase is a backend that includes auth. If your next problem is "an enterprise buyer wants SAML", pick Kinde and move on - ours is on the Enterprise plan only, through a WorkOS account of your own. If your next problem is "I need metering, quotas, workspaces and RBAC and I am about to buy four things", the bundle is the cheaper path, and the rest of this post is about why. ### What each one replaces Kinde replaces [Auth0](/compare/auth0-vs-buildbase) or [Clerk](/compare/clerk-vs-buildbase), and takes some of Stripe's job with its billing features. You keep your database, your background jobs, your notification provider, your metering. BuildBase replaces more of the middle. Authentication (passwords, passkeys, email and phone codes, social and wallet sign-in, and enterprise SSO on the Enterprise plan), workspaces with membership and RBAC, subscriptions and credit metering, workflow automation, email. It ships as `@buildbase/sdk` against one instance, so the pieces already know about each other. A quota belongs to a workspace, a workspace has members, a member has a role, and none of that is glue you write. A bundle is only cheaper if you would have bought the pieces anyway. Need auth and nothing else, and you are paying for surface you will never use. ### Pricing, verified 19 October 2026 Kinde publishes its numbers, which is more than most of this category manages. Free is $0 with 10,500 MAU. The paid ladder runs Pro at $25 a month, Plus at $75, and a Scale plan at $250 that has appeared since we first wrote this. The MAU allowance does not grow as you climb: it is 10,500 on every tier. Past it, Pro charges $0.0175 per extra user and Scale $0.0151. Two lines on that page are newer than this post. Organizations are metered now. A paid plan includes 50 monthly active organizations and Pro charges $0.50 for each one after that, though an organization with a single active user is not counted. Billing through Kinde also costs a cut of every customer transaction: 0.7% on Pro, 0.5% on Scale. Our side comes out of the repo rather than a web page. Free is $0 with 10,000 monthly active users, Launch is $19 a month, Grow $49, Scale $99. The paid plans start with a 7-day trial that does not ask for a card. Current numbers live at [/pricing](/pricing). | Feature | BuildBase | Kinde | | --- | --- | --- | | Free tier | $0, 10,000 MAU | $0, 10,500 MAU | | Entry paid plan | $19/mo (Launch) | $25/mo (Pro) | | Per extra MAU | Not MAU-priced | $0.0175 (Pro) | | Enterprise SSO | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | 1 connection free, unlimited on Plus | | Scope | 20 modules, one instance | Auth plus billing | The detail worth noticing is that users on paid subscriptions are not counted as MAU. Bill your users through Kinde and the MAU meter mostly stops mattering, with the transaction fee taking its place. Good decision. It removes the usual reason auth costs surprise people at scale. ### Where the models diverge Per-active-user pricing is the category default, and BuildBase does not use it. Not for the sake of being different: MAU is a poor proxy for what a metered product costs to run. Take a workflow tool where 50 users each trigger 10,000 runs a month. On MAU pricing that account is free. In compute it is not. That gap is why the metering module exists. If your product charges per run or per API call, the meter has to be the same system that enforces the quota and bills the overage. The shape of that is in [charging per API call in Next.js](/guides/charge-per-api-call-nextjs), and it is one call. Wiring a separate metering vendor to a separate billing vendor to a separate auth vendor is where the weeks go. > **Where Kinde wins:** Where Kinde wins, and none of it is small. > > **Enterprise SSO.** Kinde ships SAML and enterprise connections on its > self-serve plans. Ours is on the Enterprise plan only, and runs through a > WorkOS account you pay per connection. If an enterprise buyer has SSO on their > security review and you want it this month on a self-serve plan, this > comparison is already over and Kinde wins it. One connection is included even > on Free, and Plus makes them unlimited. > > **Maturity and funding.** Kinde is a funded company with a larger team and > more production mileage than we have. If vendor risk is high on your list, > that is a real consideration and you should weigh it honestly. > > **Focus.** Auth is Kinde's product, not one module out of 20. Breadth costs > depth, and on any single module that is a price we pay and they do not. ### How to actually decide Make a list of the systems you expect to need in the next twelve months. Not the ones you want. The ones a customer will make you build. If that list is "auth, and maybe subscriptions", Kinde is the better tool, and price will not settle it: both start free, with Kinde's Pro at $25 against our Launch at $19. If the list runs to workspaces, roles, metered billing, quota enforcement and event-driven workflows, you are choosing between one instance and four vendors, and the integration cost of the four is the number nobody puts on the comparison page. We added up one version of that stack in [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost). And if there is no codebase in that list at all - if the plan is a page builder like Webflow rather than a repo - neither Kinde nor BuildBase is the right comparison; see [Outseta vs BuildBase](/compare/outseta-vs-buildbase) instead. Whichever way that goes, re-check both sets of numbers on the day you commit. Ours are at [/pricing](/pricing). --- ## Stigg vs BuildBase for usage-based billing > Stigg goes deep on entitlements, credits and usage enforcement. BuildBase bundles metering into a whole backend. Which one you need depends on what else is missing. - Source: https://www.buildbase.app/compare/buildbase-vs-stigg - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-14 - Updated: 2026-10-22 ### In short Stigg is a dedicated entitlement, credits and metering layer that sits alongside your existing billing, auth and database. BuildBase includes metering, quotas and subscriptions inside a backend that also does auth, workspaces and RBAC. Stigg goes deeper on entitlements; BuildBase means fewer systems to wire together. Every usage-based billing comparison eventually reaches the same question: is pricing a product in your stack, or a feature of something bigger? Stigg's answer is that it is a product. Ours is that it is a feature. So does a third: [Lago answers it by being nothing but metering](/compare/lago-vs-buildbase), deeper than either of us on that one axis and narrower everywhere else. All three answers are defensible and they suit different teams. ### The one-paragraph answer Pick Stigg if pricing itself is the thing you iterate on: multiple packages, frequent packaging changes, entitlements that need to be modelled precisely, and an existing stack you are happy with. Pick BuildBase if metering is one of several systems you still have to build, and you would rather have quotas that already know what a workspace and a role are. ### What each one is Stigg is a usage and entitlement layer. It holds the model of what each customer, user or AI agent is allowed to do, meters what they actually use, and enforces both through their SDK, with credits and wallets on top. You keep Stripe, your auth and your database exactly as they are. It used to be fair to describe Stigg as entitlements sitting on top of someone else's metering. That is no longer true. They ingest and aggregate usage events themselves now, so the overlap with our metering module is direct rather than adjacent. BuildBase includes metering inside its credits module, one of 20 modules on a single instance. Usage is recorded against a workspace, the quota is checked in the same call, and the subscription that defines the quota lives in the same system as the workspace and its members. The practical difference shows up in the wiring. In Stigg's model, a quota check has to know which customer this request belongs to, which means your auth system and Stigg agree on an identifier and you maintain that agreement. In ours, the workspace is already the unit. ### Pricing, verified 19 October 2026 Stigg bills on two meters. The first is managed entities: any customer, user, agent or team that Stigg makes an enforcement decision for. The second is usage events, the raw metering volume. Build is free with 10,000 managed entities and 5 million usage events a month. Pro is $399 a month billed annually, or $499 month to month, with the same 10,000 entities and 25 million events included and graduated pricing above both. Scale is custom. BYOC, which runs Stigg in your own VPC with no event billing, is custom too, from $40,000 a year. Our side comes out of the repo rather than off a web page. Free is $0, Launch is $19 a month, Grow $49, Scale $99. The paid plans start with a 7-day trial that does not ask for a card. Current figures live at [/pricing](/pricing). | Feature | BuildBase | Stigg | | --- | --- | --- | | Free tier | Free plan: 10,000 MAU, stops at its allowance | Build: 10K entities, 5M events/mo | | Entry paid plan | $19/mo (Launch) | Pro: $399/mo annual, $499 monthly | | Billing unit | A plan, not per event | Managed entities plus usage events | | Self-hosted option | Yes, see /self-hosted | BYOC from $40K/yr | | Scope | Metering inside a backend | Entitlements, credits and metering | The row that matters is the billing unit, not the entry price. Stigg's bill tracks two things you do not fully control: how many entities it enforces for and how many events you send it. Ours is a plan. We meter usage, which is what `bb.usage.record` does, but what you pay for does not move with the events you meter through it. Three of our own quotas bill over on the paid plans: workflow runs (from $0.25 per 1,000), web analytics events ($2 per 100,000) and storage ($0.10 per GB-month). Which of those you want depends on whether your own revenue moves with usage too. ### The integration question Here is the part that decides it for most teams, and it is not about features. A dedicated entitlement layer is one more system that needs to agree with your auth about who the customer is, with your database about what a workspace is, and with Stripe about what was sold. Three agreements you maintain. That is completely fine when pricing is complex enough to deserve its own product, and it is overhead when it is not. Bundled metering removes those agreements by removing the boundary. The cost is that you get our model of entitlements rather than a richer one. > **Where Stigg wins:** **Entitlement depth.** This is Stigg's whole product and it shows. Complex > packaging, add-ons, credit wallets, feature-level entitlements, and a new > tier or feature shipped without a deploy. If pricing is something you change > every month, we do not match that and I would not pretend otherwise. > > **It works with what you have.** Stigg does not ask you to move your auth or > your database. Adopting it is additive. Adopting a bundle is a bigger > decision, and reversing it is harder. > > **Event headroom.** 5 million usage events a month on a free tier is past the > point where most products know whether their pricing model works. Pro includes > 25 million and graduates up to 500 million, and Stigg says usage is never cut > off on either plan. That is more metering capacity than most products will need > in a year. ### When each one is wrong Stigg is the wrong call if entitlements are the only sophisticated thing about your billing and you are still missing workspaces, roles and an auth system. You would be integrating a precise pricing model into a stack that does not exist yet. BuildBase is the wrong call if your stack is already built and working. Ripping out an auth provider that works, just to get bundled metering, is a bad trade. The bundle pays off when you are choosing the pieces. Not when you are replacing them. If you are at the earlier point, the metering side is covered in [charging per API call in Next.js](/guides/charge-per-api-call-nextjs) and the UI side in [enforcing quotas in React](/guides/enforcing-quotas-in-react). And if the real question is whether to skip both of us and build metering from scratch, [the cost of building usage metering yourself](/blog/cost-of-building-usage-metering-yourself) runs the arithmetic on that third option. And if neither entitlement depth nor bundled metering is actually the question - if what you're trying to replace is Stripe's own Billing add-on specifically - the shapes for that are sorted in [Stripe Billing alternatives](/compare/stripe-billing-alternatives). --- ## Supabase vs BuildBase: how much of the backend do you want to own? > Supabase gives you direct access to a real Postgres database and lets you build the rest. BuildBase gives you auth, billing, workspaces and RBAC already wired to a database you never touch directly. - Source: https://www.buildbase.app/compare/buildbase-vs-supabase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-14 - Updated: 2026-10-19 ### In short Supabase is a managed Postgres database with auto-generated APIs and realtime subscriptions - you touch the database directly and build the rest yourself. BuildBase bundles auth, billing, workspaces and RBAC into one backend, and you never query the database directly. Pick based on which one you would rather own. Every backend-as-a-service comparison collapses into a features table, which is the wrong first question. The real one: do you want to touch the database yourself, or not? Supabase's whole pitch is that you do. BuildBase's is that you shouldn't have to. ### The one-paragraph answer Pick Supabase if you want a real Postgres database you can query directly, run extensions on and connect any Postgres client to, and you are willing to build auth flows, billing, workspaces and RBAC around it yourself. Pick BuildBase if you would rather the auth, billing, workspaces and RBAC already existed and agreed with each other, and you are fine not touching the database directly. Both are legitimate answers to "how much of the backend do I want to own." ### What each one actually is Supabase is a managed Postgres instance with auto-generated REST and GraphQL APIs, realtime subscriptions on table changes, and its own auth, file storage and edge functions layered on top. The database is the product. Everything else exists to make that database easier to use from a client app. If mobile reach matters more than SQL access, [Firebase](/compare/firebase-vs-buildbase) is the other primitives-first BaaS worth comparing - Firestore instead of Postgres, with the same gap once billing and workspaces enter the picture. The [full Firebase alternatives lineup](/compare/firebase-alternatives) covers Appwrite and Nhost alongside Supabase, for the same reason. Weighing Supabase against that wider field rather than against BuildBase specifically? The [Supabase alternatives roundup](/compare/supabase-alternatives) lines up Firebase, Appwrite, Nhost and PocketBase by what each one actually replaces. BuildBase is the opposite shape. Twenty modules ship as one instance behind `@buildbase/sdk`: authentication, billing and subscriptions, workspaces, role-based access, workflow automation, email. The database underneath is ours, not yours - you call `bb.workspace.create()`, not `INSERT INTO workspaces`. That is a real constraint. It is also why a quota already knows which workspace it belongs to, instead of you writing the join. > **Key takeaway:** Supabase optimizes for the database being the thing you touch. BuildBase > optimizes for the database being the thing you never think about. ### Where the two overlap, and where they don't Both ship authentication. Supabase Auth gets you email, magic links and social providers on top of your own Postgres row. BuildBase's authentication module covers email and password, magic links, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO on the Enterprise plan - plus API tokens for server-to-server access, and it is one of 20 modules rather than the whole product. Billing, workspaces and workflows are where the overlap stops. Supabase does not ship subscription billing, usage metering, role-based permissions or workflow automation. You add Stripe, an entitlements layer and your own tenancy model on top of the database, the same way you would with any raw Postgres host. That is not a knock on Supabase. It is a scope decision, and it rhymes with what [teams assembling Clerk, Stripe, Lago and Knock end up paying in integration time](/blog/auth-billing-stack-cost) - Supabase just starts one layer lower, at the database itself. ### Comparing the shape of each product | Feature | BuildBase | Supabase | | --- | --- | --- | | What you get | Auth, billing, workspaces, RBAC and workflows on one instance | A managed Postgres database with auto-generated APIs | | Database access | Workspace-scoped, through the SDK | Direct SQL access to your own Postgres instance | | Billing and metering | Built in: subscriptions, credits, usage quotas | Not included, bring your own Stripe integration | | Workspaces and RBAC | Built in, workspace-scoped roles | Not included, model it yourself in your schema | | Realtime | Real-time Slack alerts on events; audience segments update periodically | Realtime subscriptions on raw table changes | | Licensing | Proprietary SaaS, self-hosted deployment available | Self-hostable (see Fairness note below) | | Pricing | Free $0, Launch $19/mo, Grow $49/mo, Scale $99/mo | Free $0, Pro $25/mo, Team $599/mo | ### Pricing, verified 19 October 2026 Supabase publishes its numbers: $0 for Free, $25 a month for Pro, $599 for Team, Enterprise by negotiation. Free gives you 500 MB of database, 50,000 monthly active users and 5 GB of egress, and pauses a project after a week of inactivity. Pro lifts that to 8 GB, 100,000 MAU and 250 GB of egress, then meters what you go over - $0.125 per extra GB of database, $0.00325 per extra MAU, $0.09 per GB of egress. The line that surprises people is compute. Pro includes $10 a month of compute credits, which covers exactly one Micro instance. Anything bigger is an add-on and the ladder is steep: $15 a month for Small, rising to $3,730 for 16XL. Disk performance is its own setting on top: you can provision extra IOPS and throughput separately, though what you actually get is capped by the compute size. That is the honest consequence of the database being the product - its size and its load are your bill, and neither is a number you can read off a plan name. Our own numbers are at [/pricing](/pricing). > **Where Supabase wins:** Three things Supabase does that we genuinely do not, and none of them are > close calls. > > **Direct database access.** You get a real Postgres instance you can run > arbitrary SQL against, install extensions on and connect to with any Postgres > client. BuildBase does not expose a database to query directly - everything > goes through the SDK. If you need that level of control, Supabase is built > for it and we are not. > > **It is open source.** Supabase is open source under Apache 2.0 and can be > self-hosted from the ground up, including the database - its own Docker Compose > stack runs Postgres as a container you connect to directly. We offer a self-hosted deployment > (see /self-hosted) - [priced out against the managed > plans here](/blog/self-host-vs-managed-cost) - but the platform itself is > proprietary. > > **Realtime on raw data.** Supabase streams row-level changes straight from > Postgres to a client. Ours does not work that way. Slack alerts fire on > specific events - a signup, a payment - not a live feed of your database. > Want to watch arbitrary table changes as they happen? That is Supabase's > model, not ours. Past roughly 3,000 concurrent subscribers on the same changes, > Supabase's own docs point you from Postgres Changes to Broadcast, which sends > each change once and fans it out. ### If you are choosing between them Ask what you are actually building, not what you are technically capable of building. Needing members and roles on a workspace is usually the tell that you are building multi-tenant SaaS rather than a single-tenant app with a database, and [wiring that up from raw tables takes longer than it looks](/guides/multi-tenant-workspaces-in-an-afternoon). If that raw-tables path also means a separate database per tenant rather than shared tables, [price out what that isolation actually costs](/blog/database-per-tenant-cost) before you commit to it. If your product is closer to "I need a database with an API and I will build the product logic myself," Supabase's directness is the right trade. You are not fighting an opinionated schema, and the open-source option means you are never fully locked in. If your product is closer to "I need auth, billing, workspaces and permissions that already agree with each other," the SDK boundary that feels like a limitation on day one is the thing that stops you rebuilding the same systems an assembled stack eventually forces you to build anyway. Neither answer is universally right. The question is only which parts of the backend you want to own. --- ## ShipFast vs BuildBase: what $199 once actually buys you > ShipFast is $199 once for a Next.js repo you own and wire up yourself. BuildBase is an SDK where the auth, billing and email are already running. When each one wins. - Source: https://www.buildbase.app/compare/shipfast-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-14 - Updated: 2026-11-02 ### In short ShipFast is a one-time $199 Next.js boilerplate: you get a GitHub repo and wire up Stripe, an email provider, a database and hosting yourself. BuildBase is an SDK where auth, workspaces, billing and email already run as a service. ShipFast wins when you want to own every line. Every ShipFast comparison I can find argues about which boilerplate to buy instead of it. Indie Kit, supastarter, a dozen listicles. None of them ask the question underneath: should you buy a boilerplate at all? That is the actual fork in the road, and it has nothing to do with feature tables. ### The one-paragraph answer Buy ShipFast if the code is the product and you want to own every line of it. $199 once, a repo, no vendor sitting in your auth path forever. Buy BuildBase if auth, billing and email are undifferentiated plumbing you would rather not maintain twice. Price is not the difference. The difference is whether you want the wiring diagram or the wiring. ### What each one actually is ShipFast is a Next.js boilerplate. You pay once, you get access to a GitHub repo in JavaScript or TypeScript, and what you receive is code: Stripe and Lemon Squeezy checkout paths, Mailgun or Resend email, MongoDB or Supabase, Google OAuth and magic links through NextAuth, components, SEO and a blog. ShipFast hosts nothing and runs nothing. Every account behind those integrations is yours to open, configure, pay for and operate. BuildBase is the other shape. 20 modules run as one instance behind `@buildbase/sdk`: hosted sign-in (passwords, passkeys, email and phone codes, social providers, wallets, and enterprise SSO on the Enterprise plan), [workspaces with RBAC](/guides/multi-tenant-workspaces-in-an-afternoon), subscriptions and [credit metering](/guides/charge-per-api-call-nextjs), workflow automation, email. You call `bb.workspace.create()`. There is no repo to fork, and no Stripe account to reconcile with a user table you also own. > **Key takeaway:** A boilerplate gives you the code and leaves you the integrations. An SDK gives > you the integrations and never gives you the code. Both of those are real trades. Neither is free. ### Pricing, verified 2 November 2026 ShipFast is one-time: $199 Starter, $249 All-in, $299 for the bundle that adds the CodeFast course. Lifetime updates, unlimited projects, and no refunds once you have repo access - which is a reasonable policy for something you cannot un-receive, and worth knowing before you click. Two things about that pricing page are worth saying out loud. First, treat $199 as the price rather than a discount. The $100 off is framed as a countdown - "$100 off for the first 8460 customers (15 left)" on 2 November, after reading 8430 (6 left) in September and 8400 (9 left) six weeks before that - which makes the crossed-out $299 anchor price decoration. Three readings over five months, and the counter has gone up rather than down each time. Second, and more usefully: **the Starter and All-in bullet lists are identical.** Same eleven items, word for word, on both. The $50 difference buys nothing the page describes. That is not a gotcha. It is just worth checking before you pay for the upgrade. Our own pricing is a Free plan at $0 and then a subscription - Launch $19 a month, Grow $49, Scale $99, current numbers at [/pricing](/pricing), verified 31 October 2026. Free stops at its allowance (10,000 monthly active users, 1 GB of storage, 2 team members), and the paid plans start with a 7-day trial that does not ask for a card. Their page has a countdown on it, so re-check both before you commit to either. So here is the arithmetic everyone skips. While you fit inside Free, BuildBase costs nothing and ShipFast is still $199. Once you need Launch, at $199 once against $19 a month, BuildBase passes ShipFast in month eleven. Ten months in we are still cheaper, $190 against their $199. A month later we are $209 and they are still $199, and from there the gap only widens in ShipFast's favour, forever. If that were the whole calculation, this post would be short and would recommend ShipFast. ### What the crossover leaves out It leaves out the four accounts. The $199 buys the code paths, not the services they call. You still open Stripe, an email provider, a database and a host, and you pay each of them, and you operate each of them. That is the same assembled stack we [added up at 20,000 users](/blog/auth-billing-stack-cost), except you also wrote the glue by hand instead of buying it. And it leaves out what happens in month nine. "Lifetime updates" is a promise about a git remote. Once you have been editing the repo since February - and you will have been, that is the entire point of owning the code - an upstream framework major does not arrive as an update. It arrives as a merge conflict against a file you rewrote. Every fork-once boilerplate has this property. ShipFast is not worse at it than its competitors; it just cannot be better, because the thing you bought was a snapshot. We build this way ourselves, which is the only reason I have an opinion worth reading here. Six products - OnceBooks, PlugNode, AgentCenter, Imejis, RemoteWait and LinkTracer - run on BuildBase. When the auth module changes, it changes once. If those six were six forks of a boilerplate, it would change six times, and two of them would quietly not get it. | Feature | BuildBase | ShipFast | | --- | --- | --- | | What you buy | A running service you call | A GitHub repo you own | | Price | Free plan, then $19/mo Launch, $49 Grow | $199 once, $249, or $299 with the course | | Integrations | Already wired, one instance | Code paths only, you open every account | | Who runs it | We do, or you self-host | You do, everywhere | | Updates | Shipped to the SDK | Lifetime, via git merge into your fork | | Scope | 20 modules including metering and workflows | Auth, payments, email, blog and UI | | Deployment | Our cloud, or self-hosted Docker | Yours, anywhere you like | > **Where ShipFast wins:** Three things ShipFast does better, and the first one is not close. > > **You own it, completely.** The repo is yours, it deploys anywhere, and nothing we run sits in the path of your login screen. If BuildBase disappeared tomorrow, a ShipFast app would not notice. That is real insurance, and no subscription can sell it to you. > > **It is cheaper for a product that never earns anything but outgrows a free tier.** Most side projects do not reach revenue. If yours stays inside our Free plan, it costs nothing with us. If it needs a paid plan and still never earns, $199 once beats $19 a month by simple arithmetic from month eleven on. Anyone telling you otherwise is selling a subscription. Which, to be clear, I am. > > **It teaches.** The bundle includes CodeFast, twelve hours of course material. We do not ship anything like it, and for a first-time founder it is worth more than the code. ### How to actually decide Ask what you want to be maintaining in eighteen months. If the answer is "my own code, all of it, because the way auth works in my product is a decision I want to keep making" - buy ShipFast. That is a coherent position and the ownership is real, though it's worth knowing [what maintaining that code actually costs in hours](/blog/cost-of-building-auth-yourself) before you commit to owning it forever. If the answer is "the product, and none of the plumbing under it", then the boilerplate's $199 was never the number that mattered. The number that mattered was the four vendor accounts and the merge conflict in month nine, and neither of those is on any pricing page. Ours included. --- ## Auth0 vs BuildBase: when the MAU bill isn't the real cost > Auth0 handles auth. BuildBase bundles auth with billing, workspaces and workflows. Here's when the bundle wins and when it doesn't. - Source: https://www.buildbase.app/compare/auth0-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-13 - Updated: 2026-10-19 ### In short Auth0 is a dedicated identity platform: enterprise SSO, SAML, deep protocol support, priced by monthly active users. BuildBase is a smaller SDK bundling auth with billing, workspaces and workflows, and SSO on Enterprise only. Pick Auth0 for self-serve SSO; pick BuildBase instead of wiring four vendors together. Most Auth0 comparisons argue about the login screen. That is not where the decision actually gets made. The real question is how many vendors you are willing to own the integration between. Auth0 answers one part of a SaaS backend extremely well. It does not answer the rest, and the rest is where the weeks go. ### The one-paragraph answer Pick Auth0 if an enterprise buyer wants SAML this quarter on a self-serve plan, or if identity is the single hardest problem in your product and you want the most mature tool for exactly that job. Pick BuildBase if auth is one of several systems you still need to build - billing, workspaces, roles, quota enforcement - and you would rather run one instance than [stitch four vendors together](/blog/auth-billing-stack-cost) and maintain the seams yourself. ### What each one is Auth0 is a dedicated identity platform. It does one thing, and the depth shows: social login, enterprise federation protocols, passwordless flows, a rules engine for customizing the auth pipeline. Your database, your billing, your workspace model - none of that is Auth0's job. It never tried to be. BuildBase takes the opposite bet. Auth is one of 20 modules on a single instance, sitting next to billing, metering, workspaces and workflow automation. Its sign-in methods are built in: email and password, magic links, email and phone codes, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO, plus API tokens for server-to-server calls. That covers most B2B SaaS sign-in flows. The enterprise identity layer is the exception: SSO is on our Enterprise plan only, through your own WorkOS account - more on that below. If the full 20-module bundle is more than you want, [Kinde sits in between](/compare/buildbase-vs-kinde) - auth with billing bolted on, short of a whole backend. The practical difference isn't feature count. It's what happens when the next requirement lands. Add a billing tier to an Auth0-based stack and you are reaching for Stripe and wiring a webhook that has to agree with Auth0 about who the user is. Add one to a BuildBase-based stack and the subscription already knows what [workspace](/guides/multi-tenant-workspaces-in-an-afternoon) it belongs to, because that relationship exists in the same system. ### Pricing, verified 19 October 2026 The free tier is the genuinely generous part: 25,000 monthly active users at $0, which is more headroom than most products need in their first year. What is worth understanding before you build on that is that the paid ladder does not begin where the free tier ends. Paid plans are quoted from 500 MAU. On the B2C ladder that is $35 a month for Essentials and $240 for Professional. On the B2B ladder - the one most SaaS companies actually need - it is $150 and $800. What a paid plan costs at your real MAU count is a different number, and it is the one to check on their page before you plan around the free tier. Enterprise SSO no longer starts where it used to. Auth0 moved a single enterprise connection onto the free plan, alongside self-service SSO and SCIM, so one SAML connection now costs nothing. Volume is still what you pay for: B2B Essentials includes three, B2B Professional five, and further connections are $100 a month each up to thirty. The B2C ladder is the exception - enterprise connections are not available on B2C Essentials or Professional at any price, so a consumer-shaped product that lands one enterprise buyer is talking to sales. | Feature | BuildBase | Auth0 | | --- | --- | --- | | Pricing model | Per-plan pricing, see /pricing | Tiered by monthly active users (MAU) | | Free tier | $0, up to 10,000 MAU (Free) | $0, up to 25,000 MAU | | Entry paid plan (B2C) | $19/mo (Launch), 7-day trial | $35/mo at 500 MAU (Essentials) | | Entry paid plan (B2B) | $19/mo (Launch), 7-day trial | $150/mo at 500 MAU (Essentials) | | Enterprise SSO / SAML | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | 1 free, 3 from B2B Essentials, +$100/mo each | | Scope | 20 modules: auth, billing, workspaces, RBAC, workflows | Identity and access management only | MAU pricing is a reasonable proxy for a product where users log in and that's mostly it. It's a worse proxy the moment usage and headcount diverge - fifty users who each trigger ten thousand API calls a month cost Auth0 the same as fifty users who log in once and leave. If your product bills by usage, the metering has to live somewhere, and Auth0 was never going to be that place - see [Stigg vs BuildBase](/compare/buildbase-vs-stigg) if metering is the piece you're actually solving for. ### Where Auth0 genuinely wins > **Where Auth0 wins:** **Enterprise SSO and SAML.** Auth0 ships this, and as of September 2026 one > enterprise connection is included even on the free plan, with three from > B2B Essentials at $150 a month. Ours is on the Enterprise plan only, and it > runs through a WorkOS account you hold and pay per connection. If a deal is > blocked on a security questionnaire asking for SAML and you are on Launch, > Grow or Scale, Auth0 wins that deal outright, and there's no way to argue > around it. > > **Depth on identity specifically.** Auth0 has spent years on nothing but > authentication - rules engines, extensive social and enterprise protocol > support, fine-grained session controls. When identity is the hard part of > your product, a tool built for exactly that problem beats a bundle that treats > it as one module among twenty. > > **Maturity.** Auth0 has been running production identity infrastructure for > longer than BuildBase has existed. If vendor risk matters more to you than > integration cost, that track record is real and worth weighing honestly. ### When each one is the wrong call Auth0 is the wrong call if you are early and assembling a stack by hand - auth here, billing there, a workspace model you're writing yourself in between. You'll integrate Auth0 into a backend that doesn't exist yet, and pay for each of the other pieces separately. BuildBase is the wrong call the moment a customer's security review asks for SAML and you are not ready for our Enterprise plan and a WorkOS account, or if identity itself is sophisticated enough to be your product's hard problem. Ripping out a working, mature auth provider to get bundled billing is a bad trade in that case. If you're deciding based on what you'll actually build next, [charging per API call in Next.js](/guides/charge-per-api-call-nextjs) and [enforcing quotas in React](/guides/enforcing-quotas-in-react) cover the metering side that Auth0 doesn't touch at all. --- ## Clerk vs BuildBase: auth is one module, not a backend > Clerk added billing this year, but plans and subscriptions live in Clerk, not Stripe. Here is what Clerk vs BuildBase covers once you count metering, workflows and email. - Source: https://www.buildbase.app/compare/clerk-vs-buildbase - Section: Comparisons - Author: Dharmendra Jagodana - Published: 2026-08-12 - Updated: 2026-10-19 ### In short Clerk is auth and user management with its own billing product that uses Stripe only for payment processing. BuildBase is one SDK bundling auth, billing, email, workflows and RBAC. Clerk wins on enterprise SSO and framework reach. BuildBase wins once you count metering and workflows. Clerk shipped a billing product this year. It is a real one, with its own plans and subscriptions rather than a thin wrapper over Stripe. It still does not make Clerk a backend. ### The one-paragraph answer If your problem is "I need enterprise SSO and the widest framework reach," Clerk is the better tool - it ships SAML connections on its self-serve plans, where ours are on the Enterprise plan only, and it supports Vue and React Native, which we do not. If your problem is "I need auth, billing, workflows and RBAC to work together without gluing four vendors," BuildBase is the simpler path, because those pieces already share one workspace model. ### What each one replaces Clerk replaces your login screen and session management. Organizations, its B2B product, adds role-based membership and domain-verified auto-join on top. Clerk Billing, added this year, turns plans into checkout flows and entitlement checks. One detail worth getting right, because we got it wrong in the first version of this post: Clerk Billing is not a wrapper around Stripe Billing. You connect your own Stripe account, but Clerk uses it for payment processing only. Plans and subscriptions are Clerk objects, and Clerk's own docs are blunt about what follows - "Can I see Subscriptions in my Stripe account? No." Clerk is not the merchant of record either. If your finance team already reads subscription state out of Stripe, that is a migration, not an integration. BuildBase replaces more of the middle. It bundles user-facing sign-in by email/password, magic link, email and phone codes, [passkeys](/guides/passkeys-nextjs), Google, LinkedIn, GitHub, Microsoft, Apple, an OpenID Connect provider of your own, Ethereum and Solana wallets, and enterprise SSO on the Enterprise plan through your own WorkOS account, plus API tokens for server-to-server auth, [workspaces with RBAC](/guides/multi-tenant-workspaces-in-an-afternoon), subscriptions and credit metering, workflow automation, and email - all running against `@buildbase/sdk` in one instance. A quota belongs to a workspace, a workspace has members, a member has a role - none of that is glue you write between vendors. Clerk Billing is real progress for Clerk, worth naming plainly: it removes one integration a Clerk user used to need, and there is more in it than this post gave it credit for in August. Seat-based plans are documented, with seat limits, per-seat pricing and a pool of included seats. So is payment-failure visibility - `subscription.pastDue`, `subscriptionItem.pastDue` and payment-attempt webhooks all exist. What it still does not do is [usage metering](/guides/charge-per-api-call-nextjs) or [quota enforcement](/guides/enforcing-quotas-in-react). Unit pricing is there, but the docs describe it in terms of seats, not consumption, and nothing documents metered usage. Nor is there workflow automation that reacts to a payment failing: Clerk will tell you the charge failed, and what happens next is still yours to build. Those stay separate purchases. A dedicated metering engine like Lago covers that specific gap in more depth than a bundled module does - see [how Lago's metering compares to ours](/compare/lago-vs-buildbase) if that's the piece missing from a Clerk-plus-Stripe stack. ### Pricing, and what we could not check on 16 September 2026 This section used to quote six Clerk prices. They are gone, and that is deliberate. Clerk's pricing page would not load for us when we re-checked on 16 September 2026. We could reach Clerk's documentation but not the page the numbers live on, so we cut the figures rather than move the verification date and hope. A competitor price you cannot check is worth less than no price at all, and there is a specific reason to distrust the old ones: the parts of Clerk's billing we _could_ read have visibly moved since August. Here is the model, from Clerk's own docs on 16 September 2026. Clerk bills per user, in Monthly Retained Users. An MRU is a user who comes back at least one day after signing up, so a signup that never returns does not bill. That free day is a thoughtful piece of design and we would happily copy it. The B2B side is what changed. Clerk now meters organizations separately as Monthly Retained Organizations: an organization with at least two members, one of whom is an MRU. Free plans include up to 50 MROs in development and 100 in production. What this post called the "organizations add-on" is now the B2B Authentication add-on, and it reaches further than a rename suggests - it gates linking enterprise connections to organizations, self-serve SSO, and any seat limit above 20 seats. So a B2B bill on Clerk is a paid plan, Pro or Business, plus that add-on. Two lines, not one. Enterprise connections themselves are free in development and capped at 25 there; in production the docs say the plan covers them and point at the pricing page for the rest. Read [Clerk's pricing page](https://clerk.com/pricing) for the numbers, and treat any Clerk price you find quoted elsewhere, including in this post's history, as needing a fresh look. BuildBase's model is flat per-plan - a Free plan with 10,000 monthly active users, then Launch at $19 a month, Grow at $49 - and the paid plans' 7-day trial does not ask for a card. Current numbers live at [/pricing](/pricing). For what the wider stack costs once Clerk's own billing is not enough by itself, see [the real monthly cost of Clerk plus Stripe plus Lago plus Knock](/blog/auth-billing-stack-cost). One more thing the docs are clear about, and it is easy to miss when you are comparing headline rates. Clerk Billing is USD only, does not support refunds, and does not support payment methods that need a 3D Secure challenge, which means those payments simply fail. It is unavailable in Brazil, India, Malaysia, Mexico, Singapore and Thailand. And there is no native mobile checkout: web and Expo web only, with no Apple In-App Purchase or Google Play Billing. If you sell into any of that, the price was never the deciding factor. | Feature | BuildBase | Clerk | | --- | --- | --- | | Free tier | Free plan, 10,000 MAU | Free plan, allowance on their pricing page | | Entry paid plan | $19/mo (Launch) | Pro, then Business (prices not verified) | | Billing unit | Flat per plan | Monthly retained users, plus organizations | | B2B organizations | Included | B2B Authentication add-on, metered as MROs | | Enterprise SSO / SAML | Not offered on Launch, Grow or Scale; Enterprise plan, via your own WorkOS account | SAML and OIDC, production requires a paid plan | | Framework support | Next.js, Vite, React Router / Remix, TanStack Start, Express, NestJS, Fastify, Hono, Astro | Next.js, React, Vue, Nuxt, Expo/React Native, and more | | Scope | 20 modules, one instance | Auth plus its own billing objects | > **Where Clerk wins:** Two things Clerk does better today, and they are not small. > > **Enterprise SSO on a self-serve plan.** Clerk ships SAML against Azure AD, Google Workspace, Okta Workforce or any custom SAML provider, plus OIDC including EASIE, from its Pro plan. Ours is on the Enterprise plan only and runs through a WorkOS account you pay per connection. If an enterprise buyer has SSO on their security review and you want it without a custom plan, this comparison is already over and Clerk wins it. > > Clerk also ships self-serve SSO, which this post did not mention in August: your customer's own IT admin claims a domain with a DNS record, picks an identity provider and tests the connection themselves, from a Security tab inside the organization profile. That removes the part of an enterprise deal where someone on your side hand-configures a connection per customer. Ours does the same job in two products: we verify the company's domain with a DNS record, and its IT admin sets up the connection in WorkOS's Admin Portal from a link we send. It works, but Clerk keeps the whole thing in one profile screen. > > **Framework reach.** Clerk supports Vue and Expo/React Native alongside the usual web frameworks. Our list is [Next.js](/guides/buildbase-on-nextjs), [Vite](/guides/buildbase-on-vite), [React Router / Remix](/guides/buildbase-on-react-router), [TanStack Start](/guides/buildbase-on-tanstack-start), [Express](/guides/buildbase-on-express), [NestJS](/guides/buildbase-on-nestjs), [Fastify](/guides/buildbase-on-fastify), [Hono](/guides/buildbase-on-hono) and [Astro](/guides/buildbase-on-astro) - narrower by design. If your frontend is Vue, or your app ships as a mobile client, Clerk covers ground we do not. ### How to actually decide Write down what your next twelve months actually require, not what would be nice to have. If the list is "auth, and maybe an enterprise SSO deal," Clerk is the right tool, and its dedicated focus on auth shows in the product. If the list runs to workspaces, metered billing, workflow automation and RBAC that all need to agree with each other, you are choosing between one instance and the several vendors Clerk still leaves you to wire together. [Kinde vs BuildBase](/compare/buildbase-vs-kinde) is the same shape of decision if Kinde is also on your shortlist, and if a one-time boilerplate is on it instead, [the accounts you still operate after paying once](/compare/shipfast-vs-buildbase) is the other axis of the same question. If you are not writing a codebase at all - if the product is a Webflow or Squarespace site - the comparison that actually applies is [Outseta vs BuildBase](/compare/outseta-vs-buildbase), not this one. And if Clerk itself isn't the fixed point - if WorkOS, Supabase or SuperTokens are also on the list - [Clerk alternatives](/compare/clerk-alternatives) breaks down which complaint each one actually answers. We keep our numbers in one place at [/pricing](/pricing). Check Clerk's own pricing page before you commit, and do it yourself rather than trusting a number in a comparison post, including this one. Theirs moved this year with the shift to retained-user billing, it has moved again since August, and on the day we went looking we could not load it at all. --- ## How to add enterprise SSO to your SaaS through your own WorkOS account > Enterprise SSO and SCIM for a B2B SaaS, in order: your WorkOS keys, the IT admin setup link, verified domains, required SSO, workspace bindings and the in-app screen. - Source: https://www.buildbase.app/guides/add-enterprise-sso-saas-workos - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-11-03 ### In short Enterprise SSO in BuildBase runs through your own WorkOS account: paste its keys once, add each customer company and send its IT admin a setup link. Verified domains route people to their company sign-in, a first sign-in lands them in the workspaces you chose, and Directory Sync blocks leavers. Enterprise plan only. The SAML handshake is the easy part of enterprise SSO. WorkOS does it, and does it well. What eats the week is everything around the handshake: which company a person belongs to, which workspace a new hire lands in, who on the customer's side owns the connection, and what happens on the day their IT team removes someone. That is the part this guide is about. BuildBase does not put its own identity layer in front of WorkOS. It runs on **your own WorkOS account**: you hold the keys, WorkOS bills the connections to you, and BuildBase runs the sign-in, the company records, the workspaces and the screens around it. If all you need is the handshake, WorkOS on its own covers it, and our [WorkOS comparison](/compare/workos-vs-buildbase) says so plainly. If you would rather not hold a WorkOS account at all, [Frontegg](/compare/frontegg-vs-buildbase) includes SSO connections on its free plan and carries the vendor relationship for you. When it works, a customer's employee opens your login page, presses **Continue with SSO**, types their work email and signs in at Okta, Microsoft Entra, Google Workspace or any SAML or OIDC identity provider. They come back signed in, inside the workspaces you chose for their company, with the role you set. > **Before you start:** A WorkOS account (its staging environment to test, production to go live), a > BuildBase organization on the Enterprise plan, an auth client with a login > page, and an owner or admin role in the BuildBase console. Enterprise SSO and > Directory Sync are not on Launch, Grow or Scale. The in-app screen in step 9 > arrives in the next `@buildbase/sdk` release; 0.0.90 does not have it. ### 1. Connect your WorkOS account In WorkOS, open the environment's **API Keys** page, copy the client ID (`client_...`) and create an API key (`sk_...`). In the BuildBase console, open **Authentication**, then **Enterprise**, paste both and choose **Save and validate**. BuildBase asks WorkOS whether the key works before it stores anything. The tab then shows your **redirect URI**. Add it to the WorkOS application's **Redirects** and make it the default. Leave AuthKit off in that environment: BuildBase uses WorkOS for single sign-on only and runs the sign-in itself. **What you should see:** the key shown only by its first and last characters, and **Check the key** answering that it works. One trap costs people an afternoon here. The client ID and the key must come from the same WorkOS environment. A staging key with a production client ID passes every check until the first real sign-in, which then fails, because saving the key checks the key alone. ### 2. Add the customer company Each company you sell to is an **enterprise**. **Add enterprise** creates a WorkOS organization for it in your WorkOS account. Two settings come with it: - **Create accounts on first sign-in**, on by default. An employee signing in through their company for the first time gets an account even when your public sign-up is closed, because their identity provider vouched for them. - **Role for new accounts**, any of your user roles except owner. **What you should see:** the enterprise, not yet connected. ### 3. Add the company's email domain In the enterprise's **Email domains**, add the company's domain, say `example.com`. It shows as **Pending** until the company's IT admin publishes the DNS record WorkOS asks for, in WorkOS's Admin Portal. WorkOS decides; BuildBase reads nobody's DNS. The domain is more than routing. It is the check on every sign-in: the email the identity provider asserts must be on one of the enterprise's verified domains, or the sign-in is refused. Consumer domains such as `gmail.com` are refused outright, and a domain one of your enterprises already holds is never handed to another. **What you should see:** the domain move to **Verified**. With your WorkOS webhook registered from the console that takes seconds. Without it, up to 6 hours: the next time your server reads WorkOS's events. **Refresh from WorkOS** asks now. ### 4. Send the IT admin their setup link The customer's IT admin connects their identity provider in the WorkOS setup portal. They never need a BuildBase account. From the enterprise, either: - **Invite the IT admin by email.** WorkOS emails them the link. Tick **Domain verification** and the same email covers step 3 as well. - **Open the setup portal now**, for when you do it together on a call. The link lasts 5 minutes. Anyone holding it can change the connection, so never forward it to the customer by chat or email. Send them the [page for IT admins](https://docs.buildbase.app/authentication/enterprise-sso-it-admin) with the invitation. **What you should see:** the enterprise's **Connection** section turn active. ### 5. Turn it on Under **Authentication**, **Methods**, add an **Enterprise SSO** method and attach it to the auth client whose login page should offer it. Then turn **Sign-in** on in the **Enterprise** tab. **What you should see:** **Continue with SSO** under the client's other methods. Pressed, it asks for a work email. It never says up front whether a domain has SSO: someone whose company is not set up is told so after they continue, so the button cannot be used to list your customers. ### 6. Choose where their people land In the enterprise's **Workspaces** section, pick the workspaces its people join, the role each one joins with, and **Save workspaces**. Someone joins on their first sign-in through the company, whether the account is new or an existing one linking up for the first time. After that it is a normal membership with a memory: a person a workspace admin removes is not put back on their next sign-in. A workspace belongs to one enterprise, and your plan's member ceiling and the workspace's seats still apply. A join one of them refuses is skipped, the person still signs in, and the enterprise shows **Needs a look** with the reason. **What you should see:** a test employee signing in and landing in the bound workspace with the role you set, not on an empty "no workspaces" screen. ### 7. Require single sign-on, if the company wants it Once the connection is active, the enterprise offers **Require single sign-on**. With it on, the company's people are refused at every other way in (password, magic link, email code, passkey, social sign-in and the rest) with a sentence pointing them at **Continue with SSO**. An app with its own password form gets `reason: "sso_required"` back from the sign-in call. Two details we cared about. A wrong password still answers "Invalid email or password", so the rule is never revealed to someone who does not hold the credential. And it only holds while single sign-on can work: turning the enterprise off, or enterprise sign-in off, lets everyone back in at once. That is your break-glass. Sessions already open are left alone either way. Order matters here. Turned on before the connection from step 4 is active, it locks the company's people out completely. ### 8. Let the directory manage people (Directory Sync) Single sign-on makes an account on first sign-in. It does nothing when someone leaves. For that, turn on **Provision people from the directory** on the enterprise and hand the directory step to the IT admin with **Set up provisioning**. The portal gives them a SCIM endpoint and a bearer token to paste into Okta, Microsoft Entra, Google Workspace or an HR system. **What you should see:** the directory shown as **Linked**, with its last sync. From then on, a person the directory adds gets an account and joins the bound workspaces. A person it removes is **blocked, not deleted**: signed out everywhere and taken out of the workspaces the enterprise put them in, with their history kept. Directory groups can map to roles in the app or in a workspace, and the highest role any group gives wins. Nobody gets an email about any of it, because a company provisioning a thousand people would otherwise send a thousand "you were added" emails. WorkOS bills Directory Sync to your WorkOS account separately from single sign-on. The [provisioning docs](https://docs.buildbase.app/authentication/enterprise-provisioning) cover the group mappings in full. ### 9. Put the Single sign-on screen in your app Your customer's workspace admins should not have to email you to find out whether their connection works. From the next `@buildbase/sdk` release, the workspace settings dialog grows a **Single sign-on** screen while enterprise sign-in is on: the company's name, the connection's state and when it was checked, a Directory sync card, a warning before a SAML certificate expires, and **Set up SSO**, which opens the IT admin's setup for members who can edit the workspace's settings. It shows on its own inside the settings dialog. To put it on a page of your own: ```tsx import { EnterpriseAccess } from '@buildbase/sdk/react'; export function SsoPage() { // The current workspace; pass workspaceId="..." for another one. return ; } ``` Or build your own around the headless hook: ```tsx import { useEnterprise } from '@buildbase/sdk/react'; export function SsoStatus({ workspaceId }: { workspaceId: string }) { const { status, loading, opening, openSetup } = useEnterprise(workspaceId); if (loading || !status) return null; if (!status.available) return

This workspace has no company sign-in.

; return (

{status.enterprise.name}: {status.sso.connectionState}

); } ``` `openSetup()` has to run from a click. The server may first ask the admin to confirm it is them, so the link is fetched before any tab opens. From your backend, the same two calls exist on the server client: ```ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); const status = await bb.enterprise.status(workspaceId); // { available: false } or the company const { url } = await bb.enterprise.createSetupLink(workspaceId); // `url` is a credential: redirect the browser to it, never log or store it. ``` We have not run these three samples against a live tenant for this post; they match the exports and the README of the SDK release they arrive in. ### What breaks, and how to tell A refused sign-in sends the person back to your login page with a `reason`. The ones you will meet first: | `reason` | What happened | What to do | | -------------------- | ------------------------------------------------------ | ------------------------------------------------------------- | | `sso_not_available` | No active enterprise has a verified domain for it | Get the domain verified, or check they typed their work email | | `sso_email_mismatch` | The identity provider sent an email off the domains | Verify that domain too, or fix the email at the IdP | | `sso_required` | They used another way in and their company forbids it | Nothing, unless requiring SSO was a mistake | | `signup_disabled` | First-sign-in accounts are off and nobody invited them | Turn it on, or invite them | **"Use SSO" with no SSO button.** The auth client they signed in through has no Enterprise SSO method attached. Attach it to every client the company's people use. **"The setup never came back."** Do not count on the WorkOS portal returning the IT admin to your app. When we tested on WorkOS's staging environment on 14 October 2026, it stayed on "Connection activated" once the connection worked and never followed the return URL. The SDK screen covers it by reading the status again whenever the admin returns to the tab, for 30 minutes after opening the setup. **Everyone at one company locked out on the same day.** A SAML connection trusts one signing certificate, and those expire. BuildBase reads WorkOS's expiry warnings, badges the enterprise in your console, and shows the company's admins **Renew the certificate** in your app, so their IT admin can fix it before the date rather than after. **Your plan changes.** If your BuildBase plan stops including enterprise SSO, nothing that works stops: people keep signing in and directories keep syncing. New setup is locked, and the API answers `402` with `FEATURE_NOT_IN_PLAN`. The full reference, including several identity providers per company, the access policy and the company's audit trail, is in the [enterprise SSO docs](https://docs.buildbase.app/authentication/enterprise-sso). The short setup checklist is [Set up Enterprise SSO](https://docs.buildbase.app/sign-in-setup/enterprise-sso). ```bash npm i @buildbase/sdk ``` --- ## Credits and usage limits for an AI app you built with a prompt > An AI feature needs a balance someone can spend down and a hard stop when it is gone. What the agent builds instead is a number in a column. Here is the shape that holds, and the prompts that get it. - Source: https://www.buildbase.app/guides/credits-and-usage-limits-for-an-ai-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-29 ### In short Credits for an AI app you built with a prompt are a balance the server spends after the work succeeds, never a column the browser decrements: check, work, then consume with an idempotency key, answer 402 when the balance is empty, show the platform's balance and store, and let a workflow send the low-balance email. You are giving the AI feature in your app a balance: a number of credits each workspace can spend, a way to buy more, a warning before it runs out, a hard stop when it has, and a limit on the free plan that resets every month. When it works, a person uses their free allowance, sees exactly how much is left, buys a pack on a test card and watches the balance rise without a reload, gets refused with a clear message at zero, and gets an email before that happens. None of it lives in a column the browser can write. That last sentence is the whole post. Ask a coding agent for credits and it builds a `credits` integer on the users table, decrements it from the page that calls the model, and adds a route "for testing" that sets it. In February 2026 someone audited three products posted on Reddit and found one with "development endpoints still in production that let anyone mark themselves as a paid user and give themselves unlimited credits". That is not an unusual app. It is the default output of the prompt "add credits". What we ran on 27 October 2026: nothing new. The consume path in this guide is the one in [charge per credit in Next.js](/guides/charge-per-credit-nextjs) and [the credits wallet](/guides/credits-wallet-nextjs), which were written against our platform and whose figures (the 30-a-minute limit, the seven-day expiry window) come from the platform's own routes. The builder-specific parts are the prompts, and the honest note is that none of them has been run inside a builder today. > **Before you start:** An app with BuildBase sign-in and a workspace per customer, on any of the > builders (the Lovable, v0, Bolt and Replit guides each end at that point). A > Stripe account connected in the console, for the packs. A feature that costs > something to run: a model call, an export, a render. ### 1. Decide what you are selling: a balance, a limit, or both Two mechanisms look alike from the pricing page and behave differently underneath, and the agent will build whichever one you name, so name the right one. **A limit (a quota)** is an allowance that comes with the plan and resets every period. Twenty generations a month on the free plan, five hundred on Pro. It is counted, not bought; when it is used up the answer is "upgrade" or "wait until the first"; and nothing carries over. **A balance (credits)** is something people buy and spend down. A pack of 500 for $10, a monthly grant of 100 with the plan, a top-up when it runs low. It carries over, it can expire, it can be given away in a promotion, and when it is gone the answer is "buy more". The balance is also a liability on your side until it is spent, which is why it is a ledger and not a number. Most AI apps want both: a quota on the free plan so strangers can try the feature, credits for everyone who pays so heavy users pay for what they use. The longer argument, with the cases where each is the wrong choice, is [quotas are not credits](/blog/quotas-are-not-credits). For this guide the decision is a sentence you say out loud: "free users get N a month; paid users spend credits". What you should see: that sentence, with the numbers filled in, before you prompt anything. ### 2. Put the price list in the console, not in code Packs, prices, grants and expiry are configuration, and they live in the BuildBase console so a price change is a form, not a deploy. - **Packs.** Each one has a name, a number of credits, a price, and an optional `validityDays`. A pack with no validity never lapses. - **Plan grants.** A plan can grant credits each period. In one configuration only (`renewOnPeriod` on, in reset mode) the unspent part expires at the next monthly reset; leave it off and granted credits carry over. - **Quotas.** On the free plan, the monthly limit for the feature, as a plan limit the server checks. Nothing about prices goes in the app. The agent will try to put them there, because the pricing page has to show them, and the answer is that the page reads the packs from the platform. What you should see: the packs listed in the console with their prices, the free plan carrying the monthly limit, and a test purchase in Stripe's test mode adding credits to a workspace before any code is written. ### 3. The server route: check, do the work, then consume This is the step that decides whether the balance means anything. The order inside the route is check, work, debit, and the debit is the gate. ```ts // app/api/generate/route.ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); const COST = 10; export async function POST(request: Request) { const { workspaceId, prompt, requestId } = await request.json(); // Advisory. Cheap, and it stops you doing work nobody can pay for. const balance = await bb.credits.getBalance(workspaceId); if ((balance?.available ?? 0) < COST) { return Response.json( { error: 'Insufficient credits', available: balance?.available ?? 0 }, { status: 402 } ); } const output = await generate(prompt); // Authoritative. The balance moves here, after the work succeeded. try { const debit = await bb.credits.consume(workspaceId, { amount: COST, description: 'AI generation', idempotencyKey: requestId, }); return Response.json({ output, remaining: debit.balanceAfter }); } catch (err) { if (err.code === 'INSUFFICIENT_CREDITS') { return Response.json({ error: 'Insufficient credits' }, { status: 402 }); } throw err; } } ``` Three things in it that the agent's version never has. The check is advisory and the consume is the decision: on the server the debit lands as one conditional update that requires the balance to still cover the amount, so two requests racing for the last credit cannot both win, and there is no window to close. The consume comes after the work, because no call reverses a consumed credit, so a debit before work that fails is a refund ticket. And the idempotency key makes a retry safe: the same key returns without touching the balance, so a user who clicks twice, or a network that resends, is charged once. Paste this prompt, with your builder's words for "server route": ```text The AI feature is paid for in credits held by BuildBase, not by this app. In the server route that runs it: read the balance with the server SDK's credits.getBalance and answer 402 if it cannot cover the cost; run the work; then call credits.consume with the amount, a description and an idempotency key taken from the request. Never consume before the work. Never store a credit balance, a credits column or a plan in our database. Do not add any route that sets a balance, grants credits or marks a user as paid, including for testing. The browser never calls the credits API directly. ``` What you should see: call the route once and the balance drops by ten. Make the model call throw and the balance does not move, because the line that moves it never runs. Send the same request id twice and it is charged once. **Correcting potential issues.** The ways the agent drifts, and the line to paste back: - It added a `credits` column and decrements it. Paste: "Remove the credits column and every read or write of it. The balance is read from credits.getBalance and spent with credits.consume, on the server only." - It consumes before the work "to prevent abuse". Paste: "Move the consume call after the work succeeds. The getBalance check before the work is the abuse prevention; the debit is after." - It left out the idempotency key, or generated it on the server. Paste: "The idempotency key comes from the client with the request, one per user action, so a retry of the same action carries the same key." - It calls the credits API from the browser with a key. Paste: "No credits call runs in the browser. The browser calls our route; the route calls the platform." ### 4. The browser: the balance, the warning and the buy button The screens are the platform's, and the agent's job is to place them. Three pieces: - `useCreditBalance(workspaceId)` returns the balance with its fields (`available`, `totalGranted`, `totalConsumed`, `totalExpired`, and the expiring part), so the number on the screen is the ledger's number. - `WhenCreditsLow` with a required `threshold` renders its children once the balance is at or below the number you give it, and `WhenCreditsExhausted` renders at zero. There is no default threshold because there is no sensible default for a number you price yourself. - `openCreditStore()` from `useSaaSAuth()` opens the purchase screen from anywhere, which is what the out-of-credits message should do, and `CreditStorePage` is the same store as a page of your own. ```text Show the workspace's credit balance in the app header with useCreditBalance from @buildbase/sdk/react. Inside the AI feature, wrap the warning in WhenCreditsLow with threshold set to the cost of one run, and wrap the out-of-credits message in WhenCreditsExhausted; both offer a button that calls openCreditStore(). Add a /credits page that renders CreditStorePage. When our route answers 402, open the store; when it answers 429, show "try again in a minute" and nothing else. ``` What you should see: the balance in the header, a yellow warning when it is at or below one run's cost, the store opening on a click, a purchase on a test card, and the header updating without a reload. Then the expiry case: `useExpiringCredits(workspaceId, 7)` lists what lapses in the next seven days (seven is the default window, 90 the ceiling), and a line on the billing screen that says "40 credits expire on Friday" is the difference between a top-up and a support ticket. **Correcting potential issues.** If the agent built its own balance screen reading its own column, step 3's first fix-up. If the "buy" button opens a Stripe link the agent pasted, paste: "The buy button calls openCreditStore(); the platform handles checkout and credits the balance. Remove the Stripe link." ### 5. The hard stop, and the email before it Two answers come out of the route in step 3, and they need two different screens. **402 means buy.** The balance cannot cover the run. The response carries how many are available and how many were requested, so the message can say the exact shortfall, and the button opens the store. **429 means wait.** The consume endpoint is rate limited to 30 requests a minute per IP, and that limiter answers with a 429 of its own. A 429 from this route is never an empty balance. Generated apps show the buy screen on any error, and a person who just bought a pack and then sees "buy more" because they clicked fast is a refund request. The email is a workflow, not code. The platform raises a `credit.low_balance` event on its own, and a workflow triggered on it sends the "running low" email from your sender, with a link to the store; a second workflow on the quota's `quota.limit_exceeded` event tells a free user they have hit the month's limit and what Pro would give them. Both are built in the console's workflow editor with a template, and each run is logged, so "did Acme get the warning" is a search. [Emails that arrive](/guides/emails-that-arrive-for-an-ai-built-app) is the guide to the sender and the workflows. What you should see: spend a workspace down past the point where the platform fires the low-balance event and the email arrives from your domain; spend it to zero and the feature refuses with the store; call the route thirty-one times in a minute and the thirty-first answers 429 with no store in sight. ### 6. The free plan's limit, which is a different thing The free tier's monthly allowance is a quota, and it is enforced on the server by the plan, not by a counter in your database. The route records one unit of usage against the workspace before the work, the platform answers whether the workspace is within its plan's limit, and an exceeded limit comes back as a refusal your route turns into a 429 with a message about upgrading. The reset is the plan's, monthly, with no cron job of yours. In the browser, `WhenQuotaExhausted` and its siblings render on the quota's state (within, near the threshold, exhausted) rather than on numbers the page computes, which is the point of [enforcing quotas in React](/guides/enforcing-quotas-in-react): the page never decides whether someone is over, it only shows what the server decided. The server side, with the batching that matters once the feature is popular, is [quota enforcement in Next.js](/guides/quota-enforcement-server-side-nextjs). ```text Free-plan workspaces get a monthly limit on the AI feature, enforced by the BuildBase plan limit, not by a counter in our database. In the server route, record usage against the workspace before running the work and answer 429 with an upgrade message when the platform says the limit is exceeded. In the browser, wrap the feature in WhenQuotaExhausted with an upgrade prompt. Do not add a usage table, a monthly reset job or a counter column. ``` What you should see: a free workspace runs the feature N times, the next call answers 429 with the upgrade message, the page shows the upgrade prompt without a reload, and on the first of the month it works again with nothing of yours having run. ### 7. What the agent builds instead, and why it fails quietly It is worth knowing the shape, because you will be reading diffs for it. The balance is an integer on the users table. The page that calls the model reads it, calls the model, subtracts, and writes it back, so a slow network means two calls and one debit, and a fast one means the opposite. A `/api/dev/add-credits` route exists because testing needed it, and nothing removed it. There is no idempotency key, so every retry is a double charge, and no ledger, so when a customer says "I had 50 and now I have 12" there is nothing to show them. The free plan's limit is a `generations_this_month` column that a cron job the agent also wrote resets, or does not, on the first. Each of those is a support ticket with a date on it, and the audit above is what it looks like when a stranger finds the dev route before you do. Enrichlead, the vibe-coded product that shut down within about a week of launch in March 2025, failed in the same family: its founder described "maxed out usage on API keys" and "people bypassing the subscription", which is what no limit and no gate cost when the feature behind them is metered by someone else's bill. The reason to care about the shape, rather than any vendor, is the API bill underneath. Every credit you fail to charge is a model call you paid for. A balance the browser can set is a balance a stranger can set to a million, and the model provider bills you for every one of them. One more thing about the builder's own credits, which are a different balance from the one you sell. A Base44 reviewer wrote on 15 October 2026 that "a runaway automated workflow in one of my apps consumed almost all 10,000 monthly integration credits". That is your building budget, not your customers' balance, and it argues for the same habit in both places: a limit the thing cannot cross, set by someone other than the thing spending it. ### Where a plain limit, or the builder's own metering, wins If your feature is cheap to run and you sell seats rather than usage, you do not want credits. A monthly quota on each plan is simpler to explain. It carries no liability on your books, it never expires on a customer who then writes in, and the plan enforces it. Credits earn their complexity when people buy them, when usage varies by ten times between customers, or when you want a balance that can be granted in a promotion. And if you bill usage in arrears, as a line on the invoice rather than as a prepaid balance, Stripe's metered prices are the right tool and credits are the wrong one: Stripe Billing adds 0.7% to the card fees, read on 27 October 2026, and does the invoicing. Lovable's and Replit's built-in payments, read the same day, take a subscription and say nothing about usage, credits or limits, so on those builders the metering is yours either way, and the shape above is the one that holds. > **Key takeaway:** Credits are a ledger the server spends after the work, never a column the > browser writes. Check, work, then consume with an idempotency key; 402 means > buy and 429 means wait; the prices, the store and the low-balance email live > in the platform, and no route in your app sets a balance. ### What breaks, and how you can tell **The balance goes negative, or two clicks charge once.** The page is subtracting a column. Step 3: the balance is only ever moved by `credits.consume` on the server. **A retry charged twice.** No idempotency key, or a key generated per attempt instead of per action. The key comes from the client, one per user action. **The buy screen appears when the user clicked fast.** The app treats 429 as 402, and step 5 says why that is the wrong screen: 429 is the rate limiter, so the message is "try again in a minute" and nothing opens. **Credits were deducted for a run that failed.** The consume ran before the work. Move it after. **A customer says they lost credits and you cannot say where.** They expired, and the balance screen never showed `totalExpired` or the expiring list. Step 4. **Someone has a million credits.** A route sets balances, usually under `/dev/` or `/admin/` with no check. Delete it, and read [the five checks](/blog/vibe-coded-app-hacked-incidents-and-five-checks) before launch. **The free limit never resets, or resets at the wrong time.** A counter column and a cron job. Step 6: the limit is the plan's, and the platform resets it. ### Install The packs, the store and the workflows live in the console; the app needs the SDK and its sign-in: ```bash npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## Add login, teams and paid plans to a Bolt.new app, and keep Bolt Cloud or Supabase for your data > Bolt runs Node in your browser tab, so the three sign-in routes answer inside the preview. Where the live copy of them runs is the one decision this guide is built around. Read on 27 October 2026. - Source: https://www.buildbase.app/guides/add-login-teams-and-paid-plans-to-a-bolt-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-28 - Updated: 2026-11-04 ### In short To add login, teams and paid plans to a Bolt.new app, ask Bolt for the @buildbase/sdk package and the three sign-in handlers from the Vite guide, keep the secret out of the browser and GitHub, and run the live handlers on a host that runs functions. Data stays in Bolt Cloud or Supabase; teams and plans are SDK calls. You are adding real sign-in, a workspace per customer, paid plans and the email that goes out when a card fails to an app Bolt built for you, without moving your data out of Bolt Cloud or your Supabase project. When it works, a stranger opens your live address in a private window, signs up with Google or a magic link, lands in their own workspace, invites a colleague who gets an email, picks a plan on a test card, and the feature they paid for appears without a reload. The client secret never reaches the browser and never reaches GitHub. Bolt is different from the other builders in one way that matters here, and it cuts both ways. Bolt runs Node in your browser tab (its supported technologies page says "Node.js for the backend", JavaScript only, no PHP or Python), so the three small sign-in routes this guide adds answer inside the preview, where you can see them work before you publish. The other edge of it: the preview's server is your tab, and the live site needs a server of its own. Where that lives is the one decision this guide is built around. What we ran on 27 October 2026: the three handlers are the ones from [BuildBase on Vite](/guides/buildbase-on-vite), which have been run end to end in `vite dev` against a real organization on our local stack, and which ran unchanged today as server routes inside the Cloudflare Workers runtime for the [Lovable guide](/guides/add-login-teams-and-paid-plans-to-a-lovable-app). What we have not run: anything inside Bolt itself. The Bolt-specific parts of this guide (the preview, the token prices, Bolt Cloud's sign-in, hosting, secrets and GitHub sync) are read from Bolt's help center today, and the guide says so wherever a Bolt behaviour is the thing that decides whether a step works. > **Before you start:** A Bolt project, on any plan. A BuildBase organization, and an auth client > created in the console under **User Management → Authentication**, with its > client ID and secret. A GitHub account, for step 1's second route. A Stripe > account, only when you reach plans. > **Tip:** Bolt's own help center asks agents to treat it as the source of truth for how > Bolt works. We did. Where this guide and a Bolt page disagree on a Bolt > behaviour, the page is newer than this post, and wins. ### 1. Decide where the live sign-in server runs Sign-in needs one thing a browser cannot hold: a secret. The hosted sign-in page sends a person back to your app with a one-time code, and swapping that code for a session uses the client secret, so the swap runs on a server and the session comes back as an httpOnly cookie on your app's own address. Three small routes do all of it: swap the code, report the session, sign out. During building, this is solved for you. Bolt's preview runs Node in the tab, the Vite dev server runs there, and a small Vite plugin answers the three routes, so the preview is a complete app. For the live site there are two honest routes, and you should pick one before you prompt, because the files differ. **Route A: stay on Bolt hosting.** Bolt's Netlify page says "Bolt hosting supports projects with a backend", and Bolt Cloud has server functions that Bolt deploys for you. What no page in the help center says is the address a server function answers on, or whether it shares your site's address. The cookie only works if the route that sets it lives on the same address as the app. So route A is a try, not a promise: ask Bolt to run the three handlers as server functions, publish, and run the check in step 5. If your live site answers the route with JSON, you are done and this is the simplest setup there is. We have not published a project this way, so we cannot tell you it works. **Route B: keep building in Bolt, run the live site from GitHub.** Bolt's GitHub integration is two-way: "every time you make a change that doesn't break the project, Bolt creates a commit for you", and "it also checks GitHub every 30 seconds for any updates made outside Bolt and pulls those in". Connect the repository to Vercel, Netlify or Cloudflare, where each handler is a one-line function file, and the live site is the same code with a server that we know answers the routes. You keep working in Bolt; the host rebuilds on every commit Bolt makes. The alternative Bolt offers in one click, Netlify from the Publish menu, is not this: Bolt's own page says Netlify there "can't host a database or a traditional backend", which is the one-click static path, not a Netlify site built from your repository. One rule for route B that is easy to miss: Bolt's page says that when the two sides conflict, "Bolt keeps your changes and overwrites the GitHub version", and that merging branches is not supported in Bolt. So make every change in Bolt, never in GitHub directly, and treat the repository as the thing the host reads, not a second place to edit. If your Bolt project is Next.js rather than Vite, the server is already in the app. Bolt's terminal (not available in Safari, where previews are hosted instead) should run `npx buildbase init --org-id `, which writes the route handlers for you, though we have not tried it there; the [v0 guide](/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app) is the Next.js version of this page, and route B applies to hosting it. What you should see: a decision, written down, and for route B a GitHub repository connected from Bolt's project menu (it starts private, on `main`) and imported into your host. ### 2. Register where people come back to The hosted sign-in page sends people back to one exact address per environment, so register them before you prompt: your live address with `/sign-in` on the end, your custom domain with `/sign-in` if you have one, and the address of the preview if you want to test sign-in there. An address it was not told about is refused. The preview is the awkward one. Bolt's preview opens in its own tab at an address Bolt assigns, and that address can change when the project restarts. Most people register the live address and the custom domain, test sign-in there, and use the preview for everything else, which is what we suggest. If you do want sign-in in the preview, open it in a new tab, copy the address, register it with `/sign-in` on the end, and expect to do it again after a restart. This is also where Bolt's own sign-in keeps its version of the same problem. Bolt Cloud's authentication page describes a Site URL, set to `localhost:3000` by default, which "does not work for live applications", and a comma-separated allow list of redirect patterns with wildcards, which Bolt "usually updates" when you publish. Those settings govern Bolt Cloud's sign-in, not this one, and the addresses you register on the BuildBase client are the only ones that matter here. [Login that works after you publish](/guides/login-that-works-after-you-publish) is the troubleshooting page for either. What you should see: the auth client in the console lists each address, and the client secret has been shown once. Do not paste it into the Bolt chat. ### 3. Ask Bolt for the package and the three handlers Paste this prompt. It names the outcome, the rules, the files, and the one thing that must never happen to the secret. Bolt installs the package in the preview, and you can watch `npm install` run in its terminal. ```text Use the @buildbase/sdk npm package to add BuildBase sign-in, a workspace per customer, paid plans and lifecycle email to this app. Keep Bolt Cloud (or my Supabase project) as the database; BuildBase is not the primary database. Do not add Clerk, Auth0, Resend or n8n, and do not enable Bolt Cloud's own sign-in. Stripe is bring-your-own; do not store card data. Read https://www.buildbase.app/llms.txt first and do not invent endpoints. Take the files from https://www.buildbase.app/guides/buildbase-on-vite unchanged: - server/auth.ts with the guide's token, session and signout handlers, byte for byte - the buildbaseAuth Vite plugin in vite.config.ts, so the preview answers POST /api/auth/token, GET /api/auth/session and POST /api/auth/signout - api/auth/token.ts, api/auth/session.ts and api/auth/signout.ts as one-line Vercel function files that export the matching handler - src/context/buildbase-provider.tsx from the guide, with import '@buildbase/sdk/css', wrapping the app in main.tsx Put VITE_BUILDBASE_ORG_ID, VITE_BUILDBASE_CLIENT_ID and VITE_BUILDBASE_REDIRECT_URL in .env, add .env to .gitignore, and leave BUILDBASE_CLIENT_SECRET empty for me to fill in; never read it in the browser and never give it a VITE_ prefix. If sign-in already exists in this app, stop and ask me before changing it. ``` For route A, replace the third line of the file list with: "run the three handlers as Bolt server functions at /api/auth/token, /api/auth/session and /api/auth/signout on the published site, reading BUILDBASE_CLIENT_SECRET from Bolt Secrets". For a Netlify or Cloudflare host on route B, name that host's function folder instead of `api/`; the handlers are plain `Request` to `Response` functions, and the Vite guide says each host needs a one-line wrapper of its own. What you should see: `@buildbase/sdk` in `package.json`, and five new or changed files. The one that matters is the handler that swaps the one-time code for a session, and it is the Vite guide's file. The provider is the guide's too, and the part worth reading is the three callbacks, because each one is a fetch to one of the routes: ```tsx // src/context/buildbase-provider.tsx (trimmed; the Vite guide has the full file) import '@buildbase/sdk/css'; import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; let cached: string | null | undefined; export async function getSession() { if (cached === undefined) { cached = (await (await fetch('/api/auth/session')).json()).sessionId; } return cached ?? null; } export function BuildBaseProvider({ children }: { children: React.ReactNode }) { return ( { const res = await fetch('/api/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); cached = (await res.json()).sessionId; return { sessionId: cached! }; }, onSignOut: async () => { await fetch('/api/auth/signout', { method: 'POST' }); cached = null; }, }, }} > {children} ); } ``` Then the first check, and it is the reason Bolt is a good place to do this. Open the preview's address with `/api/auth/session` on the end. You should see `{"sessionId":null}`: the server half is alive, inside the preview, before any button exists. The Vite plugin answered it, running in your tab. **Correcting potential issues.** Read the change before you accept it. The ways Bolt tends to drift, and the line to paste back: - It switched on Bolt Cloud's sign-in as well, or wrote a `users` table for its own login. Paste: "BuildBase is the only sign-in in this app. Remove the other sign-in pages and the users table for them, and keep every other table." - It put the secret in `.env` as `VITE_BUILDBASE_CLIENT_SECRET`, or read it in the provider. Paste: "BUILDBASE*CLIENT_SECRET is read only inside server/auth.ts. Remove every other reference and the VITE* prefix." - It wrote the three routes as Bolt server functions when you asked for route B, or as Vercel files when you asked for route A. Paste the route you chose, by name, with the file list from the prompt. - `/api/auth/session` returns the app's HTML in the preview. The Vite plugin is missing from `vite.config.ts`. Paste: "Add the buildbaseAuth plugin from the Vite guide to vite.config.ts, before react()." ### 4. The secret, and where it must never go During building, the secret lives in `.env` as `BUILDBASE_CLIENT_SECRET`, with no prefix, next to the three public `VITE_` values. The Node process that reads it is the Vite dev server in your tab, which is yours, so this is safe in the same way a `.env` on your laptop is safe. Two things keep it that way. **`.env` in `.gitignore` before GitHub.** Bolt commits every non-breaking change to the repository on its own, and Bolt's secrets page says "never store secrets in plain text in your code". A `.env` that is not ignored is code as far as a commit is concerned. Check the file before you connect the repository, not after. **A separate auth client for building.** Create a second client in the console, call it "Bolt preview", and use its secret in `.env`. If a preview secret ever leaks, you regenerate that client's secret in the console and nothing about the live site changes. The console shows a secret in full once, when the client is created, so copy it then. For the live site, the secret goes where the functions run. On route B that is the host's environment variables: Vercel's project settings, Netlify's site settings, Cloudflare's secrets. On route A it is Bolt's Secrets page, reached from the database icon at the top of the project, which Bolt's docs say is readable by server functions and, on an individual account, by the project owner only. Prefixes stay the same everywhere: three `VITE_` values the browser may see, one bare value it never does. ```bash # .env (building) and the host's environment variables (live) VITE_BUILDBASE_ORG_ID= VITE_BUILDBASE_CLIENT_ID= VITE_BUILDBASE_REDIRECT_URL=https://your-app.example.com/sign-in BUILDBASE_CLIENT_SECRET= # VITE_BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` The redirect value is the one that differs between building and live: the preview's `.env` carries the preview address, and the host's variables carry the live one. Vite inlines `VITE_` values at build time, so the host builds with its own. What you should see: `.env` listed in `.gitignore`, the repository on GitHub without it, and the host's variables set. Then one more `/api/auth/session` on the preview, still `{"sessionId":null}`, to confirm nothing broke while you moved things around. ### 5. Publish, then run the thirty-second check Publish (route A), or let the host build the latest commit (route B). Then open your live address with `/api/auth/session` on the end, before you click anything. JSON back, `{"sessionId":null}`, means the server half lives on your live address, and the rest of this guide follows. The app's HTML back means the route is not there: on route A, Bolt hosting did not put the server functions under your site's address, and route B is the answer; on route B, the function files are not in the host's function folder, or the host built an older commit. Nothing further works until this check passes, and nothing further is worth debugging until it does. Then sign in. Open the live address in a private window, click the button that calls `signIn()` from `useSaaSAuth()`, and you are sent to the hosted sign-in page, which offers whichever methods you switched on in the console. Sign up with a second email. You come back to `/sign-in` on your app, signed in. Then the two checks a demo skips. Close the browser, reopen the site: still signed in, because the cookie is good for 30 days, which is the [default session length](/guides/token-expired-mid-request). Sign out, then reload: asked to sign in again, because sign-out ended the session on the server rather than clearing a value in the browser. The methods are switches, not code: email and password, a magic link, an email code, a phone sign-in code sent through your own Twilio account, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, and Ethereum or Solana wallets. Turning on Google means creating the client in Google's console and pasting two values; nothing in the Bolt project changes. **Correcting potential issues.** "The redirect address is not allowed" on the hosted page: the address in `VITE_BUILDBASE_REDIRECT_URL` and the one registered on the client differ, usually by a trailing slash, `www`, or the `/sign-in` path. "Sign-in failed" after a correct code: the secret did not reach the function; check the host's variables, and on route A, Bolt's Secrets page. Sign-in works in the preview and not on the live site: the live address is not registered, or the host built with the preview's `.env` values because `.env` was committed after all. ### 6. A workspace per customer, and the colleague they invite Every new user lands in their own workspace on first sign-in, with no setup step. That is on by default for new organizations, and in your app it is one component for the switcher and the hooks the SDK already has. Prompt Bolt for the screens; the data model is already there. ```text Add a workspace switcher to the app header using useSaaSWorkspaces() from @buildbase/sdk/react, and a /settings page that opens the SDK's built-in workspace, members and billing screens. Members with the admin role may invite teammates by email; everyone else sees the member list read-only. Do not create workspace, membership or role tables in Bolt Cloud or Supabase; BuildBase holds them. ``` What you should see: a switcher listing the workspaces the signed-in person belongs to, with **Add team** creating another if you allow it. On the members screen, inviting an address that has no account yet sends an email with a link; the person signs up and lands in the workspace with the role you chose. That flow has been in the SDK since version 0.0.71, and the reasons an invite can be refused (a seat limit, an outsider policy) come back as named errors rather than silence. Why not let Bolt write the tables? Bolt's own security audit is better than most at catching what goes wrong here: its help page says it checks "that protected parts of your app require an account", that "users can't do things you don't intend, like changing a price", and that keys are not "sent to visitors' browsers". What no audit can check is which workspace a row belongs to, because a generated `teams` table has no rule for that until someone writes one, and the role column it adds is checked on one page and nowhere else. The SDK's roles are enforced by the API, so a member who types the address of an admin page is refused by the server, not just by a missing menu item. Bolt Cloud's sign-in page, read today, mentions no roles, teams or permissions for the people using your app, so whatever a prompt builds here is built from scratch. **Correcting potential issues.** If a member can see another workspace's rows by changing an id in the address bar, Bolt wrote a page that reads your database without scoping it. That is your data and your query, and the next section is about it. ### 7. Your data stays where it is: the one honest wrinkle Your tables stay in Bolt Cloud or in your Supabase project. The rule we give every agent is "do not use BuildBase as the primary database", and it applies here. Supabase's own post of 30 September 2025 says Bolt Cloud backends run on Supabase, so the wrinkle is the same on both: row-level security policies keyed to the old sign-in (`auth.uid()` and friends) do not know who a BuildBase user is, because a BuildBase session is an opaque id, not a token Supabase can read. There are two ways through, and most apps want the first. **Read and write through server routes.** A function on the host (or a server function on route A) checks the BuildBase session and queries your database with a server-side credential, scoped by the BuildBase user or workspace id. This is the pattern generated apps should use anyway, because it puts the permission check where it cannot be forged. The server SDK makes the check one call: ```ts // server/buildbase.ts import BuildBase from '@buildbase/sdk'; // The Vite guide's cookie: bb-session-id, or bb-session-id- when // VITE_BUILDBASE_ENVIRONMENT names a development or staging environment. const readCookie = (request: Request) => (request.headers.get('cookie') ?? '').match( /(?:^|;\s*)bb-session-id=([^;]+)/ ); export function bbFor(request: Request) { const match = readCookie(request); return BuildBase({ serverUrl: process.env.VITE_BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app', orgId: process.env.VITE_BUILDBASE_ORG_ID!, getSessionId: async () => (match ? decodeURIComponent(match[1]) : null), }); } ``` A route that needs the user calls `bbFor(request).users.getProfile()`, and a missing or expired session comes back as an error rather than a guess. **Mint a Supabase-shaped token for browser queries.** If pages query Supabase directly from the browser and you want the existing policies to keep working, add one more function: it validates the session with the server SDK, then signs a short-lived HS256 token with your Supabase project's JWT secret, with `sub` set to the BuildBase user id and `role` and `aud` set to `authenticated`, and the browser passes it to Supabase as the bearer token. `auth.uid()` then matches `sub`, so store the BuildBase user id in your owner columns. The step-by-step is in [the skill repository](https://github.com/buildbase-app/claude-skill/blob/main/distribution/supabase-jwt.md). You own that route and its refresh schedule. The platform change that would make it unnecessary, BuildBase publishing signing keys so Supabase can verify a user token directly, is recorded as not built. Run Bolt's database review after a change this size. Its help page says it "checks your database rules and permissions and flags anything that could make your data insecure, like a permission rule that allows anyone to read a table", and the full audit is a free button in the Publish menu (prompting Bolt to audit costs tokens; the button does not). ### 8. Plans people can pay for, and the email when a card fails Plans, prices and trials live in the BuildBase console and sync to your own Stripe account at Stripe's rates, with a 0% platform fee, and no card data touches your app. The part that generated apps get wrong is what happens after the payment, so this step is mostly about the webhook route and the feature flag. In the console, create two plans, Launch and Pro, say, each with a 7-day trial and a monthly and a yearly price. Then the webhook. It is a fourth function, and this is the prompt for it: ```text Add api/webhooks/buildbase.ts as a POST function. Verify the signature with parseWebhookEvent from @buildbase/sdk on the raw request body, using BUILDBASE_WEBHOOK_SECRET from the host's environment variables. Handle payment.failed with our own side effects only (flag the workspace, post to Slack); the platform emails the customer itself, but only once I have connected an email sender and switched on the Payment Failed notification event in the console. Ignore other events. Gate the export feature behind a BuildBase feature flag tied to the Pro plan, checked in a function. Do not store the plan in Bolt Cloud or Supabase. ``` Point an endpoint in the console at `https://your-app.example.com/api/webhooks/buildbase`, add its signing secret to the host as `BUILDBASE_WEBHOOK_SECRET`, and publish. What you should see: subscribe on a test card and the Pro feature appears without a reload, because the flag follows the workspace's plan. Let the test card fail on renewal and the email goes out from your sending domain, because `payment.failed` is one of the 129 events in the catalog and the console's notification or a workflow sends it; the route in your app is for whatever you want to happen besides. The console's delivery log shows each attempt, and a delivery your server was down for is retried up to five times over about two and a half minutes. Compare that with Bolt's own Stripe integration, read today: one-time payments and subscriptions, with "automatic webhook handling for payment events", and the page says Bolt "automatically handles webhook endpoint registration and signature verification", on a project that uses Bolt Database or Supabase and has sign-in set up, and not with Firebase. That is a good integration for selling one thing to one person. What the page does not describe is a plan that belongs to a team, seats, limits, trials that end without a card, or credits, so if a plan has to change what the app does for a whole workspace, [entitlements rather than flags](/blog/entitlements-are-not-feature-flags) is the ten-minute read before you prompt. ### Where Bolt's built-in wins Keep Bolt Cloud's sign-in when your app has one user per account and you need nothing after login. It is zero-config inside Bolt, it lives in the same place as your database, its Site URL and redirect list are updated for you when you publish, and nothing leaves Bolt hosting. Keep Bolt's Stripe integration when you sell one subscription to one person and want the webhooks registered and verified without touching them. And keep Bolt's security audit in either case; it is free from the Publish menu, and it checks things (a changed price, a key in the browser) that this guide's setup does not make go away. Choose BuildBase when the question is "what may this team do now that they paid": a workspace per customer, invites and roles enforced by the API, plans with versions, feature flags tied to the plan, credits with a hard stop, and the lifecycle email, from one SDK, with your data staying in Bolt Cloud. That is the layer Bolt's help center does not reach today, and [the launch checklist](/guides/vibe-coded-app-launch-checklist) is the twenty-item version of why it matters before strangers arrive. > **Key takeaway:** On Bolt the preview is a real server, so the three routes work before you > publish. The whole job is making sure the live site has a server too, and the > thirty-second check in step 5 tells you whether it does. ### What this costs in tokens Bolt prices building by tokens. On 27 October 2026 its pricing page lists Free at $0 with 1M tokens a month and a 300K daily cap, Pro at $25 a month with 10M tokens, rollover and no daily cap, Teams at $30 a member starting at 10M tokens each, and Enterprise by consumption, with "save up to 28%" on the annual toggle. Hosting is separate and per account: Free gets 10 GB of bandwidth and 333,333 requests a month, after which the site stops displaying until the month resets; Pro gets 30 GB and 1 million requests with pay-as-you-go above that. Bolt changes these; check the page. The prompt in step 3 is one request, with perhaps two fix-ups; steps 6 and 8 are one each. The expensive thing on Bolt is not a feature, it is a loop. A one-star Trustpilot review from 29 August 2026 put it as "half the time you spend your tokens trying to resolve issues that their own AI has created itself", and another, from 4 October, reported "approximately 212K Tokens out of my 300K daily allowance" gone "in a very short period of time". Naming the exact files, the exact variable names and the exact guide is how you avoid the loop, and it is why this page is long. The other half is step 5: do not spend tokens debugging sign-in until the thirty-second check passes, because until it does, the problem is not in the code Bolt wrote. BuildBase's side: a Free plan at $0, then Launch at $19 a month, with a 7-day trial and no card on the paid plans. ### What breaks, and how you can tell **`/api/auth/session` returns HTML on the live site and JSON in the preview.** Step 5. The live site has no server for the routes: on route A the functions are not under your site's address, on route B the function files are not in the host's folder. Route B, or the folder. **"Sign-in failed" on a correct code.** The secret did not reach the function. Check the host's variables, or Bolt's Secrets page on route A. **Sign-in works in the preview and loops on the live site.** The live address is not registered with `/sign-in` on the end, or the host built with the preview's redirect value because `.env` was committed. Step 2 and step 4. **The secret is in the repository.** `.env` was not ignored before Bolt connected GitHub. Regenerate the secret in the console (the old one stops working immediately), add `.env` to `.gitignore`, and treat the old value as public. **The preview address changed and sign-in there stopped.** The project restarted. Register the new address, or test sign-in on the live site only. **Rows vanish, or "permission denied", after switching sign-in.** Row rules keyed to the old sign-in no longer match. Section 7: route the reads through the server, or mint the token. **The package install fails in the preview.** Bolt runs Node inside the browser, which cannot load compiled native addons, and the SDK's dependencies are plain JavaScript, so read the install error before assuming the package; it is usually another dependency the agent added in the same change. ### Install In Bolt, the install is a sentence in the chat: "Use the @buildbase/sdk npm package", and `npm install` runs in the preview's terminal. On a checkout of the repository, it is the usual line: ```bash npm i @buildbase/sdk ``` --- ## Add login, teams and paid plans to a Replit Agent app, and keep Replit's database for your data > A Replit project is a real Linux workspace with a shell, so the SDK installs like anywhere else. The three sign-in routes go on the Express server Agent already wrote; we ran them on 27 October 2026. - Source: https://www.buildbase.app/guides/add-login-teams-and-paid-plans-to-a-replit-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-28 - Updated: 2026-11-04 ### In short To add login, teams and paid plans to a Replit Agent app, run npx buildbase init, mount the three sign-in handlers on the Express server through a 26-line adapter tested on 27 October 2026, put the secret in Secrets and in the published app, and keep your data in Replit Database. Teams and plans are SDK calls. You are adding real sign-in, a workspace per customer, paid plans and the email that goes out when a card fails to an app Replit's Agent built for you, without moving your data out of Replit Database. When it works, a stranger opens your published address in a private window, signs up with Google or a magic link, lands in their own workspace, invites a colleague who gets an email, picks a plan on a test card, and the feature they paid for appears without a reload. The client secret lives in Secrets and never reaches the browser. Replit is the easiest of the builders to do this on, for one reason: a Replit project is a real Linux workspace with a shell. `npm install` installs, `npx` runs, and the server Agent wrote is a Node process you can read. There is no "where does the server live" question, which is most of the Bolt and Lovable guides. The question here is different: Replit does not document which stack Agent generates, so step 1 is finding out, and the rest of the guide is written for the layout Replit's own pages describe indirectly, a React front end on an Express server with PostgreSQL behind it. What we ran on 27 October 2026: the three sign-in handlers from [BuildBase on Vite](/guides/buildbase-on-vite), unchanged, mounted on Express 4.22.3 through a 26-line adapter, with `@buildbase/sdk` 0.0.90 installed from npm, Node 22, the API routes ahead of a stand-in for the Vite middleware, on port 5000 as Replit's template expects. Each route answered as the guide says it should: the session route returned `{"sessionId":null}` with no cookie and `{"sessionId":"abc123"}` with one, the token route returned 400 with no code and 401 with a bogus one (our platform rejected it, as it should), and sign-out set the cookie with `Max-Age=0`. The same results held with `express.json()` applied globally before the routes, which is how Agent's generated server does it, and `tsc` reported no errors. What we have not run: anything inside Replit itself (the Shell, Secrets, Publishing), `npx buildbase init` in a Replit project, the ESM layout Replit's template uses, or the hosted sign-in round trip, which needs a registered address. Where a Replit behaviour decides whether a step works, this guide quotes Replit's page and says so. > **Before you start:** A Replit project built by Agent, on any plan (Starter publishes one app, which > Replit's page says goes down after 30 days). A BuildBase organization, and an > auth client created in the console under **User Management → Authentication**, > with its client ID and secret. Your published address, registered on that > client as a redirect URL ending in `/sign-in`. A Stripe account, only when you > reach plans. > **Tip:** The handlers in this guide are the Vite guide's, byte for byte, and the > server-side pattern is the [Express guide](/guides/buildbase-on-express)'s. > This page is the Replit wrapping around them: the Shell, Secrets, the adapter, > and the prompts that keep Agent on the rails. ### 1. Find out what Agent built Open `package.json` from the file tree and read the dependencies. Then open `replit.md`, which Agent writes at the root of every project and reads before every request; its first lines usually name the stack. Replit's docs do not state what Agent generates, but three of its pages say it sideways. The deployment types page says "Agent builds full-stack apps that need a backend server, so use Autoscale or Reserved VM for those". The Clerk Auth page says Agent protects "your API routes" with "Clerk's Express middleware". And the `replit.md` examples describe "React frontend, Node.js backend, PostgreSQL database" and an app "built with React and Express.js". So the layout to expect is one `package.json` with `react`, `vite`, `express` and a Postgres client, a `client/` folder the Vite dev server serves, a `server/` folder Express runs, and a `shared/` folder between them. Three cases, and what each means for the rest of this page: - **`express` and `vite` both listed.** This guide applies as written. The three routes go on the Express server, and the provider goes in the React app. - **`next` listed.** You have a Next.js app, and `npx buildbase init` in the Shell writes all ten files, including the three route handlers and the webhook. Follow the [v0 guide](/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app) from its step 2 and come back here for Secrets and Publishing. - **`express` with no `vite`, or a server with HTML templates.** The [Express guide](/guides/buildbase-on-express) is the right one: the server drives sign-in itself and `req.user` keeps working. What you should see: a sentence you can say out loud, "my app is React on Express with Postgres", before you prompt anything. ### 2. Register where people come back to The hosted sign-in page sends people back to one exact address per environment, so register them before you prompt: your published `.replit.app` address with `/sign-in` on the end, your custom domain with `/sign-in` if you have one, and the preview's `replit.dev` address if you want to test sign-in before publishing. An address it was not told about is refused. The preview address is the one to watch. It is a `replit.dev` address Replit assigns to the running project, and it is not the published one. Register it if you want to sign in during building; otherwise register the published address and test sign-in there. Replit's own sign-in keeps a list of your app's domains in the `REPLIT_DOMAINS` environment variable and asks you to republish to refresh it; that list governs Replit Auth, not this one, and the addresses on the BuildBase client are the only ones that matter here. [Login that works after you publish](/guides/login-that-works-after-you-publish) is the troubleshooting page for either. What you should see: the auth client in the console lists each address, and the client secret has been shown once. Do not paste it into the Agent chat or into `replit.md`. ### 3. Install the skill and run `init` in the Shell Open the Shell (Tools, then Shell) and run three commands. The first installs the BuildBase skill, which is the set of rules that keeps Agent from building its own sign-in next to this one; the second installs the SDK; the third writes the provider and the environment file. ```bash npx skills add buildbase-app/claude-skill npm i @buildbase/sdk npx buildbase init --org-id ``` Replit's Agent Skills page says installed skills live under `/.agents/skills/`, that "only a brief description loads until the skill is invoked", and that skills "installed via CLI or copied from the internet have not" been audited, so read the skill's `SKILL.md` once yourself; it is short. If the first command put the skill somewhere else, move the folder under `.agents/skills/`. `init` reads `package.json` to tell Next.js, Vite and Express apart. When it finds both `vite` and `express`, it treats the project as Vite, because that is the order it checks in, so on this layout it writes the provider under `src/` (or `client/src/`) and `.env.example` with the variable names, and prints the Vite guide's address for the three handlers, which step 4 covers. It never overwrites a file. It leaves every secret empty and refuses a secret passed on the command line, which is the behaviour you want in a shared workspace. We have not run it inside a Replit project; if it reports a path you did not expect, the provider is one file and step 4's prompt names where it goes. Then two lines in `replit.md`, so every future request starts from the same rules: ```text ## Sign-in, teams and billing BuildBase (@buildbase/sdk) is the only sign-in in this app. Do not add Replit Auth, Clerk or a users table. Workspaces, roles, plans and credits live in BuildBase; app data stays in Replit Database and every query scopes by the workspace id from the BuildBase session. Secrets stay in the Secrets tool, never in code, never with a VITE_ prefix. ``` What you should see: `@buildbase/sdk` in `package.json`, a provider file, `.env.example`, and the two lines in `replit.md`. ### 4. Mount the three routes on Express The handlers are the Vite guide's `server/auth.ts`, plain `Request` to `Response` functions. Express 4 speaks its own request and response objects, so a small adapter turns one into the other. This is the file we ran today, as written: ```ts // server/buildbase-routes.ts import express, { Router, type Request as Req, type Response as Res, } from 'express'; import { session, signout, token } from './auth.js'; type WebHandler = (request: Request) => Response | Promise; /** Run a web-standard `Request -> Response` handler as an Express route. */ const adapt = (handler: WebHandler) => async (req: Req, res: Res) => { const headers = new Headers(); for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value); const hasBody = req.method !== 'GET' && req.method !== 'HEAD' && req.body !== undefined; const request = new Request( `${req.protocol}://${req.get('host')}${req.originalUrl}`, { method: req.method, headers, body: hasBody ? JSON.stringify(req.body) : undefined, } ); const response = await handler(request); res.status(response.status); response.headers.forEach((value, name) => res.append(name, value)); res.send(Buffer.from(await response.arrayBuffer())); }; export const authRouter = Router(); authRouter.post('/api/auth/token', express.json(), adapt(token)); authRouter.get('/api/auth/session', adapt(session)); authRouter.post('/api/auth/signout', adapt(signout)); ``` Two choices in it are deliberate. The token route parses JSON with `express.json()` and re-serialises the body, rather than streaming the raw request, because Agent's generated `server/index.ts` applies `express.json()` to every route before any of yours, which consumes the stream; this adapter works either way, and we checked both. And `Set-Cookie` is copied with `res.append`, so the session cookie arrives as its own header rather than folded into another. Then the router goes on the app before the Vite middleware, so the API is never swallowed by the front-end fallback. Paste this prompt: ```text Use the @buildbase/sdk npm package, already installed, to add BuildBase sign-in to this app. Read https://www.buildbase.app/llms.txt first and do not invent endpoints. - Create server/auth.ts with the token, session and signout handlers from https://www.buildbase.app/guides/buildbase-on-vite, byte for byte. - Create server/buildbase-routes.ts with the adapter from the BuildBase Replit guide and mount authRouter in server/index.ts before the Vite middleware and before any catch-all route. - Keep the BuildBaseProvider that npx buildbase init wrote and wrap the React app in it in client/src/main.tsx, with import '@buildbase/sdk/css'. - Read VITE_BUILDBASE_ORG_ID, VITE_BUILDBASE_CLIENT_ID and VITE_BUILDBASE_REDIRECT_URL from the environment; I will add BUILDBASE_CLIENT_SECRET in Secrets myself. Never read it in client/ and never give it a VITE_ prefix. - Do not add Replit Auth, Clerk, Passport or a users table. If sign-in already exists in this app, stop and ask me before changing it. ``` What you should see: three new files and one changed one, and nothing under `client/` that mentions the secret. The provider `init` wrote is the Vite guide's: `getSession` fetches `/api/auth/session` once per page load, `handleAuthentication` posts the one-time code to `/api/auth/token`, and `onSignOut` posts to `/api/auth/signout`, so the three routes are the whole contract between the two halves. **Correcting potential issues.** Read the change before you accept it. The ways Agent tends to drift, and the line to paste back: - It mounted the router after the catch-all, so `/api/auth/session` returns the app's HTML. Paste: "Mount authRouter in server/index.ts before the Vite middleware and before any route that serves index.html." - It rewrote the handlers as Express middleware with `req.body` and `res.cookie`. Paste: "Keep server/auth.ts byte for byte as the guide has it and keep the adapter; do not rewrite the handlers." - It added Replit Auth "as a fallback", or kept a `users` table for its own login. Paste: "BuildBase is the only sign-in in this app. Remove the other sign-in and its users table, and keep every other table." - It read the secret in a client file, or prefixed it `VITE_`. Paste: "BUILDBASE*CLIENT_SECRET is read only inside server/auth.ts on the server. Remove every other reference and the VITE* prefix." ### 5. Secrets, twice Open Tools, then Secrets under Setup, and add `BUILDBASE_CLIENT_SECRET` with the value the console showed you once. Replit's secrets page says the tool "automatically encrypts the data and makes it available to your Replit project as an environment variable", which is exactly how `server/auth.ts` reads it. The three public values can go in the same tool as configurations (its "separate sections for secrets and configurations") or in `.env`; either way they reach Vite as `VITE_` variables, which Vite inlines into the browser bundle, which is fine for an organization id and a client id and fatal for a secret. ```bash # Secrets tool (the one bare value) and configurations (the three public ones) BUILDBASE_CLIENT_SECRET= VITE_BUILDBASE_ORG_ID= VITE_BUILDBASE_CLIENT_ID= VITE_BUILDBASE_REDIRECT_URL=https://your-app.replit.app/sign-in # VITE_BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` Then the second time, and this is the step people miss. Replit's troubleshooting page says "Secrets you set in the Project Editor do not automatically carry over to your published app. Add all production Secrets and environment variables in the Publishing pane", under Adjust settings, Production app secrets. One value differs between the two: the redirect, which carries the `replit.dev` address in development and the published one in production, and Replit's secrets page adds that the tool has a "New published app configuration" option for exactly this. What you should see: `printenv | grep BUILDBASE` in the Shell lists the four names with the secret present (Replit's page says `printenv` is how to see every variable; organization members without the Owner role cannot read secret values in the tool but can print them, which is worth knowing before you share the workspace). ### 6. Run, then publish, then sign in from a private window Press Run and open the preview. Before any button exists, open the preview's address with `/api/auth/session` on the end. You should see `{"sessionId":null}`: the server half is alive. That is the response we got today from the same router on the same handlers, and it is the first thing to check whenever sign-in misbehaves later, because the app's HTML there means the route is not mounted ahead of the fallback. Publish with the default deployment type. Replit's page says Autoscale "is the default and recommended choice" for web apps and APIs, that Static "is not compatible with Replit Apps created using Agent", and that Secrets "are available for all deployment types except Static Deployments". `REPLIT_DEPLOYMENT` is set to `1` in the published app if you ever need to tell the two apart in code. Then sign in. Open the published address in a private window, click the button that calls `signIn()` from `useSaaSAuth()`, and you are sent to the hosted sign-in page, which offers whichever methods you switched on in the console. Sign up with a second email. You come back to `/sign-in` on your app, signed in. Then the two checks a demo skips. Close the browser, reopen the site: still signed in, because the cookie is good for 30 days, which is the [default session length](/guides/token-expired-mid-request). Sign out, then reload: asked to sign in again, because sign-out ended the session on the server rather than clearing a value in the browser; today's test showed the sign-out response clearing the session cookie with `Path=/; HttpOnly; SameSite=Lax; Max-Age=0`. The guide names that cookie `bb-session-id`, as `npx buildbase init` does. The methods are switches, not code: email and password, a magic link, an email code, a phone sign-in code sent through your own Twilio account, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, and Ethereum or Solana wallets. Turning on Google means creating the client in Google's console and pasting two values; nothing in the Replit project changes. **Correcting potential issues.** "The redirect address is not allowed" on the hosted page: the address in `VITE_BUILDBASE_REDIRECT_URL` and the one registered on the client differ, usually by a trailing slash or the `/sign-in` path, or production is still carrying the `replit.dev` value. "Sign-in failed" after a correct code: the secret did not reach the published app; Production app secrets, not the editor's Secrets, is where it has to be. The preview works and the published app does not: Replit's troubleshooting page puts production Secrets and the port configuration first, and so do we. ### 7. A workspace per customer, and the colleague they invite Every new user lands in their own workspace on first sign-in, with no setup step. That is on by default for new organizations. In your app it is one component for the switcher plus the hooks the SDK already has, so prompt Agent for the screens; the data model is already there. ```text Add a workspace switcher to the app header using useSaaSWorkspaces() from @buildbase/sdk/react, and a /settings page that opens the SDK's built-in workspace, members and billing screens. Members with the admin role may invite teammates by email; everyone else sees the member list read-only. Do not create workspace, membership or role tables in Replit Database; BuildBase holds them. Add a workspace_id column to every table that holds customer data, filled from the BuildBase session on the server, and filter every query by it. ``` What you should see: a switcher listing the workspaces the signed-in person belongs to, with **Add team** creating another if you allow it. On the members screen, inviting an address that has no account yet sends an email with a link; the person signs up and lands in the workspace with the role you chose. That flow has been in the SDK since version 0.0.71, and the reasons an invite can be refused (a seat limit, an outsider policy) come back as named errors rather than silence. Why not let Agent write the tables? Because Replit's own options do not have this layer either, and the page says so. Replit Auth means "users sign in with their existing Replit accounts" on a Replit-branded page. Clerk Auth gives your app its own tenant and branded sign-in, and under "What's not supported" the same page lists "Organization tenants, Clerk's organization and team-membership features". So whatever Agent builds for teams, it builds from scratch. Every audit of a generated app finds the same thing: a role column checked on one page and nowhere else. The SDK's roles are enforced by the API, so a member who types the address of an admin page is refused by the server, not just by a missing menu item. **Correcting potential issues.** If a member can see another workspace's rows by changing an id in the address bar, Agent wrote a query that filters by the row id and not by the workspace. That is your data and your query, and the next section is about it. ### 8. Your data stays in Replit Database, and it is simpler here Your tables stay in Replit Database. The rule we give every agent is "do not use BuildBase as the primary database", and it applies here. On Supabase-shaped backends there is a wrinkle, because row-level security policies keyed to the old sign-in cannot read a BuildBase session; on Replit there is not, because the database is PostgreSQL that your Express server reads with a server-side connection, and the permission check lives in the route, where it cannot be forged. So the pattern is one helper and one habit. The helper binds the server SDK to the request's cookie: ```ts // server/buildbase.ts import BuildBase from '@buildbase/sdk'; import type { Request } from 'express'; export function bbFor(req: Request) { // The Vite guide's cookie: bb-session-id, or bb-session-id- when // VITE_BUILDBASE_ENVIRONMENT names a development or staging environment. const match = (req.headers.cookie ?? '').match( /(?:^|;\s*)bb-session-id=([^;]+)/ ); return BuildBase({ serverUrl: process.env.VITE_BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app', orgId: process.env.VITE_BUILDBASE_ORG_ID!, getSessionId: async () => (match ? decodeURIComponent(match[1]) : null), }); } ``` The habit is that every route that touches customer data asks the SDK who is asking and which workspace they are in, and passes that workspace id into the query. A route with no session gets an error from the SDK rather than a guess, and a query without a `workspace_id` filter is the bug to look for in every change Agent makes from now on. The pattern is spelled out, with the audit that found "any logged-in user could grant themselves admin", in [teams, invites and admin versus member](/guides/teams-invites-and-roles-for-a-vibe-coded-app). One Replit-specific comfort. After the July 2025 incident in which the agent deleted a customer's production database during a code freeze, Replit rolled out automatic separation of development and production databases, so the test data you create in the preview does not sit next to real customers' rows. Jason Lemkin's line from that week, "there is no way to enforce a code freeze in vibe coding apps like Replit", is the reason to keep the permission check in a route you can read rather than in a table rule you cannot. ### 9. Plans people can pay for, and the email when a card fails Plans, prices and trials live in the BuildBase console and sync to your own Stripe account at Stripe's rates, with a 0% platform fee, and no card data touches your app. The part that generated apps get wrong is what happens after the payment, so this step is mostly about the webhook route and the feature flag. In the console, create two plans, Launch and Pro, say, each with a 7-day trial and a monthly and a yearly price. Then the webhook. On Express it needs the raw body, because the signature is computed over the bytes, and Agent's global `express.json()` would parse them first: ```text Add server/buildbase-webhook.ts and mount it in server/index.ts as app.post('/api/webhooks/buildbase', express.raw({ type: 'application/json' }), buildbaseWebhook), before express.json(). Verify the signature with parseWebhookEvent from @buildbase/sdk on the raw body, using BUILDBASE_WEBHOOK_SECRET from Secrets. Handle payment.failed with our own side effects only (flag the workspace, post to Slack); the platform emails the customer itself, but only once I have connected an email sender and switched on the Payment Failed notification event in the console. Ignore other events. Gate the export feature behind a BuildBase feature flag tied to the Pro plan, checked in a server route. Do not store the plan in Replit Database. ``` Point an endpoint in the console at `https://your-app.replit.app/api/webhooks/buildbase`, add its signing secret as `BUILDBASE_WEBHOOK_SECRET` in Secrets and again in Production app secrets, and republish. What you should see: subscribe on a test card and the Pro feature appears without a reload, because the flag follows the workspace's plan. Let the test card fail on renewal and the email goes out from your sending domain, because `payment.failed` is one of the 129 events in the catalog and the console's notification or a workflow sends it; the route in your app is for whatever you want to happen besides. The console's delivery log shows each attempt, and a delivery your server was down for is retried up to five times over about two and a half minutes. Autoscale scales to zero when idle, which is fine: the first retry wakes it. Compare that with Replit's own routes to payments, read today: the Stripe connector, on paid plans, where Agent sets up a Stripe sandbox and you connect the live account from the Publish pane, or your own keys in Secrets with the Checkout page and webhook endpoint Agent writes. Its Stripe page walks through deposits, balance charges and refunds for a booking app and mentions a monthly subscription with Stripe Billing as a customisation. It says nothing about a plan that belongs to a team, seats, limits, trials that end without a card, or credits, so if a plan has to change what the app does for a whole workspace, [entitlements rather than flags](/blog/entitlements-are-not-feature-flags) is the ten-minute read before you prompt. ### Where Replit's built-in wins Keep Replit Auth when your app is a prototype or an internal tool and Replit branding is acceptable, which is Replit's own description of where it fits; it is one sentence to Agent, Replit sends the password reset emails for you, and there is nothing to configure. Keep Clerk Auth when you want a branded sign-in with separate development and production user stores and you need nothing after login; Replit provisions the tenant, stores the keys and switches them at publish time, and its migration from Replit Auth to Clerk moves the accounts for you. Keep Replit's Stripe connector when you sell one thing to one person and want the sandbox and the live switch handled for you. Choose BuildBase when the question is "what may this team do now that they paid": a workspace per customer, invites and roles enforced by the API, plans with versions, feature flags tied to the plan, credits with a hard stop, and the lifecycle email, from one SDK, with your data staying in Replit Database. That is the layer Replit's pages list as not there today, and [the launch checklist](/guides/vibe-coded-app-launch-checklist) is the twenty-item version of why it matters before strangers arrive. > **Key takeaway:** On Replit there is a shell and a server, so nothing here is a workaround: the > three routes mount on Express through 26 lines we ran today. The two things to > get right are the secret, twice, and a workspace id on every query. ### What this costs in credits Replit prices Agent work by effort. Its AI billing page says one checkpoint is created per request, that complex builds are "bundled into one checkpoint that may cost more than a simple request", and that "Replit asks for confirmation before a paid action". On 27 October 2026 the pricing page lists Core at $20 a month ($18 billed annually) with $20 towards models, Pro at $100 ($90 annually) with $100 and rollover for two months, and Enterprise as custom; the Starter plan has daily Agent credits up to a monthly cap and one published app that goes down after 30 days. Published apps, the database and storage are billed by usage from the same credits. Replit changes these; check the page. The prompts in steps 4, 7 and 9 are three checkpoints, with perhaps two fix-ups. The expensive thing on Replit is not a feature, it is a loop, and the loop here has a name: a one-star Trustpilot review from 17 October 2026 reads, in full, "Users can't log in. AI gets into a failure loop." Another, from 20 September, warns that "especially if you set the limit 50 dollar it turns out take 300 dollar". Naming the exact files, the exact routes and the exact guide is how you avoid the loop, and `replit.md` is how you avoid it next month too. A non-developer who built a SaaS on Replit in three hours in July 2026 chose it because "I wanted authentication, payments, and a database without configuring anything myself", and called the lock-in "the uncomfortable trade-off for the convenience"; this guide is the version of that trade where the accounts, the teams and the plans are yours to take with you. BuildBase's side: a Free plan at $0, then Launch at $19 a month, with a 7-day trial and no card on the paid plans. ### What breaks, and how you can tell **`/api/auth/session` returns the app's HTML.** Step 4. The router is mounted after the Vite middleware or the catch-all. Move it up. **"Sign-in failed" on a correct code.** The secret is not in Production app secrets, only in the editor's Secrets. Step 5, the second half. **Sign-in works in the preview and loops after publishing.** Production is still carrying the `replit.dev` redirect value, or the published address is not registered with `/sign-in` on the end. Step 2 and step 5. **The token route returns 400 with a stack trace in the log.** The body was not JSON. The adapter hands malformed JSON to Express's parser, which answers 400 on its own; the provider always sends JSON, so this is a hand-made request, not the app. **The webhook returns 401 on every delivery.** `express.json()` parsed the body before the raw handler saw it. Mount the webhook route with `express.raw` ahead of `express.json()`. **A member can see another workspace's rows.** The query filters by the row id and not by `workspace_id`. Section 8, the habit. **`npx buildbase init` says "could not tell the framework".** Neither `next`, `vite` nor `express` is in `package.json`. Pass `--framework vite` for the provider, and mount the routes by hand as in step 4. ### Install In the Shell: ```bash npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## Emails that arrive: confirmation, reset and welcome emails for an AI-built app > The confirmation email worked for you and never reaches a stranger, because the sender is for development. Find the sender, put your domain behind it, and make the lifecycle emails run on their own. - Source: https://www.buildbase.app/guides/emails-that-arrive-for-an-ai-built-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-28 ### In short An AI-built app sends confirmation and reset emails through a development sender until you connect a domain: Supabase delivers only to your project team, two an hour, and BuildBase uses whichever sender was created first. Find the sender, verify a domain, move the default, then make the lifecycle emails workflows. "Then a real person signs up, never gets the confirmation email, and you never hear from them again." A dev.to writer put that at the top of a seven-step guide for beginners on 20 October 2026, and it is the whole failure in one sentence: the email worked for you, in the preview, and that is the last time it worked. You are making three kinds of email arrive, in this order: the ones the app cannot work without (confirmation, magic link, password reset, invitation), the ones that make it a product (welcome, trial ending, card failed), and the ones people opt into (campaigns, digests). When it works, a stranger signs up from a Gmail address, gets the confirmation in under a minute from your own domain, the welcome arrives after it, the trial-ending reminder goes out three days before the trial ends with no code involved, and every one of those messages is in a log you can open. What we ran on 27 October 2026: the sender, domain and workflow pieces here are the ones the published guide on [transactional email landing in spam](/guides/transactional-email-landing-in-spam) and the notifications guide are built on; the Supabase and Resend figures were read from their pages today. We have not sent test mail through a builder's own pipeline today, so where a builder's behaviour matters it is named rather than claimed. > **Before you start:** A domain you control and can add DNS records to. An app with sign-in working, > either the builder's built-in or BuildBase. A second email address at a > provider you do not use for work, to test with. For the workflow steps, > BuildBase sign-in, because the triggers are platform events. ### 1. Find out which sender sent the last email Before you touch DNS, open the last email your app sent and read the sender address, because the fix depends entirely on who sent it. There are three usual answers, and two of them are development senders. **The builder's or Supabase's default sender.** If your app's sign-in is Lovable Cloud, Bolt Cloud or your own Supabase project, the confirmation email comes from Supabase's built-in sender until you change it. Supabase's docs on custom SMTP say three things about that sender: "Supabase Auth will refuse to deliver messages to addresses that are not part of the project's team", "currently this value is set to 2 messages per hour", and the server "is not meant for production use". That is why your own confirmation arrived and a stranger's did not: you are on the team, and they are not, and even on the team the third sign-up in an hour waits. **A personal Google account somebody connected during setup.** This is the BuildBase version of the same trap, and it is quieter. System mail (the magic link, the verification code, the password reset code, the workspace invitation) does not name a sender; it goes through whichever single sender in the organization is flagged as the system default, which is usually the first sender anyone created. Every way of creating a sender fills that flag only if it is empty, and never moves it. So if someone connected their own Google account to check that email works, and weeks later someone else added a verified domain and a Mailgun sender on it, every sign-in link since has still gone out through Gmail, from the first person's address, and no DNS record you fix will change that. **An email API the agent wired directly.** A `fetch` to Resend's or SendGrid's API with a key from the environment and a hard-coded sender, usually `onboarding@resend.dev` or a bare address on an unverified domain. It works in the sense that the request is well formed; Resend's free plan sends 3,000 emails a month, 100 a day, and the test domain is for testing. How to prove which one you have: in Supabase, Authentication, SMTP Settings tells you whether custom SMTP is on; in BuildBase, the email history row stores the `from` it used and the sender it went through, and an organization owner can list every sender in the org with its `systemDefault` flag. If the sender you expected is not the one in the history, step 3 is the fix. What you should see: one sentence you can say out loud, "the confirmation email goes out through X from address Y", before you change anything. ### 2. Put a domain you own behind it A sender on a domain you own, with the three DNS records that let other mail servers trust it, is the whole of deliverability for an app this size. On BuildBase, connect a sender through Google, Mailgun, Amazon SES or your own SMTP; on Supabase, turn on custom SMTP with a sender from any of the services its docs name (Resend, SES, Postmark, SendGrid, ZeptoMail, Brevo), after which mail goes to everyone, at 30 an hour until you raise the limit on the rate-limits page. Two decisions before the records: **A subdomain, not the root.** Send from `mail.example.com` rather than `example.com`. If a campaign ever damages the sending reputation, it damages the subdomain, and your personal mail on the root keeps arriving. It also lets the sign-in mail and the marketing mail live on different subdomains with different reputations. **One sender for system mail.** The magic link, the reset code and the invitation should come from a sender on the verified domain, with a From name that is your product and a reply-to that a human reads. A reset code from `no-reply@mail.example.com` with the product name is fine. One from `firstname.lastname@gmail.com` is the first thing a stranger notices. The records themselves (SPF, DKIM, DMARC) are three TXT entries your DNS provider shows you how to add, and the sender's own page prints the values. What matters more than adding them is checking them, which is what the next guide does: [transactional email landing in spam](/guides/transactional-email-landing-in-spam) reads the `Authentication-Results` header on a copy in the spam folder and tells you which of the three failed, instead of guessing. On BuildBase, domain verification runs through Mailgun regardless of which provider delivers a given sender, so a verified sending domain needs Mailgun connected even if SES delivers the mail. #### The three records, in plain words You do not have to understand the records to add them, but you do have to understand them to read a failure, so here is each in one breath. SPF is a list, published on your domain, of the servers allowed to send mail that claims to come from it. If Mailgun sends your reset code and Mailgun is not on the list, the receiving server has no reason to believe the message is yours. The sender's page tells you the one entry to add, and a domain can carry only one SPF record, so a second sender joins the same record rather than getting its own. DKIM is a signature. The sending server signs each message with a private key, and the public half sits in your DNS so the receiver can check that nothing changed in transit and that the signer was allowed to sign for your domain. It is the long record, and the one most often pasted wrong, so do not mark the step done until the sender's page says it verified. DMARC is the policy that says what to do when the other two fail, and where to send the reports. Start at `p=none`: nothing is rejected, and the reports show you which legitimate mail is failing before you tighten it. The one thing to know is that DMARC also checks that the domain in the From line is the domain the other two records were checked for. That is why a message sent through a sender verified on your domain, with a From address at gmail.com, can pass SPF, pass DKIM and still fail DMARC, and it is the third branch of the spam guide's decision tree. Prompt for it, if the agent is doing the wiring: ```text Connect a sender on mail. for all system email and set it as the organization's default sender. Do not send any email from the agent's own code through Resend, SendGrid or another API; every email goes through the platform's sender. Show me the three DNS records I need to add and which one failed if verification does not pass. ``` What you should see: the domain shows verified in the console, and a test email from the sender arrives at your second address with the From name and the domain you chose. Then open the message's headers and look for `spf=pass`, `dkim=pass` and `dmarc=pass`. Three passes is done; anything else is the spam guide's decision tree. ### 3. Move the default, then test as a stranger Moving the system default to the sender on your verified domain is one call, and it has to happen before you delete anything, because the delete route refuses to remove a sender while it holds the flag: ```bash curl -X PATCH https://api.console.buildbase.app/api/emails/senders/$SENDER_ID/default \ -H "Authorization: $BUILDBASE_TOKEN" ``` The sender's owner can do it, and so can an organization owner or admin. On Supabase, the equivalent is enabling custom SMTP with the new sender's host, port, username and password in the project's Authentication settings; once saved, the built-in sender is no longer used. What you should see: sign up from your second address, at a provider you do not use for work (a Gmail account if you build on Outlook, or the reverse), from a private window, and time the confirmation email. Under a minute, from your domain, in the inbox. Then request a password reset and a magic link and check both come from the same sender. If the confirmation arrives and the reset does not, two senders are in play and the default did not move. **Correcting potential issues.** If the agent "fixed" this by adding an email API call inside the sign-up route, paste: "Remove the email code from the sign-up route. Confirmation, reset and invitation emails are sent by the platform through the default sender; the app sends nothing itself." If a sender shows as verified but mail still fails DMARC, the From domain on the message is not the one that was checked, which is the spam guide's third case. ### 4. The welcome, the trial ending, the card that failed These three emails are the difference between an app and a product, and generated apps never send them because nobody asked. On BuildBase they are workflows rather than code: a trigger on an event the platform already knows about, an email step with a template, published without a deploy, with every run logged per step. The triggers are the platform's own events, and three matter on launch day: - **A sign-up.** The welcome email, with the one thing you want a new person to do first. Keep it to one link. - **`subscription.trial_will_end`.** A heads-up a few days before the trial ends, with a link to the plan screen. This is the single most effective email a subscription product sends. - **`payment.failed`.** The card failed; here is the link to update it. The platform sends this one itself when the console notification or a workflow is on, so the webhook handler in your app is for your own side effects (flag the account, post to Slack), not for the email. In the console's workflow editor those are three triggers and three email steps, each with a template in HTML, Markdown or plain text and merge tags for the person's name and the workspace. Conditions and waits go between steps ("wait three days; if they have not created a project, send the nudge"), and a follow-up stops once the person has done the thing, which is the part a cron job the agent wrote never gets right. More than sixty triggers exist; these three are the ones that pay for themselves in the first month. Here is the trial reminder as it looks in the editor, so that "no code" means something concrete. The trigger is `subscription.trial_will_end`. Step one is a condition on the workspace's subscription, because a customer who already added a card does not need the nudge. Step two is an email to the workspace owner, from your default sender, with a merge tag for the date the trial ends and one button to the plan screen. Step three is a wait of two days, then a second email only if the condition still holds. Every run lists each step with its time and outcome, so "did the reminder go out to Acme" is a search in the console, not a dig through logs. Prompt for the parts that touch the app: ```text Do not write welcome, trial-ending or failed-payment emails in code. I will create them as workflows in the console. In the app, make sure the sign-up, trial and subscription events reach the platform (they do by default through BuildBase sign-in and billing); do not add a cron job, a queue or an email API for these. ``` What you should see: sign up as a stranger and the welcome arrives after the confirmation, from the same domain. Start a trial on a test card, and the reminder is scheduled; the workflow's run log shows the wait step pending. Let the test card fail on renewal and the failed-payment email goes out, and the run log shows it did. If any of those shows nothing, the trigger is not wired, and the log says which one. ### 5. The emails people can turn off, and the one they always can A person should be able to choose which emails they get, and every email that is not required to operate the account should carry a one-click unsubscribe. The sign-in emails (confirmation, reset, magic link) are the account working and always send; everything else is a preference. BuildBase ships the preference screen: a settings page where a user picks which notifications they receive, with one-click unsubscribe and a `List-Unsubscribe` header on campaign mail so mail clients show their own unsubscribe button. [Which notifications users get to turn off](/guides/which-notifications-users-can-turn-off) is the guide to deciding what goes on that screen, and the rule of thumb is short: if a person would be angry to receive it, it is optional; if they would be angry not to, it is required. What you should see: the settings page shows the preference list, turning one off stops that email on the next run of its workflow, and a campaign sent to a list shows an unsubscribe link that works in one click. On Supabase-only apps there is no preference screen until you build one, and the agent's version is usually a boolean column checked by nothing. ### 6. What the email says, and what it should not The last check is the content, and it is the one the spam filters do not catch. A non-developer who built a mental-health app in five weeks and spent three months getting it ready for real users listed, among the things he had to fix, that "booking confirmation emails included the reason for the session". The email worked. It leaked. Three rules that cover most of it. A transactional email says what happened and what to do next, and nothing the person did not type into the email field themselves; a sensitive field belongs behind the sign-in, with a link. The sign-in emails carry a code or a link that expires, and never a password. And a message to a user names the user, not "Dear user", which is both the right thing and a signal the filters read. What you should see: open each of the emails from steps 3 and 4 and ask whether you would be comfortable if it were forwarded. If not, move the detail behind a link. ### Where the builder's own sender wins For a single-user app or a tool for your own team, the sender the builder gives you is fine, and the limits that break it for strangers (team-only delivery, two an hour) are limits you will never hit. Replit and Bolt connect Resend and SendGrid as connectors, v0 connects Resend in one click, and Resend's free plan at 3,000 emails a month covers a small app with no domain of its own for a while. If your app sends one kind of email and you already have a Resend account, connect it and skip the rest. Choose a platform sender with workflows when the emails are the product's behaviour rather than a notification: a trial that ends on its own, a card that fails and a reminder that follows it, a preference screen, campaigns to a list, and a log you can open when a customer says "I never got it". Lovable's Cloud page lists no email at all and points to a separate guide on sending from your own domain; Bolt's and Replit's connectors send, and leave the rest to code. [The launch checklist](/guides/vibe-coded-app-launch-checklist) puts email where it sits among the other nineteen things. > **Key takeaway:** The confirmation email that only you receive is not a bug in the email. It is > a development sender doing exactly what its docs say. Find the sender, put > your domain behind it, move the default, and make the lifecycle emails > workflows you can watch run. ### What breaks, and how you can tell **You get the confirmation, strangers do not.** Step 1: the development sender delivers only to the project's team, and only two messages an hour even then. **The reset code arrives from a personal Gmail address.** Step 3. Somebody connected their own account first, and the system default never moved. **The domain says verified and mail still goes to spam.** Open the copy in the spam folder and read `Authentication-Results`, as the spam guide walks through: SPF or DKIM failing points at a record, and DMARC failing while both pass means the From domain is not the one that was checked. **The welcome arrives, the trial reminder never does.** Step 4. Either the wait step is still pending or the trigger is not wired, and the run log says which. **A user turned off notifications and still gets them.** Step 5. The preference is a column nobody's code reads; the platform's preference screen is the one the workflows honour. **The sender cannot be deleted.** It holds the system default flag. Move the default first. ### Install The sender, the workflows and the preference screen live in the console; the app needs only the SDK and its sign-in routes: ```bash npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## Add login, teams and paid plans to a Lovable app, and keep Lovable Cloud or Supabase for your data > New Lovable apps are TanStack Start apps, which means they can hold the three server routes BuildBase sign-in needs. Built and typechecked on 27 October 2026, with the Supabase wrinkle stated plainly. - Source: https://www.buildbase.app/guides/add-login-teams-and-paid-plans-to-a-lovable-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-27 - Updated: 2026-11-04 ### In short To add login, teams and paid plans to a Lovable app, ask Lovable for the @buildbase/sdk package, add three small server routes that swap the sign-in code for a session cookie, keep the client secret in Lovable Secrets, and leave your data in Lovable Cloud or Supabase. Teams, roles and plans are then SDK calls. You are adding real sign-in, a workspace per customer, paid plans and the email that goes out when a card fails to an app Lovable built for you, without moving your data out of Lovable Cloud or your Supabase project. When it works, a stranger opens your published address in a private window, signs up with Google or a magic link, lands in their own workspace, invites a colleague who gets an email, picks a plan on a test card, and the feature they paid for appears without a reload. The client secret never leaves Lovable's server side. The thing that makes this possible is a change Lovable made in May 2026. New Lovable apps are TanStack Start apps, which render on the server and can hold server routes, instead of React + Vite apps that render only in the browser. A server route is exactly what the sign-in code exchange needs, because it uses a secret the browser must never see. Older Lovable apps are still Vite, and this guide says what to do about that too. What we ran on 27 October 2026: a current TanStack Start app with the official Cloudflare Workers adapter, the shape Lovable's new apps use, scaffolded with `@tanstack/cli` 0.72.0 (TanStack Start 1.169.4, Vite 8.3.5, React 19.3.1), with `@buildbase/sdk` 0.0.90 installed from npm. The three handlers from our Vite guide went in unchanged, as server routes. Typecheck passed, the production build passed, a `wrangler deploy --dry-run` passed, and the three routes answered correctly inside the Workers runtime, in development and in the built Worker, against a stub of our platform. What we have not run: the real hosted sign-in round trip (that needs an organization and a registered redirect address), a browser, a real deploy, or Lovable's own build pipeline. Where that last one matters, this guide says so. > **Before you start:** A Lovable project on a paid plan or the free plan, either stack. A BuildBase > organization, and an auth client created in the console under **User > Management → Authentication**, with its client ID and secret. Your published > Lovable address (and your custom domain, if you have one) registered on that > client as redirect URLs, each ending in `/sign-in`. A Stripe account, only > when you reach plans. > **Tip:** The handlers in this guide are the ones from [BuildBase on > Vite](/guides/buildbase-on-vite), byte for byte. If you are comfortable in a > terminal, that guide and the [admin-dashboard > example](https://github.com/buildbase-app/examples/tree/main/admin-dashboard) > are the tested originals; this page is the Lovable wrapping around them. ### 1. Find out which Lovable app you have Open the **Code** view and look at `package.json`. If it lists `@tanstack/react-start`, you have a TanStack Start app and every step below applies as written. If it does not, you have an older React + Vite app, and you need a server first. Lovable's own docs give that test, and the date behind it: projects created from 13 May 2026 (22 June for Enterprise workspaces) use TanStack Start; earlier ones run on React with Vite and render in the browser. There is no framework choice. Every project uses the same stack, and if you want a different one, Lovable's answer is to continue outside Lovable through Git sync. If yours is Vite, you have two honest routes: - **Ask Lovable to upgrade the project to TanStack Start.** Its upgrade page says anyone who can edit the project can start it on any plan, most upgrades cost 10 to 35 credits, the database is untouched, your published site does not change until you publish the upgraded version, and you can revert from version history. Do that first, test every page (the page warns that some browser-only libraries can break server rendering), then come back to step 2. - **Export to GitHub and host somewhere with serverless functions.** Git sync is two-way and on every plan for github.com; it always creates a new private repository. Then follow the Vite guide on Vercel, Netlify or Cloudflare, where the three handlers are one-line function files. You keep building in Lovable; the sign-in server lives on the host. Why not run the handlers as Lovable Cloud edge functions and stay on Vite? Because the session has to be an httpOnly cookie on your app's own address, and a function on another origin cannot set one there. A server route in the same app can. That is the whole reason TanStack Start matters here. What you should see: either `@tanstack/react-start` in `package.json`, or a decision about which of the two routes above you are taking. ### 2. Register where people come back to The hosted sign-in page sends people back to one exact address per environment, so register them before you prompt: your published Lovable address with `/sign-in` on the end, your custom domain with `/sign-in` if you have one, and `http://localhost:3000/sign-in` if you ever run the exported code locally. An address it was not told about is refused. This is also where the most common Lovable login complaint lives. Lovable's own sign-in docs say that when sign-in works in preview but fails on a published or custom domain, the redirect addresses are the thing to check, and that is true of BuildBase's hosted page as much as of the built-in one. A wildcard can stand in for one leftmost subdomain on a domain you own, but not on a public suffix, so `*.lovable.app` is refused; register each address you actually use. Preview addresses change, so most people register the published one and the custom domain and test sign-in there. What you should see: the auth client in the console lists each address, and the client secret has been shown once. Do not paste it into the Lovable chat. ### 3. Ask Lovable for the package and the three routes You do not install anything. Lovable's docs say to name the package in the project chat, and it adds it to the dependencies; there is no terminal step. Paste this prompt. It names the outcome, the rules, the files, and the one thing that must never happen to the secret. ```text Use the @buildbase/sdk npm package to add BuildBase sign-in, a workspace per customer, paid plans and lifecycle email to this app. Keep Lovable Cloud (or my Supabase project) as the database; BuildBase is not the primary database. Do not add Clerk, Auth0, Resend or n8n. Stripe is bring-your-own; do not store card data. Read https://www.buildbase.app/llms.txt first and do not invent endpoints. Take the three handlers from https://www.buildbase.app/guides/buildbase-on-vite unchanged and run them as TanStack Start server routes: - src/server/auth.ts with the guide's token, session and signout handlers, byte for byte - src/routes/api/auth/token.ts (POST), src/routes/api/auth/session.ts (GET) and src/routes/api/auth/signout.ts (POST): each a createFileRoute with server.handlers that calls the matching handler - src/context/buildbase-provider.tsx from the guide, with import '@buildbase/sdk/css', wrapping in the root route's component in src/routes/__root.tsx Put VITE_BUILDBASE_ORG_ID, VITE_BUILDBASE_CLIENT_ID and VITE_BUILDBASE_REDIRECT_URL in .env. I will add BUILDBASE_CLIENT_SECRET under Secrets myself; never read it in the browser and never give it a VITE_ prefix. If sign-in already exists in this app, stop and ask me before changing it. ``` What you should see: `@buildbase/sdk` in `package.json`, and five new or changed files. The route that matters is the one that swaps the one-time code from the hosted page for a session, and in TanStack Start it is three lines around the Vite guide's handler: ```ts // src/routes/api/auth/token.ts import { createFileRoute } from '@tanstack/react-router'; import { token } from '../../../server/auth'; export const Route = createFileRoute('/api/auth/token')({ server: { handlers: { POST: ({ request }) => token(request) } }, }); ``` `session.ts` is the same shape with `GET: ({ request }) => session(request)`, and `signout.ts` with `POST: () => signout()`. A Start handler receives `{ request, params, context }` rather than a bare `Request`, which is the only reason the wrapper exists; `src/server/auth.ts` is the guide's file. The provider wraps the root route: ```tsx // src/routes/__root.tsx (the component; the html shell stays as Lovable wrote it) import { createRootRoute, Outlet } from '@tanstack/react-router'; import { BuildBaseProvider } from '../context/buildbase-provider'; export const Route = createRootRoute({ // head and shellComponent as Lovable generated them component: () => ( ), }); ``` Two things we checked that you do not have to: the provider renders on the server in its loading state without touching `window`, so server rendering does not break; and the stylesheet import is emitted as a route asset and linked in the server-rendered HTML, so the SDK's screens are styled before the page becomes interactive. **Correcting potential issues.** Read the change before you accept it. The ways Lovable tends to drift, and the line to paste back: - It wrote `createServerFn` functions instead of server routes. Those are for calling from your own pages, not for the three `/api/auth/*` addresses the provider fetches. Paste: "Replace the server functions with file routes under src/routes/api/auth, each exporting a createFileRoute whose server.handlers entry calls the matching handler, as the guide shows." - It put the secret in `.env` as `VITE_BUILDBASE_CLIENT_SECRET`, or read it in the provider. Paste: "BUILDBASE*CLIENT_SECRET is read only inside src/server/auth.ts on the server. Remove every other reference and the VITE* prefix." - It kept, or added, a sign-in of its own next to BuildBase's. Paste: "BuildBase is the only sign-in in this app. Remove the other sign-in pages and the users table for them, and keep every other table." ### 4. Add the secret, and the three public values The secret goes under **More → Settings → Secrets** as `BUILDBASE_CLIENT_SECRET`. Lovable's docs say a secret's value can never be viewed again in Lovable, only replaced or deleted, that it is not repeated in chat, logs or code, and that secrets never reach the browser. That is the right place. The three public values go in `.env`, which Lovable says is where `VITE_`-prefixed, browser-exposed variables belong, and which it asks you not to add to `.gitignore`. ```bash # .env VITE_BUILDBASE_ORG_ID= VITE_BUILDBASE_CLIENT_ID= VITE_BUILDBASE_REDIRECT_URL=https://your-app.lovable.app/sign-in # VITE_BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` Here is the part we could not confirm from Lovable's docs, so you have to: the secrets page says secrets are injected into edge functions and server-side integrations at runtime, and the external-hosting page says server-function secrets are set on the host. Neither names a TanStack Start server route. In our test the Workers runtime exposed the secret to the route as `process.env.BUILDBASE_CLIENT_SECRET` because the Worker had `nodejs_compat` on. Step 5 tells you whether Lovable's Worker does the same: a sign-in that fails with "Sign-in failed" on a correct code means the secret did not reach the route. One more detail from the test. The provider reads the three public values with `import.meta.env`, which Vite inlines at build time, and the handlers read the same three names with `process.env` at request time. In a Worker that means the values have to exist as runtime variables too, not only in the build. If step 5 fails with a missing org id, the fix-up is below. What you should see: after publishing, open `https://your-app.lovable.app/api/auth/session` and get `{"sessionId":null}`. The server half is alive before any button exists. If you get the app's HTML back instead, the routes are not there, and either the prompt did not land or this is still a Vite project. **Correcting potential issues.** If the server route cannot see `process.env` at all, or reads the public values as empty, paste: "In src/server/auth.ts, read VITE_BUILDBASE_ORG_ID, VITE_BUILDBASE_CLIENT_ID and VITE_BUILDBASE_SERVER_URL with import.meta.env, and read BUILDBASE_CLIENT_SECRET from the Worker's env binding; keep every read inside the handler, never at module scope." ### 5. Publish, then sign in from a private window Publish. Open the published address in a private window, click the button that calls `signIn()` from `useSaaSAuth()`, and you are sent to the hosted sign-in page, which offers whichever methods you switched on in the console. Sign up with a second email. You come back to `/sign-in` on your app, signed in. Then the two checks a demo skips. Close the browser, reopen the site: still signed in, because the cookie is good for 30 days, which is the [default session length](/guides/token-expired-mid-request). Sign out, then reload: asked to sign in again, because sign-out ended the session on the server rather than clearing a value in the browser. In our test the session cookie came back with `Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000`, and sign-out answered with `Max-Age=0`. The guide names it `bb-session-id`, as `npx buildbase init` does. The methods are switches, not code: email and password, a magic link, an email code, a phone sign-in code sent through your own Twilio account, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, and Ethereum or Solana wallets. Turning on Google means creating the client in Google's console and pasting two values; nothing in the Lovable app changes. **Correcting potential issues.** "The redirect address is not allowed" on the hosted page: the address in `VITE_BUILDBASE_REDIRECT_URL` and the one registered on the client differ, usually by a trailing slash, `www`, or the `/sign-in` path. "Sign-in failed" after a correct code: the secret did not reach the server route; check the Secrets panel, and if it is there, use the env-binding fix-up in step 4. Lovable's own 50-address limit applies to its built-in sign-in, not to this one. ### 6. A workspace per customer, and the colleague they invite Every new user lands in their own workspace on first sign-in, with no setup step. That is on by default for new organizations, and in your app it is one component for the switcher and the hooks the SDK already has. Prompt Lovable for the screens; the data model is already there. ```text Add a workspace switcher to the app header using useSaaSWorkspaces() from @buildbase/sdk/react, and a /settings page that opens the SDK's built-in workspace, members and billing screens. Members with the admin role may invite teammates by email; everyone else sees the member list read-only. Do not create workspace, membership or role tables in Lovable Cloud or Supabase; BuildBase holds them. ``` What you should see: a switcher listing the workspaces the signed-in person belongs to, with **Add team** creating another if you allow it. On the members screen, inviting an address that has no account yet sends an email with a link; the person signs up and lands in the workspace with the role you chose. That flow has been in the SDK since version 0.0.71, and the reasons an invite can be refused (a seat limit, an outsider policy) come back as named errors rather than silence. Why not let Lovable write the tables? Because every audit of a vibe-coded app finds the same bug: a role column checked on one page and nowhere else. Lovable's own end-user sign-in docs describe no roles, teams or workspaces for the people using your app, so whatever a prompt builds here is built from scratch. The SDK's roles are enforced by the API, so a member who types the address of an admin page gets refused by the server, not just a missing menu item. **Correcting potential issues.** If a member can see another workspace's rows by changing an id in the address bar, Lovable wrote a page that reads your database without scoping it. That is your data and your query, and the next section is about it. ### 7. Your data stays where it is: the one honest wrinkle Your tables stay in Lovable Cloud or in your Supabase project. The rule we give every agent is "do not use BuildBase as the primary database", and it applies here. The wrinkle is row-level security: policies keyed to the old sign-in (`auth.uid()` and friends) do not know who a BuildBase user is, because a BuildBase session is an opaque id, not a token Supabase can read. There are two ways through, and most apps want the first. **Read and write through server routes.** A server route or server function checks the BuildBase session and queries your database with a server-side credential, scoped by the BuildBase user or workspace id. This is the pattern generated apps should use anyway, because it puts the permission check where it cannot be forged. The server SDK makes the check one call: ```ts // src/server/buildbase.ts import BuildBase from '@buildbase/sdk'; import { getCookie } from '@tanstack/react-start/server'; // The Vite guide's cookie: bb-session-id, or bb-session-id- when // VITE_BUILDBASE_ENVIRONMENT names a development or staging environment. export async function getSessionId() { return getCookie('bb-session-id') ?? null; } let client: ReturnType | undefined; export function bb() { client ??= BuildBase({ serverUrl: process.env.VITE_BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app', orgId: process.env.VITE_BUILDBASE_ORG_ID!, getSessionId, }); return client; } ``` In our test a `/profile` route's server function called `bb().users.getProfile()` with that cookie, the call reached the platform, and a missing session redirected home. One note from the typecheck: TanStack Start refuses to send a value it cannot serialise out of a server function, and the SDK's user type carries free-form claims, so return the fields the page needs (`{ email }`) rather than the whole user. **Mint a Supabase-shaped token for browser queries.** If pages query Supabase directly from the browser and you want the existing policies to keep working, add one more server route: it validates the session with the server SDK, then signs a short-lived HS256 token with your Supabase project's JWT secret (kept in Secrets), with `sub` set to the BuildBase user id and `role` and `aud` set to `authenticated`, and the browser passes it to Supabase as the bearer token. `auth.uid()` then matches `sub`, so store the BuildBase user id in your owner columns. The step-by-step is in [the skill repository](https://github.com/buildbase-app/claude-skill/blob/main/distribution/supabase-jwt.md). You own that route and its refresh schedule. The platform change that would make it unnecessary, BuildBase publishing signing keys so Supabase can verify a user token directly, is recorded as not built. Lovable's Quick scan still runs on every publish and still checks that tables have row rules; nothing here switches it off, and the Deep scan is worth running once after a change this size. ### 8. Plans people can pay for, and the email when a card fails Plans, prices and trials live in the BuildBase console and sync to your own Stripe account at Stripe's rates, with a 0% platform fee, and no card data touches your app. The part that generated apps get wrong is what happens after the payment, so this step is mostly about the webhook route and the feature flag. In the console, create two plans, Launch and Pro, say, each with a 7-day trial and a monthly and a yearly price. Then the webhook. It is a fourth server route, and this is the prompt for it: ```text Add src/routes/api/webhooks/buildbase.ts as a POST server route. Verify the signature with parseWebhookEvent from @buildbase/sdk on the raw request body, using BUILDBASE_WEBHOOK_SECRET from Secrets. Handle payment.failed with our own side effects only (flag the workspace, post to Slack); the platform emails the customer itself, but only once I have connected an email sender and switched on the Payment Failed notification event in the console. Ignore other events. Gate the export feature behind a BuildBase feature flag tied to the Pro plan, checked in a server route. Do not store the plan in Lovable Cloud or Supabase. ``` Point an endpoint in the console at `https://your-app.lovable.app/api/webhooks/buildbase`, add its signing secret under Secrets as `BUILDBASE_WEBHOOK_SECRET`, and publish. What you should see: subscribe on a test card and the Pro feature appears without a reload, because the flag follows the workspace's plan. Let the test card fail on renewal and the email goes out from your sending domain, because `payment.failed` is one of the 129 events in the catalog and the console's notification or a workflow sends it; the route in your app is for whatever you want to happen besides. The console's delivery log shows each attempt, and a delivery your server was down for is retried up to five times over about two and a half minutes. Compare that with the built-in payments, read on 27 October 2026 from Lovable's docs: Paddle at 5.0% plus 50 cents per transaction (a flat 10% under $10) or your own Stripe at Stripe's rates, on Pro and up; one active subscription per user by default, one provider per project, and once payments are on, the project cannot be forked. Trials, discount codes and monthly or yearly prices are there. Usage-based billing, seats and credits are not mentioned, and neither is a plan per team. If your app sells one subscription to one person, the built-in is simpler. If a plan belongs to a workspace and has to change what the app does, [entitlements rather than flags](/blog/entitlements-are-not-feature-flags) is the ten-minute read before you prompt. ### Where Lovable's built-in is the better pick Keep Lovable's built-in sign-in when your app has one user per account and you need nothing after login. It is zero-config inside Lovable, which an external SDK will never be, it ships SAML SSO and OIDC, which BuildBase does not, so a buyer who signs in with Okta is better served by it, and its redirect addresses are managed for you on the built-in backend. Keep the built-in payments when you sell one subscription per person and want the tax side handled, which is Paddle's own pitch for it. Choose BuildBase when the question is "what may this team do now that they paid": a workspace per customer, invites and roles enforced by the API, plans with versions, feature flags tied to the plan, credits with a hard stop, and the lifecycle email, from one SDK, with your data staying in Lovable Cloud. That is the layer Lovable's docs do not reach today, and [the launch checklist](/guides/vibe-coded-app-launch-checklist) is the twenty-item version of why it matters before strangers arrive. > **Key takeaway:** On Lovable the hard part was never the SDK, it was having a server. New > Lovable apps have one. Three server routes, a secret in Secrets, and the rest > is hooks, with your database exactly where it was. ### What this costs in credits Lovable prices builds by the request. Its own pricing page gives examples: 0.50 credits to make a button grey, 1.20 to add authentication, 1.70 or so for a landing page with images, and 1 credit per message in plan mode. Pro is $25 a month for 100 credits ($21 on annual billing) and Business $50 for 100, with daily build credits on top; an upgrade from Vite to TanStack Start is 10 to 35. All read on 27 October 2026, and Lovable changes these. The prompt in step 3 is one request, with perhaps two fix-ups. Steps 6 and 8 are one each. The expensive thing on Lovable is not a feature, it is a loop: about 63% of the negative reviews we read across the builders were about credits spent on fixes that did not fix. Naming the exact files, the exact env names and the exact guide is how you avoid the loop, and it is why this page is long. BuildBase's side: a Free plan at $0, then Launch at $19 a month, with a 7-day trial and no card on the paid plans. ### What breaks, and how you can tell **Sign-in works in preview and loops after publishing.** The published address, or the custom domain, is not registered with `/sign-in` on the end. Register each exact address; `*.lovable.app` is refused. **"Sign-in failed" on a correct code.** The secret did not reach the server route. Check Secrets, then use the env-binding fix-up in step 4. **`/api/auth/session` returns the app's HTML.** There are no server routes, because the project is still React + Vite, or the prompt wrote server functions instead. Step 1, then step 3's first fix-up. **The org id is empty on the server.** The handlers read `process.env` at request time and the Worker only has the values from the build. Read the three public values with `import.meta.env` in `src/server/auth.ts`. **The secret is in the browser.** Search the published JavaScript for its first characters. If it is there, it was prefixed `VITE_`. Rotate it in the console, move it to Secrets, publish again. **Rows vanish, or "permission denied", after switching sign-in.** Row rules keyed to the old sign-in no longer match. Section 7: route the reads through the server, or mint the token. **The package install breaks the build.** Lovable's docs say it cannot guarantee third-party packages. The SDK's dependencies are plain JavaScript with no native code, which is the usual cause of a broken install, so read the build error before assuming the package; and keep `bun.lock` in place, because Lovable installs with Bun. ### Install In Lovable, the install is a sentence in the chat: "Use the @buildbase/sdk npm package". On an exported copy, Lovable's docs say to install with Bun so the lockfile stays in sync (`bun add @buildbase/sdk`), and on any other host it is the usual line: ```bash npm i @buildbase/sdk ``` --- ## Add sign-in, teams and paid plans to a v0 app without leaving Next.js > A v0 app is a Next.js app, which is the easiest place to add BuildBase: one prompt or one init command, five variables in Vercel, one redirect address, then teams, plans and the failed-payment email. - Source: https://www.buildbase.app/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-27 - Updated: 2026-11-04 ### In short To add sign-in, teams and paid plans to a v0 app, keep it a Next.js app and add BuildBase: paste one prompt in v0, or run npx buildbase init on the repo v0 keeps in GitHub. Put five variables in Vercel with the secret server-only, register your domain as the redirect address, and teams, plans and email are SDK calls. You are adding real sign-in, a workspace per customer, paid plans and the email that goes out when a card fails to an app v0 generated for you. When it works, a stranger opens your production domain in a private window, signs up with Google or a magic link, lands in their own workspace, invites a colleague, picks a plan on a test card, and the feature they paid for appears without a reload. All of it is in your repository, and none of the secrets are in the browser. v0 is the easiest builder to do this on, for one reason: every v0 app is a Next.js app with the App Router, and Next.js is where our SDK has the most road under it. The same ten files that `npx buildbase init` writes into any Next.js app are the files v0 will write if you hand it the right prompt. What we ran on 27 October 2026: `npx buildbase init` in a fresh Next.js App Router app, then typecheck and `next build`, through the CLI's own gates (a 60-cell matrix of project shapes, platform builds in seven frameworks, and a 59-assertion end-to-end run against a stub server). What we have not run today is this exact flow inside v0's own chat, so where a step says "you should see", that is what Next.js and v0's documented behaviour give you, and the one place v0's behaviour matters is called out. > **Before you start:** A v0 project, connected to GitHub and to a Vercel project (v0's docs say that > is what gets you environment variables, deployments and previews). A BuildBase > organization, and an auth client created in the console under **User > Management → Authentication**, with its client ID and secret. Your production > domain registered on that client as a redirect URL, and > `http://localhost:3000` beside it. A Stripe account, only when you reach > plans. > **Tip:** Already have a Next.js app with a `with-buildbase` shape? The [Next.js > guide](/guides/buildbase-on-nextjs) is the tested version of every snippet > below, and this page is the v0-specific wrapping around it: which prompt, > where the variables go, and what v0 does with the branch. ### 1. Decide where people come back to The hosted sign-in page sends people back to one exact address you registered, so decide it before you prompt: your production domain for the live app and `http://localhost:3000` for local work. Register both on the auth client. Everything that goes wrong later with "login loops" traces back to this address. Why one address? Because the sign-in happens on a page BuildBase hosts (on your own domain, if you set that up later), and that page needs to know the only places it is allowed to send a signed-in person. An address it was not told about is refused, which is the right behaviour and the most common first-day surprise. v0 adds a wrinkle: it deploys to Vercel, and Vercel gives every deployment a preview address on `vercel.app`. A wildcard can stand in for one leftmost subdomain on a domain you own, but not on a public suffix, so `*.vercel.app` is refused. If you want to test sign-in on a preview deployment, register that preview's exact address. Most people register production and localhost and test sign-in there. What you should see: in the console, the auth client lists two redirect URLs, and the client secret is shown once. Copy it somewhere you will not paste into a chat. ### 2. Paste the prompt into v0 Paste this into the v0 chat for your project. It names the outcome, the rules, the guide v0 should follow, and the one thing that must never happen to the secret. ```text Add BuildBase (@buildbase/sdk) to this Next.js app for sign-in, a workspace per customer, paid plans and lifecycle email. Follow https://www.buildbase.app/guides/buildbase-on-nextjs exactly, and read https://www.buildbase.app/llms.txt first. Do not invent endpoints. Keep the existing database. Do not add Clerk, Auth0, Better Auth, Resend or n8n. Stripe is bring-your-own; do not store card data. Write app/providers.tsx, app/api/auth/token/route.ts, app/api/auth/session/route.ts, app/api/auth/signout/route.ts, lib/buildbase.ts and app/api/webhooks/buildbase/route.ts, and wrap app/layout.tsx in the provider. Read NEXT_PUBLIC_BUILDBASE_ORG_ID, NEXT_PUBLIC_BUILDBASE_CLIENT_ID and NEXT_PUBLIC_BUILDBASE_REDIRECT_URL in the browser; read BUILDBASE_CLIENT_SECRET and BUILDBASE_WEBHOOK_SECRET only in route handlers, never with a NEXT_PUBLIC_ prefix. Leave every secret empty in .env.example. If sign-in already exists in this app, stop and ask me before changing it. ``` What you should see: v0 creates a working branch (its docs say it never pushes to your base branch; it opens or reuses a pull request when you publish), and the branch contains those six files plus an edited `app/layout.tsx`. The provider should look like this, which is the tested shape from the Next.js guide, trimmed: ```tsx // app/providers.tsx 'use client'; import '@buildbase/sdk/css'; import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; export function Providers({ children }: { children: React.ReactNode }) { return ( (await (await fetch('/api/auth/session')).json()).sessionId, handleAuthentication: async (code: string) => { const res = await fetch('/api/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); return { sessionId: (await res.json()).sessionId }; }, onSignOut: async () => { await fetch('/api/auth/signout', { method: 'POST' }); }, }, }} > {children} ); } ``` And the route that matters, the one that swaps the one-time code from the hosted page for a session and puts it in a cookie the browser cannot read: ```ts // app/api/auth/token/route.ts import { NextResponse } from 'next/server'; export async function POST(request: Request) { const { code } = await request.json(); const res = await fetch( `${process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app'}/api/v1/auth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, orgId: process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID, clientId: process.env.NEXT_PUBLIC_BUILDBASE_CLIENT_ID, clientSecret: process.env.BUILDBASE_CLIENT_SECRET, }), } ); if (!res.ok) return NextResponse.json({ error: 'Sign-in failed' }, { status: 401 }); const { data } = await res.json(); const response = NextResponse.json({ sessionId: data.sessionId }); // The name `npx buildbase init` writes; with NEXT_PUBLIC_BUILDBASE_ENVIRONMENT // set to a development or staging key it is bb-session-id-. response.cookies.set('bb-session-id', data.sessionId, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 60 * 60 * 24 * 30, }); return response; } ``` The session route returns that cookie's value so the app can restore itself after a refresh; the sign-out route deletes it. Both are a handful of lines in the [with-buildbase example](https://github.com/buildbase-app/examples/tree/main/with-buildbase/app/api/auth). **Correcting potential issues.** Read the diff before you accept it. The three ways v0 tends to drift, and the line to paste back: - It added `better-auth`, `@clerk/nextjs` or `next-auth` anyway. Paste: "Remove that package. BuildBase is the only sign-in in this app. Keep the users in my existing database." - It put the secret in a `NEXT_PUBLIC_` variable, or read it in a client component. Paste: "BUILDBASE*CLIENT_SECRET must be read only in app/api/auth/token/route.ts. Remove every other reference and never prefix it with NEXT_PUBLIC*." - It created `BuildBase(...)` at the top of `lib/buildbase.ts` instead of inside a function. That breaks `next build` on any machine where the variables are not filled in yet. Paste: "In lib/buildbase.ts, create the server client lazily inside a bb() function, as the guide shows." ### 3. Set five variables in Vercel Four public values and one secret go in the Vercel project's environment variables, not in a file v0 commits. v0's docs say environment variables are managed in Vercel (Project menu → Settings → Environment Variables) and that previews run the full application with them, so the route handlers see the secret on every deployment and the browser never does. ```bash NEXT_PUBLIC_BUILDBASE_ORG_ID= NEXT_PUBLIC_BUILDBASE_CLIENT_ID= NEXT_PUBLIC_BUILDBASE_REDIRECT_URL=https://your-domain.com BUILDBASE_CLIENT_SECRET= BUILDBASE_WEBHOOK_SECRET= # NEXT_PUBLIC_BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` The rule behind the split is the same one every Next.js app lives under: anything prefixed `NEXT_PUBLIC_` is inlined into the browser bundle. That is fine for an organization id and a client id, which are public by design, and fatal for a secret. So the secret has no prefix, and only `app/api/auth/token/route.ts` reads it. Redeploy. What you should see: open `https://your-domain.com/api/auth/session` and get `{"sessionId":null}`. The server half is alive before any button exists. If you get HTML back instead, the route is not deployed, and the diff in step 2 did not land on the branch Vercel built. ### 4. Sign in from a private window Open the production domain in a private window, click the button that calls `signIn()` from `useSaaSAuth()`, and you are sent to the hosted sign-in page, which offers whichever methods you switched on in the console. Sign up with a second email. You come back to the registered address signed in. Then do the two checks a demo skips. Close the browser, reopen the site: still signed in, because the cookie is good for 30 days, which is the [default session length](/guides/token-expired-mid-request). Sign out, then reload: asked to sign in again, because sign-out ended the session on the server rather than clearing a value in the browser. The methods are switches, not code. Email and password, a magic link, an email code, a phone sign-in code sent through your own Twilio account, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, and Ethereum or Solana wallets. Turning on [Google sign-in](/guides/social-login-nextjs) means creating the client in Google's console and pasting two values; nothing in the v0 app changes. **Correcting potential issues.** If the hosted page says the redirect address is not allowed, the address in `NEXT_PUBLIC_BUILDBASE_REDIRECT_URL` and the one registered on the client differ, usually by a trailing slash or `www`. They must match exactly. If you are testing on a preview deployment, see step 1: register that preview's exact address or test on production. ### 5. A workspace per customer, and the colleague they invite Every new user lands in their own workspace on first sign-in, with no setup step. That is on by default for new organizations, and in your app it is one component for the switcher and the hooks the SDK already has. Prompt v0 for the screens; the data model is already there. ```text Add a workspace switcher to the app header using useSaaSWorkspaces() from @buildbase/sdk/react, and a /settings page that opens the SDK's built-in workspace, members and billing screens. Members with the admin role may invite teammates by email; everyone else sees the member list read-only. Do not create workspace, membership or role tables in my database; BuildBase holds them. ``` What you should see: a switcher listing the workspaces the signed-in person belongs to, with **Add team** creating another if you allow it. On the members screen, inviting an address that has no account yet sends an email with a link; the person signs up and lands in the workspace with the role you chose. That invitation flow is in the SDK since version 0.0.71, and the reasons an invite can be refused (a seat limit, an outsider policy) come back as named errors rather than a silent nothing. Why not let v0 write the tables? Because the audits of vibe-coded apps all find the same bug: a role column checked on one page and nowhere else. The SDK's roles are enforced by the API, so a member who types the address of an admin page gets refused by the server, not just a missing menu item. [Roles and permissions per workspace](/guides/roles-and-permissions-per-workspace-nextjs) goes deeper when you want permissions of your own. **Correcting potential issues.** If a member can see a second workspace's data by changing an id in the address bar, v0 wrote a page that reads your database without scoping it to the current workspace. Paste: "Every query in this page must be scoped to the current workspace id from useSaaSWorkspaces(); refuse the request on the server if the user is not a member." That is your database and your query, and no SDK can scope it for you. ### 6. Plans people can pay for, and the email when a card fails Plans, prices and trials live in the console and sync to your own Stripe account; the platform fee is 0%, and no card data touches your app. The part generated apps get wrong is what happens after the payment, so this step is mostly about the webhook route and the feature flag. First the catalog, in the console: a Launch plan and a Pro plan, say, with a 7-day trial on both and a monthly and a yearly price. Then the webhook. `init` writes `app/api/webhooks/buildbase/route.ts`, and the prompt in step 2 asked v0 for the same file. It verifies the signature with `parseWebhookEvent` on the raw body and handles events from the published catalog, 129 of them, by name: ```text In app/api/webhooks/buildbase/route.ts, handle payment.failed with our own side effects only (flag the workspace, post to Slack); the platform emails the customer itself, but only once I have connected an email sender and switched on the Payment Failed notification event in the console. Handle subscription.created by nothing; the plan is already on the workspace. Gate the export feature behind a BuildBase feature flag tied to the Pro plan, checked on the server. Do not store the plan in my database. ``` Point an endpoint in the console at `https://your-domain.com/api/webhooks/buildbase`, copy its signing secret into `BUILDBASE_WEBHOOK_SECRET` in Vercel, and redeploy. What you should see: subscribe on a test card and the Pro feature appears without a reload, because the flag follows the workspace's plan. Let the test card fail on renewal and the email goes out, from your sending domain, because `payment.failed` is a real event the console's notification or a workflow acts on, rather than a Stripe event the app guessed at; the route in your app is for whatever you want to happen besides. In the console, the webhook's delivery log shows each attempt, and a delivery your server was down for is retried up to five times over about two and a half minutes. Two pieces worth ten minutes before you prompt for them. A plan change creates a new version rather than editing the old one, so nobody is moved to a new price without you choosing to move them; [plan versioning](/guides/plan-versioning-nextjs) explains why that matters on the day you raise prices. And the difference between [entitlements and feature flags](/blog/entitlements-are-not-feature-flags) decides whether "paid" means "sees the button" or "may call the endpoint". You want the second. **Correcting potential issues.** If v0 wrote a Stripe webhook handling `invoice.payment_failed` directly, it built the billing a second time. Paste: "Remove the direct Stripe webhook. BuildBase receives Stripe's events; my app receives BuildBase's. Handle payment.failed in app/api/webhooks/buildbase/route.ts only." If the feature check lives in a client component, paste: "Check the feature flag on the server in the route that performs the export, not in the component that shows the button." ### The other path: init on the repository v0 keeps v0 keeps your code in a GitHub repository it created (or one you imported), and that repository is the source of truth. If you ever open a terminal, the fastest version of steps 2 and 3 is two commands on a clone of it: ```bash npm install @buildbase/sdk npx buildbase init --org-id ``` It reads `package.json`, sees Next.js, and writes ten files: the provider, the three sign-in routes, the webhook route, the server helper, `.env.example` and `.env.local`, and it wraps `app/layout.tsx`. Four things it will not do: overwrite a file that exists, write a secret (every value is left empty, and it refuses a secret passed on the command line), touch a Pages Router app (refused, with a message), or change anything on a second run (it prints `already configured`). Push the branch and open the pull request; when it merges, v0's docs say it synchronizes the chat with the base branch, so the next prompt sees the files. Then set the variables in Vercel exactly as in step 3. What we have not done is run `init` from inside v0, because v0's chat is not a terminal. In our own agent evaluation, agents read about `init` and wrote the files by hand instead, because `init` needs the organization id and they had none. If you have the id, `init` is the shorter road. ### Where v0's own options are the better pick If all you need is sign-in and you like owning code, Better Auth is the honest default on v0: Vercel bought it in July 2026, it is open source under MIT with 4.7 million weekly downloads, and it is the library an agent on Vercel's platform is most likely to reach for. Clerk has been one click from the v0 chat since 9 September 2026 and Auth0 since the week after, and v0 loads a provider's skills automatically when its integration is installed, so they are wired with less prompting than BuildBase, which is not a Marketplace integration today and needs the links in the prompt above. Pick one of those when your app has one user per account and the plan lives in Stripe alone. Pick BuildBase when the question is "what may this team do now that they paid", because that is the part none of the three documents for your end users: a workspace per customer, invites and roles enforced by the API, plans with versions, feature flags tied to the plan, credits with a hard stop, and the lifecycle email, from one SDK. The [Clerk comparison](/compare/clerk-vs-buildbase) is the line-by-line version. > **Key takeaway:** On v0 the hard part is not the framework, it is the prompt. Name the guide, > name the files, name where the secret may be read, and v0 writes what init > would have written. After that, teams and plans are hooks, and [the launch > checklist](/guides/vibe-coded-app-launch-checklist) is what to run before you > share the link. ### What breaks, and how you can tell **Sign-in works on production and loops on a preview deployment.** The preview's `vercel.app` address is not registered, and a wildcard on a public suffix is refused. Register the exact address or test on production. **`next build` fails on Vercel with "orgId is required".** `BuildBase(...)` is being created at module level in `lib/buildbase.ts`, before the environment variables exist on the build machine. Create it inside a function on first use, as the Next.js guide shows. **The secret is in the browser.** Search the deployed JavaScript for the first characters of the client secret. If it is there, a variable was prefixed `NEXT_PUBLIC_` or read in a client component. Rotate the secret in the console, fix the prefix, redeploy. **Paid, but the feature did not appear.** The webhook endpoint in the console points at the wrong address, or `BUILDBASE_WEBHOOK_SECRET` is empty on Vercel. The delivery log in the console shows each attempt and its status; a 401 there means the secret, a timeout means the route. **A member sees another team's data.** The page queries your database without the workspace id. The SDK scopes what it holds; your tables are yours to scope, and the fix is in the query, not in the SDK. **`init` refuses the app.** It is a Pages Router project. v0 generates the App Router, so this only happens on an imported repository; the Next.js guide's steps work by hand on either. ### Install Add the SDK to the repository v0 keeps, or paste the prompt in step 2 and let v0 write the same files: ```bash npm i @buildbase/sdk ``` --- ## Login that works after you publish: the live-site checklist for a vibe-coded app > Sign-in works in the preview and loops, lands on localhost or hangs on the live site. Six checks, in the order a stranger hits them, with the exact error strings and the setting behind each one. - Source: https://www.buildbase.app/guides/login-that-works-after-you-publish - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-27 - Updated: 2026-11-04 ### In short Login that works in the preview and fails on the published site comes down to an address: the sign-in provider only returns to URLs it was told about, and the live one was never added. Six checks in order: the redirect address, the Google client, the confirmation email, the session, sign-out, a second browser. A Replit review from 17 October 2026 reads, in full: "Users can't log in." A paid-fix vendor advertises on Mastodon with the exact symptom: "lovable login works in preview, then loops or dumps you on localhost after publish?" And on dev.to, the largest troubleshooting cluster we found for any builder, ten posts in thirty days, is Lovable sign-in that works for the builder and fails for everyone else. It is nearly always the same thing. Sign-in happens on a page somebody else hosts (Supabase, Lovable Cloud, Bolt Cloud, Google, BuildBase's hosted page), and that page only sends people back to addresses it has been told about. The preview address was told about. The published one, and the custom domain you added on Friday, were not. Nothing in the app is broken, which is why no amount of prompting fixes it, and why a loop of fixes is how the credits go. This is a checklist, not a tutorial: six checks in the order a stranger hits them, each with the symptom, the error string if there is one, the setting behind it, and how to prove it is fixed. Run every one on the **published** site, in a private window, as a second person, never as yourself in the editor's preview. The settings and limits quoted were read from each vendor's own docs on 27 October 2026. > **Before you start:** A published app with a sign-in of any kind (the builder's built-in, your own > Supabase project, or BuildBase), a second email address you control, and a > second browser or a private window. For the Google check, access to the Google > Cloud Console project that holds the OAuth client. ### First, find out who does your sign-in Before any check, name the thing that signs people in, because every setting below lives in a different place depending on the answer. Most builders have given you one of four: | Who signs people in | How to tell | Where the allow list lives | | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | The builder's built-in backend (Lovable Cloud, Bolt Cloud, Replit Auth) | The Users list is inside the builder, and you never created a Supabase or BuildBase account for this app | The builder's own auth settings; Lovable and Bolt manage most of it when you publish | | Your own Supabase project | There is a Supabase dashboard for this app and the code calls `supabase.auth` | Supabase, Authentication, URL Configuration: the Site URL and the Redirect URLs | | BuildBase's hosted page | The code has a `SaaSOSProvider`, three `/api/auth/*` routes and a `bb-session-id` cookie | The auth client in the BuildBase console, under User Management, Authentication | | Something the agent wrote itself | A `users` table, a password hash, a `jsonwebtoken` or `iron-session` dependency | Nowhere; the redirect is whatever the code does, and the code is the setting | The fourth row is the one to worry about. There is no allow list because the agent wrote its own sign-in, and the checks below still apply, but the "setting" is a line of code the agent chose. [What a coding agent builds when nobody tells it otherwise](/blog/what-a-coding-agent-builds-when-nobody-tells-it-otherwise) is what that line usually looks like. ### 1. The redirect address: where sign-in sends people back Symptom: sign-in works in the preview; on the live site it loops back to the sign-in page, lands on `localhost:3000`, or shows "redirect URL not allowed". Cause: the live address is not on the provider's allow list, so the provider falls back to its default, which is the preview or localhost. A published app has more addresses than it looks. Lovable gives you a preview address, a published `something.lovable.app` address, and your custom domain if you added one; v0 and Vercel give you a preview address per deployment and a production domain; Bolt gives you a Netlify address and your domain. Each is a different string to the provider, and an allow list that holds one of them holds one of them. Register the published address and the custom domain as a matter of course, and the preview only if you test sign-in there. The settings, by provider: **Supabase (your own project, or the one a builder created for you).** The Site URL is the default redirect when no `redirectTo` is given, and the docs tell you to change it "from `http://localhost:3000` to your production URL". Redirect URLs live on the URL Configuration page; the `redirectTo` your code passes must match that list. Wildcards exist (`*` matches within one path segment, `**` across them), and the docs keep them for local and preview work: "we recommend setting the exact redirect URL path for your site URL in production". **Lovable Cloud.** The built-in sign-in allows up to 50 redirect addresses per app. If the app uses your own Supabase project instead, Lovable's sign-in docs say it does not update that project's Site URL or redirect URLs for you; you add the published address and the custom domain in the Supabase dashboard yourself. **Bolt Cloud.** Bolt's auth settings carry a Site URL ("the primary live URL of your app") and a URI allow list; new projects default to `localhost:3000`, which the docs say "does not work for live applications". Bolt usually updates these when you publish, and the docs add that you may need to edit them by hand, "especially with multiple domains". **BuildBase.** Each auth client has a list of redirect URLs, and the hosted sign-in page returns only to one of them, path included. A wildcard can stand in for one leftmost subdomain on a domain you own (`https://*.app.example.com/sign-in`), and never on a public suffix, so `*.lovable.app` and `*.vercel.app` are refused. Register the published address, the custom domain, and `localhost` for local work, each once. [Auth clients, redirect URLs and environments](/guides/auth-clients-redirect-urls-and-environments) is the pattern for keeping preview, staging and production apart without sharing a client. How to prove it: open the published site in a private window, start sign-in, and read the address bar when it fails. If it says `localhost`, the Site URL is the default. If it says "not allowed" or "mismatch", the address differs from the registered one by a trailing slash, `www`, `http` versus `https`, or the path. Fix the one character, and try again from a fresh private window, because the old one may have cached the failure. The four ways an address differs, because every one of them has cost someone an afternoon: `https://app.example.com/sign-in` is not `https://app.example.com/sign-in/` (the slash), not `https://www.app.example.com/sign-in` (the `www`), not `http://app.example.com/sign-in` (the scheme), and not `https://app.example.com/` (the path). Allow lists compare strings, not intentions. If you want the agent to do the registering, give it the strings rather than the job, because an agent asked to "fix login on the live site" will change code, and the code was never wrong: ```text Do not change any sign-in code. In the sign-in provider's settings, set the Site URL to https:// and add these redirect URLs exactly, with no wildcard: https:///sign-in, https:///sign-in, http://localhost:3000/sign-in. Then tell me which settings page you changed and what it now contains. ``` **Correcting potential issues.** If the agent answers by editing the sign-in code anyway, paste: "Revert that change. The problem is the provider's allow list, not the code; show me the current Site URL and redirect list before changing anything else." On a builder that manages the list for you (Lovable Cloud, Bolt Cloud), publishing again after adding a custom domain is often the whole fix, because the builder updates the list on publish; Bolt's docs say exactly that, with the caveat about multiple domains. ### 2. The Google client: `redirect_uri_mismatch` Symptom: the Google button opens Google's page, which shows "Error 400: redirect_uri_mismatch", or returns to the app with nothing signed in. Cause: the address Google was asked to return to is not one of the authorized redirect URIs on your OAuth client, exactly. This one has a second allow list, and it is Google's, not your provider's. Whoever handles the sign-in (Supabase, Bolt Cloud, BuildBase) has one callback address that Google must know; Bolt's docs, for example, show the origin and redirect URIs to paste into Google Cloud Console when you turn Google on. That address does not change when you publish, which is why this check passes for most people. It fails when the client was created for a different provider, when a second provider was added later, or when someone pasted the app's address instead of the provider's callback. The Figma Make community thread that opened on 22 July 2025, "Google signup works but no access to app", stayed open into September with no root cause given; the symptom in it is this check and the one before it together: Google succeeded, then the provider returned to an address the app did not expect. How to prove it: read the `redirect_uri` in Google's error page, copy it character for character into the OAuth client's authorized redirect URIs, save, wait a few minutes, retry from a private window. If your sign-in is BuildBase, [social login in Next.js](/guides/social-login-nextjs) shows the one callback address to register and the two values to paste back. ### 3. The confirmation email that only you receive Symptom: you signed up fine; a stranger signs up and the confirmation email never arrives, or arrives an hour later, or lands in spam. Cause: the sender is a development sender with limits you never hit, because you were inside them. Supabase's docs on custom SMTP say it plainly about the built-in sender: "Supabase Auth will refuse to deliver messages to addresses that are not part of the project's team", the limit is "2 messages per hour", and the server "is not meant for production use". You are on the team. Your customers are not. The dev.to writer who put it best: "Then a real person signs up, never gets the confirmation email, and you never hear from them again." The fix on Supabase is a custom SMTP sender (Resend, SES, Postmark, SendGrid and others are named in the docs) set in the project's auth settings, after which mail goes to everyone, with a limit of 30 an hour until you raise it on the rate-limits page. On BuildBase, sign-in emails go out through your organization's sending domain (Google, Mailgun, Amazon SES or your own SMTP), which you set once for every email the platform sends, and the [guide on email landing in spam](/guides/transactional-email-landing-in-spam) covers the domain records that keep it out of the junk folder. How to prove it: sign up with an address at a provider you do not use for work (a Gmail account if you build on Outlook, or the reverse), and time the email. Then open it on a phone and look at the sender name and address. "noreply@mail.app.supabase.io" is the development sender; your own domain is the fix. ### 4. The session after a reload, and after a week Symptom: sign-in works; reloading the page signs you out, or everything is fine until a week later when every user is signed out at once. Cause: the session is held in the wrong place, or on the wrong host. The right place is a cookie the browser cannot read, set by your server after the sign-in code is exchanged, with a lifetime you chose. On BuildBase that cookie is 30 days by default, which is the [default session length](/guides/token-expired-mid-request), and the Vite, Next.js and Lovable guides all set it the same way. A session kept in `localStorage` by the browser survives reloads but can be read by any script on the page, which is the thing the 2025 Lovable exposure and the 2026 Moltbook leak had in common: a key the browser held. The wrong host is subtler. A cookie set on `app.example.com` is not sent to `example.com`, and a cookie set on the published `*.lovable.app` address does not follow you to the custom domain. If sign-in works on one address and not the other, that is the cookie, and [a session cookie not shared across subdomains](/guides/session-cookie-not-shared-across-subdomains) is the two-line fix. How to prove it: sign in, close the browser entirely, open the published site again. Still signed in. Then open the same site on the custom domain in the same browser. Still signed in, or you have the subdomain problem. And if your app uses Next.js middleware to guard pages, the symptom "the page reloads forever after sign-in" has its own guide: [middleware redirect loop after login](/guides/nextjs-middleware-redirect-loop-after-login). ### 5. Sign-out that actually signs out Symptom: a user signs out, presses back, and is still inside. Or signs out on a laptop and stays signed in on a phone. Cause: sign-out cleared a value in the browser and told the server nothing. A sign-out has to end the session where it lives, on the server, so that the cookie, the phone and the tab that was left open all stop working at once. On BuildBase, `onSignOut` calls your sign-out route, which clears the cookie, and the SDK revokes the session on the platform, so a device list shows it gone and the other devices lose it too. A generated sign-out usually does only the first half. How to prove it: sign in on two browsers as the same person. Sign out on one. Reload the other. If it is still signed in, the server was never told. The device list on the account screen is the honest check: a session that is signed out should not be listed. The same list is the answer to the first support email every app gets, "I think someone else is logged into my account". Every BuildBase user has a list of their devices and can sign out one or all of them, and so can you, as the owner, from the console; a generated app has neither, because nobody asked, and the only way to end a stolen session is to change the password and hope. If your sign-in is the builder's built-in, check whether the Users view offers the same; as of 27 October 2026, Lovable's shows sign-up and last sign-in times and the methods used, and Replit's Users tab lists people and last sign-in, and neither documents a way to end a session from there. ### 6. The second person, and the second browser Symptom: none yet, because nobody has tried. This is the check that finds the five above before a customer does. Every check on this list fails for a stranger first and for you last, because your browser carries the preview's cookies, your email is on the project's team, and your Google account already consented. So the last check is the first one to run: a private window, a second email address, a phone on mobile data rather than your Wi-Fi, and the published address typed by hand rather than clicked from the editor. Walk the whole path: sign up, confirm, sign out, sign in, close the browser, reopen, forgot password. Then do it once more on the custom domain. Ten minutes, and it is the same ten minutes a stranger will spend before deciding whether your app is real. ### What prompting it instead costs The reason this is a checklist and not a prompt: the fix is a setting, and an agent asked to fix it will change code. Lovable's own pricing page gives 1.20 credits as the example cost of adding authentication in build mode (read 27 October 2026), and the complaint that dominates every builder's reviews is the loop: "repeated 'fixes' that did not fix the problem", as one 1-star Lovable review from 12 October 2026 puts it, and "You will then spend DAYS and credits telling it to do the same thing 15 times", from another in September. Fifteen attempts at 1.20 credits is a fifth of a Pro plan's monthly 100, spent on code that was never wrong. The six checks above cost nothing but ten minutes, and the one prompt worth sending is the one in check 1 that names the addresses and forbids code changes. > **Key takeaway:** Sign-in that works in preview and fails live is an address problem, not a code > problem. Find the allow list, add the exact live address, test as a stranger > from a private window. Prompting the agent to "fix login" will spend credits > on code that was never wrong. ### Where the built-in sign-in is the better pick If your app has one user per account and the built-in sign-in works for strangers after the six checks above, keep it. Lovable Cloud, Bolt Cloud and Replit Auth manage their own redirect addresses when you publish, and Lovable's built-in sign-in adds SAML SSO and OIDC of its own, where BuildBase's [enterprise SSO](/enterprise) runs through your own WorkOS account on the Enterprise plan. An external sign-in adds a client to register and an address to keep in step, and for a single-user app that is work for nothing. Choose a hosted sign-in on your own domain when you want one address to register per environment instead of one per builder preview, methods that are switches rather than code (passkeys, magic links, Google, GitHub, Microsoft, Apple and the rest), a device list and a sign-out that ends the session everywhere, and the teams and plans layer on top. [Should you run auth on your own domain](/guides/should-you-run-auth-on-your-own-domain) is the decision in full, and [the launch checklist](/guides/vibe-coded-app-launch-checklist) is the other nineteen things to check before strangers arrive. ### What breaks, and how you can tell **Loops to the sign-in page on the live site.** Check 1. The live address is not on the allow list, or differs by one character. **Lands on `localhost:3000` after sign-in.** Check 1. The Site URL is still the default. Supabase's and Bolt's docs both name that default. **Error 400: redirect_uri_mismatch.** Check 2. Google's authorized redirect URIs do not include the provider's callback address exactly. **Confirmation email arrives for you and nobody else.** Check 3. The development sender delivers only to the project's team, at two an hour. **Signed out on every reload.** Check 4. The session route is not deployed, or the cookie is set on another host. **Signed out, pressed back, still inside.** Check 5. Sign-out never reached the server. **"Users can't log in", and you cannot reproduce it.** Check 6. You are testing as yourself. Private window, second email, phone on mobile data. ### Install If the fix for your app is a hosted sign-in page with one address to register, the SDK and the CLI write the sign-in routes for you: ```bash npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## Paid plans that actually gate features: plans, trials, limits and seats for a vibe-coded app > Every builder takes the money. The hard half is after: the plan has to change what the app does, and nobody may mark themselves paid. Each step with a prompt, from the webhook to the server gate. - Source: https://www.buildbase.app/guides/paid-plans-that-gate-features-vibe-coded-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-27 ### In short A paid plan gates a feature when three things agree: the plan lives on the customer workspace, not in your database; the button checks it in the browser; and the server checks it again before doing the work. Stripe takes the card, BuildBase keeps the plan, and a signed webhook ties the two together. "The worst Lovable payment bug is the one where the payment works." A developer who fixes vibe-coded apps for a living wrote that on 20 October 2026, and it is the whole subject of this guide. The customer is charged. The app never notices. The paid feature stays grey, the customer emails you, and you refund a payment that worked perfectly. Every builder now takes the money. Lovable has Paddle and Stripe built in, Bolt and Replit have Stripe connectors, v0 has Stripe in the Vercel Marketplace, Base44 has its own payments by Wix. What none of their docs cover, as of 27 October 2026, is the part after the checkout: a plan that belongs to a team rather than a person, a trial that ends on its own, a seat count, a usage limit, and a feature that appears when the plan says so and disappears when the card fails. That is what you are building here. When it works: a customer picks a plan on a test card, the paid feature appears without a reload, a colleague they invited gets it too because the plan belongs to the workspace, the trial ends and the app knows, and when the card fails on renewal the feature closes and an email goes out. And at no point does your app hold a column that says `paid: true`. What we ran on 27 October 2026: the SDK's plan, entitlement and webhook pieces are the ones the Next.js guide and the existing billing guides are built on, and the webhook route is the one `npx buildbase init` writes. The prompts below are what we hand to an agent; the "what you should see" lines are what those pieces do. We have not run this flow inside a builder's own chat today, so where a builder's behaviour matters it is named. > **Before you start:** An app with BuildBase sign-in already working (the [v0 > guide](/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app) or the [Lovable > guide](/guides/add-login-teams-and-paid-plans-to-a-lovable-app) gets you > there), a Stripe account in test mode, and the signing secret of a webhook > endpoint created in the console. A workspace per customer is already on by > default; this guide assumes it. ### 1. Decide what "paid" changes, in writing Before any prompt, write down what each plan unlocks, as a short list of feature names: `export`, `api-access`, `five-seats`, `priority-support`. Those names become feature flags tied to plans, and they are the only vocabulary the rest of this guide uses. A plan that does not change what the app does is a donation, not a subscription. Why first? Because an agent asked for "add Stripe subscriptions" builds a checkout and stops. It has no idea which button the money is supposed to turn on, so it turns on nothing, and that is the bug in the opening line. Naming the features before the prompt is the difference between "add billing" and "gate the export feature behind the Pro plan". Keep two kinds of thing apart while you write the list, because they are wired differently: - **A feature the plan includes or does not.** Export on Pro, not on Launch. This is a flag tied to the plan. - **A quantity the plan allows.** Five seats, 1,000 generations a month, 10 GB. This is a limit or a credit balance, and it has its own guide: [a credits wallet](/guides/credits-wallet-nextjs) when it is a balance, [enforcing quotas](/guides/enforcing-quotas-in-react) when it is a cap. The distinction between a flag and an entitlement is worth ten minutes before you prompt: [entitlements are not feature flags](/blog/entitlements-are-not-feature-flags) explains why "sees the button" and "may call the endpoint" are two different questions, and why you want the second. What you should see: a list of three to six feature names and which plan carries each. Paste it into the prompts below where they say ``. ### 2. Create the plans in the console, synced to your Stripe Plans, prices and trials live in the BuildBase console and sync to your own Stripe account; Stripe is yours, at Stripe's rates, and the platform fee is 0%. No card data touches your app, ever. In the console, create the plans from step 1 with a monthly and a yearly price each, and mark which features each plan includes. Three settings matter more than they look: **The trial.** A free trial that becomes a plan without a second checkout. Decide the length now, and decide whether it needs a card. Our own plans run a 7-day trial with no card; [a trial without a card](/guides/free-trial-without-a-card-nextjs) walks through what changes when you skip the card, chiefly that the trial ending has to do something on its own. **Versions.** A plan change creates a new version rather than editing the old one, so raising a price never moves an existing customer unless you choose to move them. [Plan versioning](/guides/plan-versioning-nextjs) is the day-you-raise-prices guide, and [proration on plan change](/guides/proration-on-plan-change-nextjs) covers what the customer is charged when they switch mid-month. **Currencies.** Pick them before the first subscription. [Choosing your currencies before you have customers](/guides/choosing-billing-currencies-before-your-first-subscription) is short and saves a migration. The pricing page and the checkout come ready-made, in 21 currencies, and you can use the SDK's or draw your own against the same plans. If you draw your own, the [annual and monthly toggle](/guides/annual-and-monthly-toggle-nextjs) is the one piece worth copying rather than inventing, because the yearly price has to come from the plan rather than from a multiplication in the component, or the two drift the first time you change one. What you should see: in Stripe's test dashboard, products and prices that match the console, created by the sync rather than by hand. If you made a price in Stripe first, that is the wrong direction; the console is the source and Stripe the mirror, and [keeping a pricing page honest against your plans](/guides/keeping-a-pricing-page-honest-against-your-plans) explains why. ### 3. The webhook: where the plan reaches your app The plan never lives in your database. It lives on the customer's workspace in BuildBase, and your app learns about changes through signed webhook events. The route that receives them is the one `npx buildbase init` writes, or the one this prompt asks for: ```text Add a POST route at /api/webhooks/buildbase (app/api/webhooks/buildbase/route.ts on Next.js). Verify every delivery with parseWebhookEvent from @buildbase/sdk on the raw request body, using BUILDBASE_WEBHOOK_SECRET from the environment, and reject anything that fails verification with 401. Handle these events by name and nothing else: subscription.created, subscription.upgraded, subscription.downgraded, subscription.canceled, subscription.suspended, subscription.trial_will_end, subscription.trial_expired, payment.failed, payment.succeeded. Do not write the plan, the trial state or any "paid" flag to my database. The workspace carries them. Use the events to send email, post to Slack, or log, and respond 200 quickly. ``` Then, in the console, point an endpoint at that address and copy its signing secret into `BUILDBASE_WEBHOOK_SECRET`. Why "do not write the plan to my database" is in the prompt, in bold in our heads: the audit that keeps coming up in these guides found, in February 2026, "development endpoints still in production that let anyone mark themselves as a paid user and give themselves unlimited credits". That endpoint existed because the plan was a row the app owned. When the plan is a property of the workspace in BuildBase, read through the SDK, there is no row to flip and no endpoint to leave behind. What you should see: subscribe on a test card, and the console's delivery log for the endpoint shows `subscription.created` delivered with a 200 from your route. Stop your server, cancel the subscription, start it again: the `subscription.canceled` delivery is retried and lands, because deliveries are tried up to five times over about two and a half minutes. [What a webhook is, and what happens when delivery fails](/blog/what-are-webhooks) has the ladder. **Correcting potential issues.** If the agent wrote a Stripe webhook handling `invoice.paid` or `customer.subscription.updated` directly, it built the billing a second time, next to the one in the console. Paste: "Remove the direct Stripe webhook. BuildBase receives Stripe's events; my app receives BuildBase's events at /api/webhooks/buildbase only." If it added a `plan` column to a users or workspaces table, paste: "Remove the plan column. The plan is read from the workspace through the SDK, never stored in my database." ### 4. The button: gate the feature in the browser In the app, the gate is a component around the feature, with the feature name from step 1 as its `slug`. The SDK ships two for this, and the difference matters. ```tsx import { WhenEntitled, WhenWorkspaceFeatureEnabled } from '@buildbase/sdk/react'; // The current workspace's plan includes this feature, and nobody has turned it off. }> // The flag is on for this workspace, whichever plan it is on. ``` `WhenEntitled` answers the plan question: does this workspace's plan include the feature, and is it still available (a suspended subscription says no). `WhenWorkspaceFeatureEnabled` answers the switch question: is the flag on for this workspace, which is how you run a beta for the customers you choose, or let a workspace admin turn an allowed feature on or off from the built-in settings screen. Most paid features want the first; most betas want the second. Prompt for it: ```text Wrap each paid feature in the app in from @buildbase/sdk/react, using these feature slugs: . Where a feature is locked, show a short upgrade prompt that opens the SDK's plan screen; do not hide the button silently. Show the current plan, the trial end date and an upgrade or cancel action on the /settings page using the SDK's built-in billing screen. Do not build a custom pricing table; use the SDK's. ``` What you should see: on a free workspace the export button shows the upgrade prompt; subscribe on a test card and it becomes the real button without a reload, because the workspace's plan changed under the component. A teammate in the same workspace sees the same, because the plan belongs to the workspace rather than to the person who paid. That last part is what a per-user subscription cannot do, and it is why Lovable's one subscription per user, documented as the default on 27 October 2026, is the wrong shape for anything with teams. > **Key takeaway:** The browser gate decides what people see. It never decides what they may do. > Anything a component hides can be requested by hand, so step 5 is the one that > makes the plan real. ### 5. The server: the gate that cannot be bypassed Every feature the browser gates has a server route that does the work, and that route checks the plan again before doing it. This is the step generated apps skip, and it is the step the audits catch, so it gets its own prompt rather than a sentence in another one. ```text In every server route that performs a paid feature (), check the current workspace's entitlement for the feature slug through the BuildBase server SDK before doing the work, using the session from the request, and return 402 with a short JSON error when the workspace is not entitled. Never trust a plan or feature value sent by the browser in the request body or headers. Do not cache the answer across requests. ``` Why 402 and why "never trust the request body": the other finding in that February audit was "a live marketplace with real Stripe payments where any logged-in user could grant themselves admin and hijack payment routing with a single request", and a Mastodon post from a developer who reviews AI-built code names the pattern he looks for first: "server routes that take a user id from the request body instead of the session". A plan in the request body is the same mistake with a different noun. The server asks BuildBase who this session is and what its workspace is entitled to, and ignores whatever the browser claims. [Server-side quota enforcement](/guides/quota-enforcement-server-side-nextjs) shows the same shape for a limit, and the reason the answer should not be cached for long: a permission change reaches a signed-in user within the hour, and [why that is](/blog/why-permissions-refresh-hourly) is a trade we made on purpose. What you should see: in the browser's developer tools, copy the request the export button makes and replay it from a free workspace's session. It should come back 402, every time, whatever you put in the body. **Correcting potential issues.** If the route checks a header like `x-plan: pro` or a field in the JSON body, paste: "Remove every plan or feature value read from the request. Derive the workspace from the session and ask the BuildBase server SDK for the entitlement." If the route checks nothing because "the button is already hidden", paste the same line, and then read step 4's takeaway again. ### 6. Seats, when the plan is per person Some plans are priced per seat: three members included, more at a price. The workspace keeps the seat count, inviting past it is refused by the server with a named error, and the SDK's `useSeatStatus` counts pending invitations against the ceiling the same way the server does, so the invite button can say "2 of 5 seats" before anyone clicks it. [Charge per seat](/guides/charge-per-seat-nextjs) is the full guide, and the prompt is one line: ```text Price the Pro plan per seat with three seats included. Show seat usage from useSeatStatus on the members screen, and let an admin buy more seats through the SDK's plan screen. Do not count members in my own database; the workspace knows. ``` What you should see: the fourth invitation on a three-seat plan is refused with a seat-limit error the members screen shows in words, not a silent nothing. If you ever see "something went wrong" instead, the error's `code` was dropped on the way to the screen; the SDK's invitation errors carry it. ### 7. The trial ends, the card fails: what happens on its own A subscription has a life after checkout, and the events in step 3 are how the app keeps up without you watching. Three of them deserve a workflow rather than a line in the webhook route, because a workflow is a thing you can see ran. - **`subscription.trial_will_end`**: a heads-up email a few days before, with a link to the plan screen. This is the single most effective email a SaaS sends, and generated apps never send it because nobody asked. - **`payment.failed`**: an email saying the card failed, with the link to update it, and a note to your Slack channel. The subscription is not cancelled on the first failure; the dunning sequence handles retries, and [usage that does not match the invoice](/guides/usage-does-not-match-invoice) explains the states between "paid" and "gone". - **`subscription.suspended`**: the feature gate from step 4 closes on its own, because `WhenEntitled` reads the workspace's state, and a last email says so. In the console's workflow editor these are three triggers, two email steps and one Slack step, published without a deploy. In the app, nothing changes, which is the point. What you should see: let a test card fail on renewal (Stripe's test cards include one that fails on the second charge). The `payment.failed` delivery lands, the email goes out from your sending domain, Slack gets a line, and the export button on that workspace shows the upgrade prompt again once the subscription is suspended. ### Where the builder's own payments are the better pick Keep Lovable's built-in payments, or Bolt's or Replit's Stripe connector, when your app sells one subscription to one person and the plan does not need to change what the app does beyond a single "premium" check. Inside the builder they are a prompt away, and Lovable's Paddle option (5.0% plus 50 cents per transaction, read from its docs on 27 October 2026) handles the tax side, which Stripe alone does not. If you sell in many countries and want someone else to be the merchant of record, that is a real advantage we do not offer; our billing is Stripe, bring your own. Choose this guide's shape when the plan belongs to a team, when a feature has to open and close with the subscription, when seats or limits are part of the price, or when a trial has to end without you. Lovable's docs describe one active subscription per user by default, one provider per project, and a project that cannot be forked once payments are on; none of Bolt's, Replit's or v0's describe a plan per team at all. That layer is what the webhook, the two gates and the workflows above add, with Stripe still yours. [The Clerk and Stripe combination, and when to skip it](/compare/clerk-stripe-combination) is the same comparison from the other side. ### What breaks, and how you can tell **Paid, still on the free plan.** The endpoint in the console points at the wrong address, or `BUILDBASE_WEBHOOK_SECRET` is empty. The delivery log shows each attempt: a 401 means the secret, a timeout means the route. **The feature appears for the person who paid and not for their teammate.** Something stored the plan per user. Remove it; the plan is on the workspace, and `WhenEntitled` reads the workspace. **The feature works after cancelling.** The server route in step 5 is missing, or it cached the answer. Replay the request from the cancelled workspace's session and watch for the 402. **Two customers were charged twice for one upgrade.** Your route did the work twice because the retry ladder delivered the same event twice and nothing noticed, which is what the event id is for: it is identical on every retry, so store it and make a second sighting a no-op. [Idempotency in billing](/blog/idempotency-in-billing) is the fix. **The pricing page shows a price Stripe does not charge.** Someone edited Stripe by hand. The console is the source. Re-sync, then read [keeping a pricing page honest](/guides/keeping-a-pricing-page-honest-against-your-plans) before it happens again. **The trial ended and nothing happened.** No workflow is listening to `subscription.trial_expired`, so the gate closed on its own and the email did not go out, because nobody asked for it. Step 7. ### Install Add the SDK to the app you have, or let the CLI write the webhook route and the rest of the sign-in files: ```bash npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## Teams, invites and admin vs member for an app you built with a prompt > No builder ships teams for your end users. Give every customer their own workspace, let them invite colleagues by email, and make admin vs member a rule the server enforces, not a hidden button. - Source: https://www.buildbase.app/guides/teams-invites-and-roles-for-a-vibe-coded-app - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-27 ### In short To add teams to a vibe-coded app, give every customer a workspace of their own on first sign-in, let members invite colleagues by email with a role, and enforce that role where the data is read, on the server. BuildBase holds the workspaces, members and roles; your database keeps the data, scoped by workspace id. Two people from the same company sign up for your app separately. Now you have two accounts that should have been one, two sets of data that should have been shared, and no way to merge them that does not involve you, a database, and a Saturday. This is the teams problem, and it arrives with the second customer rather than the hundredth. No builder ships the answer for your end users. Lovable's changelog is full of workspaces, roles, invites and SCIM, and every entry is about Lovable's own workspaces for the people building the app. Its end-user sign-in docs describe no teams, roles or invitations; Base44's cover sign-in methods and no roles; Bolt, Replit and v0 document nothing here. All read on 27 October 2026. Whatever a prompt builds for teams, it builds from scratch, and what it builds is the subject of every audit of a vibe-coded app we have read. So this guide does it the other way round. The workspaces, the members, the invitations and the roles live in BuildBase, where they already exist, and your database keeps your data with one extra column. When it works: a new customer lands in their own workspace the moment they sign in, invites a colleague who gets an email and arrives in the same workspace with the role they were given, sees a member list and a switcher, and cannot see, or change, a single row that belongs to another company, however the request is made. What we ran on 27 October 2026: the workspace, invitation and role pieces below are the ones the published guides on [workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon), [team invitations](/guides/team-invitations-nextjs) and [roles per workspace](/guides/roles-and-permissions-per-workspace-nextjs) are built on, and the data-isolation pattern is the one in [per-org data isolation](/guides/per-org-data-isolation-nextjs). The prompts are what we hand an agent. We have not run them inside a builder's chat today. > **Before you start:** An app with BuildBase sign-in working (the [v0 > guide](/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app) or the [Lovable > guide](/guides/add-login-teams-and-paid-plans-to-a-lovable-app) gets you > there), and a BuildBase organization in Platform mode, which is the default. A > second email address you control, for the invite. ### 1. Decide what a workspace is, in your product's words A workspace is the thing a customer pays for and shares with colleagues. Before any prompt, decide what your product calls it (team, company, studio, school, client) and whether a person can belong to more than one. That one decision shapes the switcher, the invitation email and the settings screen, and an agent will guess it wrong if you do not say. Two settings in the console back the decision, under the organization's workspace settings: - **Auto-create first workspace.** On by default: a new user lands in a workspace of their own on first sign-in, with no setup step. Leave it on unless every user is invited into an existing team and never starts one. - **Can users create more workspaces.** On if a consultant can have one workspace per client; off if a person belongs to exactly one company. What you should see: a decision written in one line ("a workspace is a school; teachers belong to one; admins can create more"), and the two switches set to match. Everything below uses your word. ### 2. The switcher and the first workspace The SDK's `useSaaSWorkspaces()` returns every workspace the signed-in person belongs to, the current one, and the calls to create and switch. The switcher is one component you style; the data is already there. Prompt for it: ```text Add a switcher to the app header using useSaaSWorkspaces() from @buildbase/sdk/react: list the the user belongs to, mark the current one, switch on click, and show "New " if the organization allows users to create more. Call fetchWorkspaces() once after sign-in and select the first if none is selected. Do not create , membership or role tables in my database; BuildBase holds them. Every page that shows my data reads currentWorkspace.id from useSaaSWorkspaces() and uses it in the query. ``` What you should see: sign up with a fresh email and you are in a workspace already, named for you, with the switcher showing one entry. If creating more is allowed, create a second and switch; the pages re-query for the new id. If the switcher is empty, the override in step 1 is off or the organization is in Personal mode, and [auto-created first workspace](/guides/auto-created-first-workspace-nextjs) has the two-minute fix. The last line of that prompt is the one that matters, and the next section is about why. ### What an agent builds for teams when nobody tells it otherwise Left to itself, an agent asked for "teams" writes a `teams` table, a `memberships` table with a `role` column, and a page that lists members. It is the textbook shape, and it is where every audit of a vibe-coded app we have read finds the leak, so it is worth knowing before you prompt what the generated version leaves out. The invitation is usually a row inserted for an email address, with no email sent, no pending state and no expiry, so the invited person either never hears about it or arrives to find nothing. The role is checked on the page that lists members and nowhere else; the routes that change data trust whoever is signed in. The workspace id travels in the request body, because that is the easiest place for the agent to put it, which means any member can send another workspace's id. And the "current workspace" is whatever the browser last said it was. None of that is carelessness. A developer who runs a competing platform said on Hacker News in August 2026 that the apps he sees from non-technical founders are "all apps with multi-tenancy - database backed - payment integrations - the works", a dance-school management tool, a classifieds site with paid upgrades. The builders ask for teams because their customers are teams, and the agent delivers the textbook, which was written for a tutorial with one trusted user. The three findings from the February 2026 audit (self-promotion to admin, a paid flag anyone could set, a dev endpoint left live) are the textbook meeting its first stranger. What this guide does differently is move the parts that need to be right (who is in which workspace, who may do what, how an invitation becomes a member) into a system that already enforces them, and leave the agent one job it can do well: filter your rows by an id the server already knows. ### 3. Your data, scoped by workspace: the part no SDK does for you Your tables are yours, in Lovable Cloud, Supabase, Neon or wherever the builder put them, and every row that belongs to a customer carries their workspace id. BuildBase decides who is in which workspace; your queries decide which rows a workspace sees, and no SDK can write those queries for you. This is the step a prompt gets wrong most often, so it is the longest one. The rule has three parts, and all three have to hold: 1. **Every customer row has a `workspace_id` column**, set when the row is created, from the current workspace, on the server. 2. **Every read and write filters by it**, with the id taken from the session's workspace on the server, never from the request body. 3. **The database refuses what the query forgets.** Row-level security in Supabase or Postgres, or a check in the data layer that no route can skip. Why "never from the request body" gets its own clause: a developer who reviews AI-built code wrote on 25 October 2026 that the first thing he looks for is "server routes that take a user id from the request body instead of the session", alongside "tables without RLS, policies that say true". A workspace id in the request body is the same bug: any member can send another workspace's id and read its rows. The server knows which workspace the session is in; it never needs to be told. ```text Add a workspace_id column to every table that holds customer data (), filled on insert from the current workspace on the server. Filter every select, update and delete by workspace_id, taking the id from the server session's current workspace, never from the request body, query string or headers. Add row-level security policies so a row is only readable and writable when its workspace_id matches the caller's current workspace. Keep the policies in a migration file I can read. ``` If your sign-in is BuildBase and your data is in Supabase, there is one honest wrinkle: Supabase policies keyed to `auth.uid()` do not know a BuildBase session. Either read and write through server routes that check the session and query with a server credential scoped by the workspace id, or mint a Supabase-shaped token on your server for browser queries. Both are laid out in [the Lovable guide](/guides/add-login-teams-and-paid-plans-to-a-lovable-app), section 7, and [per-org data isolation](/guides/per-org-data-isolation-nextjs) shows the server-route shape in Next.js. What you should see, and this is the test that matters: sign in as a member of workspace A, open a page that lists rows, and in the browser's developer tools replay the request with workspace B's id in the body, the query string and a header. Every attempt returns A's rows or nothing. Then change the id in the page address, if the page carries one. Same result. If any of those returns B's data, the filter trusts the client, and nothing else in this guide helps until that is fixed. > **Key takeaway:** BuildBase decides who belongs to which workspace. Your queries decide which > rows a workspace sees, with the id from the session, never the request. Both > halves have to be right, and the audits say the second half is the one that is > usually wrong. ### 4. Invite a colleague by email Members invite teammates by email and give each one a role. An address with no account yet gets an email with a link; following the link is the proof, so the person signs up and lands in the workspace without a separate email-verification step. If the organization has switched invitations off, the landing page says so before anyone is sent anywhere. The SDK's built-in members screen does all of this, which is why the prompt is mostly about not rebuilding it: ```text Add a /settings page that opens the SDK's built-in workspace, members and billing screens. On the members screen, admins can invite by email with a role, change a member's role, remove a member, and see and withdraw pending invitations; members see the list read-only. Use the SDK's screens and hooks (useWorkspaceInvitations, inviteMember); do not build an invitation table, an invitation email or an accept page of my own. ``` What you should see: invite your second email address as a member. The email arrives from your sending domain with a link; open it in a private window, sign up, and you land in the same workspace with the member role. Back in the first window, the pending invitation has become a member. Then invite the same address again: refused, with a named reason, because the SDK's invitation errors carry a `code` and the server's fields (the seat limit and the count when it is a seat limit, the retry delay when it is a rate limit), and the screen says each in words. Two things can refuse an invitation that look like bugs and are not. A seat limit on the plan, which the members screen shows as "n of m seats" through `useSeatStatus`, counting pending invitations the way the server does. And an outsiders policy: an organization can block inviting people from outside its own domains, or cap the role an outsider may hold, and the error names that too. [Why an invited member cannot see the workspace](/guides/invited-member-cannot-see-workspace) walks the other failure, where the invitation worked and the data did not follow. ### 5. Admin and member: enforce the role where the data is A role is a rule about what a teammate may do, and it is only a rule if the server applies it. Owners and admins decide what each member can do; the API refuses what the role does not allow; the interface merely hides what would be refused. Generated apps get the third part and skip the second, which is the bug every audit finds. The February 2026 audit of three apps posted to Reddit found "a live marketplace with real Stripe payments where any logged-in user could grant themselves admin and hijack payment routing with a single request". The admin button was hidden. The request behind it was not checked. One request. Roles in BuildBase exist at two levels: organization roles for your own staff, and workspace roles for the customer's team, with defaults a workspace can adjust and permissions you add for your product ("export reports", "manage billing"). In the browser, the SDK ships the gates: ```tsx import { WhenWorkspaceRoles, WhenPermission } from '@buildbase/sdk/react'; ``` And on the server, the same question asked of the session, not the request: ```text Every server route that changes data or settings must check the caller's role or permission in the current workspace through the BuildBase server SDK, using the session, before doing the work, and return 403 with a short JSON error otherwise. Never read a role, a permission or an "isAdmin" value from the request body, query string or headers. In the browser, wrap admin-only controls in or from @buildbase/sdk/react, as a convenience only; the server check is the rule. ``` Two levels, and it is worth knowing which you are prompting for. An organization role is for your own staff: who at your company may see every workspace, change plans, read the audit log. A workspace role is for the customer's team: owner, admin, member, or the names your product uses, with the defaults a workspace admin may adjust for their own team. The permissions you add ("reports.export", "billing.manage") hang off workspace roles, so a customer's owner decides which of their colleagues may export, and your server asks that question of the workspace, not of a global table. If you have one role column today, this is why it is not enough: the same person can be an admin of one workspace and a member of another. What you should see: as a member, copy the address of an admin-only page and open it: the controls are gone. Then, from the developer tools, replay an admin request (change a role, delete the workspace) with the member's session. 403, every time, whatever the body says. If it succeeds, the route checks nothing or checks the client, and that is the one-request bug. One honest caveat about timing: a role change reaches a signed-in user within the hour, not instantly, because the SDK refreshes permissions on a schedule rather than on every request. [Why permissions refresh hourly and not instantly](/blog/why-permissions-refresh-hourly) is the trade, and [a permission change not taking effect](/guides/permission-change-not-taking-effect) is what to do when you need it sooner. [What is RBAC](/blog/what-is-rbac) is the explainer if "role" and "permission" are blurring together. ### 6. Switching, and the data that did not switch The last bug is the quiet one. A person switches workspace in the switcher, and a page still shows the old workspace's rows, because a hook cached them or a query ignored the change. It looks like a leak and it is usually a stale fetch. ```text Every data hook and loader in the app depends on currentWorkspace.id from useSaaSWorkspaces(): when it changes, refetch, and clear any cached rows from the previous before the new rows arrive. Never keep rows from one in memory while another is selected. ``` What you should see: with two workspaces that have different data, switch back and forth. Each page shows only the selected workspace's rows, immediately, with no flash of the other's. [Stale data after a workspace switch](/guides/stale-data-after-workspace-switch) covers the cache details in Next.js. ### The screens you do not have to build The settings screens for all of this ship with the SDK: workspace, members (invite, pending invitations, roles, remove), billing, plan, usage, devices, notifications and the rest, thirteen in all, in eight languages including right-to-left ones. The `/settings` prompt in step 4 opens them inside your app's own layout. You can draw your own members screen against the same hooks (`useSaaSWorkspaces`, `useWorkspaceInvitations`, `useSeatStatus`), and the only reason to is a design system the built-in screens do not match; the behaviour is the same either way, and the refusals (a seat limit, an outsider policy, a duplicate invitation) come back as the same named errors. Where the built-in screens earn their keep is the part nobody budgets for: the pending-invitation list, the "withdraw" action, the role change that has to be refused when it would leave a workspace with no owner, the member removal that has to end that person's session on the server. A generated members page does the first thing on that list and none of the others. ### Where the builder's built-in sign-in wins If your app is for one person, a notebook, a personal tracker, a tool for a single operator, you do not need any of this, and the builder's built-in sign-in with its users list is the better pick: zero setup, no switcher, no roles to explain. Lovable's Users view, Replit's Users tab and Base44's auth cover that case well, and adding workspaces to an app that will never have two people in one account is weight for nothing. The moment a second person from the same customer shows up, the maths flips. Merging two personal accounts into one team later is the migration every small SaaS dreads, and the audits say the generated version of teams is where the data leaks. [What is multi-tenancy](/blog/what-is-multi-tenancy) is the short explainer; [the best multi-tenant backend](/compare/best-multi-tenant-backend) is the comparison if you want to weigh the alternatives before committing. ### What breaks, and how you can tell **A member sees another company's rows by changing an id.** The filter takes the id from the request. Step 3, and nothing else matters until it is fixed. **The switcher is empty, or "New team" does nothing.** Auto-create is off, the organization is in Personal mode, or "Can invite members" is disabled under advanced overrides. Step 1's two switches. **The invitation email never arrives.** It is sent from your organization's sending domain, and that domain is not set up yet; [email landing in spam](/guides/transactional-email-landing-in-spam) is the guide. The invitation itself exists; check pending invitations on the members screen. **Invited, signed up, sees nothing.** The person signed up with a different email than the one invited, or accepted in a browser that then switched to a personal workspace. [Invited member cannot see the workspace](/guides/invited-member-cannot-see-workspace) walks it. **A member promoted themselves.** The role-change route checks the client, or checks nothing. Step 5; replay the request to prove the fix. **The role changed but the member still sees the old buttons.** Up to an hour, by design. Sign out and in to force it, or follow [permission change not taking effect](/guides/permission-change-not-taking-effect). ### Install Add the SDK to the app you have, or let the CLI write the sign-in files the switcher and members screen sit on: ```bash npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## The vibe coder's launch checklist: 20 things between a demo and a product > Your AI-built app works for you. Before strangers use it, twenty things have to be true that a demo never tests: login that holds up live, teams, plans that gate access, emails that arrive. - Source: https://www.buildbase.app/guides/vibe-coded-app-launch-checklist - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-27 ### In short A vibe-coded app is ready for strangers when twenty things are true that a demo never tests: sign-in that survives publishing, teams with roles, paid plans that gate features, emails that arrive, usage limits, signed webhooks. This list names each in plain words, what your builder already covers, and what to add. Your app works. You showed it to a friend, they signed up, it looked real. Then you published it, and the second person who tried it could not log in. That is not a bug in the usual sense. A demo tests one person, in one browser, who already trusts the app and never tries to break it. A launch tests strangers, their colleagues, their phones, and their credit cards. Twenty things have to be true for that to go well, and a demo exercises none of them, which is why the demo passed and the launch did not. This is that list. It is written for someone who built the app by prompting and will add the next piece the same way, so every item says what the thing is in plain words, what your builder already gives you (checked on 27 October 2026 against each builder's own docs), what to look at on the live site, and what to add. The technical term appears once in brackets so you can search for it. After that, the plain word does the work. ### Why the demo passed and the launch will not The demo passed because nothing in it was hostile. The launch fails because the app has no opinion about strangers: who they are, which company they belong to, what they paid for, what they may see. Those four questions are the whole difference between a working page and a product, and no builder answers them for you by default. The evidence is not theoretical. In 2025 a scan of 1,645 published Lovable apps found 170 of them, 10.3%, with database tables any visitor could read or write; that became CVE-2025-48757, which Lovable disputes. In February 2026 a researcher reported 16 flaws in one exam app featured on Lovable's own Discover page, including a sign-in check written backwards that let anonymous visitors in and blocked real users; 18,697 records were exposed. The same month, a developer audited three products people had posted to Reddit and wrote up what he found: "any logged-in user could grant themselves admin and hijack payment routing with a single request", and in another, "development endpoints still in production that let anyone mark themselves as a paid user and give themselves unlimited credits". None of those apps was broken in the demo sense. Every one of them worked for its builder. An ICU doctor who had spent a month vibe-coding medical simulators said the quiet part out loud on Hacker News in September, while explaining why he would not post his own email address on the forum: "I'm not smart enough to know whether that is safe or not." A person who ships software to strangers and cannot judge that about an email address is the reader this list is for. Nobody can judge it by looking. You have to check. ### How to use this list Go in order. The order is the order a stranger meets your app: the front door first, then who they are and who they work with, then money, then the things that happen on their own, then what your server hears about, then the rest of the product. Do each check on the **published** site, in a private window, as a second person, never as yourself in the builder's preview. For each item there is a line saying what the builders cover. Lovable, Bolt, Replit, v0 and Base44 ship more every week, so that line carries a date, and if you are reading this months later, open the builder's docs before you trust it. The paste prompt is at the end, and so is the install line. ### The front door The two things about login that a demo never tests are the second browser and the second week. A sign-in that works in the preview, in your own browser, proves nothing about a stranger on a phone or about the same person coming back after a holiday. Both are checks you can run in five minutes. #### 1. Login that survives publishing What it is: sign-in (authentication) that works on the live address, not just in the editor. The way it fails is specific: it works in preview, then on the published site it loops back to the sign-in page, or lands on `localhost`, or the Google button spins and stops. A Replit review from 17 October 2026 reads, in full, "Users can't log in." Why: the provider doing the sign-in only sends people back to addresses it has been told about. The preview address was registered; the published one was not. Lovable's own sign-in docs point at exactly this when sign-in works in preview but fails on a published or custom domain, and add that if you connected your own Supabase project, Lovable does not update those addresses for you. What the builders give you, 27 October 2026: Lovable's built-in sign-in covers email, phone, Google, Apple, Microsoft, Sign in with Lovable, SAML SSO and OIDC, with up to 50 redirect addresses per app. Bolt Cloud covers email and Google. Replit gives you Replit Auth or a Clerk account it provisions. v0 has no end-user sign-in of its own; Clerk and Auth0 are one click away. Base44 has built-in sign-in with social providers. What to check: open the published site in a private window, sign up with a second email, close the browser, open it again. You should still be signed in. Then sign out and confirm you really are: reload, and you should be asked to sign in again. What BuildBase adds: a hosted sign-in page on your own domain, so there is one address to register per environment instead of one per builder preview. The methods are switches in the console, not code: email and password, a magic link, an email code, a phone sign-in code sent through your own Twilio account, passkeys, Google, LinkedIn, GitHub, Microsoft, Apple, your own OIDC provider, and Ethereum or Solana wallets. Sessions are 30 days by default, and sign-out ends the session on the server, not just in the browser. #### 2. A list of your users, and the power to sign one out What it is: a record of every person who signed up (user management), with their devices and their activity, and two buttons you will need on a bad day: sign this device out, and block this account. The demo never needs this because the only user is you. The first support email you get after launch is "I think someone else is logged into my account", and the honest answer requires a device list. What the builders give you: Lovable's Users view is a searchable list with sign-up and last sign-in times and the methods each person used. Bolt and Base44 show users in their database views. None of them documents a device list or a sign-out-everywhere button for your end users. What to check: sign in on two browsers as the same person. Can that person see both sessions anywhere? Can you, as the owner, end one of them? What BuildBase adds: every user has a device list, and both the user and you can sign out one device or all of them. You can remember things about each person (onboarding done, plan chosen) as attributes, keep lists of people by hand or by filter, and import a CSV of the mailing list you already have. ### Who is who A stranger rarely arrives alone. They sign up for their company, invite a colleague, and expect the colleague to see the same data and nothing else. Teams and roles are the two items on this list that no builder ships for your end users today, and they are the two that every audit of a vibe-coded app finds broken. #### 3. Teams: an account per company, not per person What it is: each customer gets their own space (a workspace, which is what multi-tenancy means in practice) with its own members, its own plan and its own data. One company hitting a limit never blocks another. Builders say "teams"; developers say "tenants". Same thing. Why it matters now rather than later: the moment two people from one company sign up separately, you have two accounts that should have been one, and merging them later is the single most painful migration a small app does. What the builders give you, 27 October 2026: Lovable's changelog is full of workspaces, roles, invites and SCIM, and all of it is about Lovable's own workspaces for the people building the app, not for the people using it. Lovable's end-user sign-in page mentions no teams, roles or workspaces, Base44's auth docs cover sign-in methods and no roles, and Replit, Bolt and v0 document nothing here for end users at all. What to check: sign up as two people from the same imaginary company. Can the first invite the second? Does the second see the first's data, and only that? Can either of them see a third stranger's data by changing an id in the address bar? What BuildBase adds: a new user lands in a workspace on first sign-in, with no setup step, and you decide whether they may create more. A switcher shows every workspace a person belongs to; you style the button, the SDK does the rest. Members invite teammates by email, including people who have no account yet, and give each one a role. Each workspace carries its own plan, seats and limits. #### 4. Admin and member: who can press which button What it is: roles and permissions (RBAC). Owners and admins decide what each teammate can do, and the rule is enforced where the data lives, not only by hiding a button in the interface. That last clause is the whole item. The audit quoted above found an app where "any logged-in user could grant themselves admin" with one request, because the button was hidden and the request behind it was not. A prompt that says "only admins can see the billing page" will usually hide the page. It will not usually stop the request. What the builders give you: nothing documented for end-user roles on any of the five, as of 27 October 2026 (Lovable's built-in payments page does mention roles, but those are Lovable's own roles for who may set up payments on the project). What to check: as a plain member, copy the address of an admin-only page and open it. Then repeat an admin request with your member session from the browser's developer tools, and watch what comes back; both should be refused by the server, not just missing from the menu. What BuildBase adds: roles at the organization level and per workspace, with permissions of your own ("export reports") and defaults a workspace can adjust. The same rules are enforced by the API, which is the half most generated apps skip. One honest caveat: a permission change reaches a signed-in user within the hour, not instantly, and [why that is](/blog/why-permissions-refresh-hourly) is a trade we made on purpose. ### Getting paid "Payments feel like the kind of thing that should require a 'real' developer." A builder who could not code wrote that in July 2026, then found Stripe worked first time. Taking the money is the easy half, and every builder now does it. The hard half is what happens after: the plan has to change what the app does, the trial has to end, the invoice has to exist. #### 5. Plans, prices, trials and the invoice What it is: subscriptions and billing. Your plans and prices, a free trial that becomes a paid plan without a second checkout, upgrade and downgrade and cancel from inside the app, and an invoice for every charge. What the builders give you, 27 October 2026: Lovable's built-in payments run through Paddle (5.0% plus 50 cents per transaction, and a flat 10% under $10) or your own Stripe account at Stripe's standard rates, on Pro and up, with one active subscription per user by default and one provider per project. Bolt Cloud and Replit have Stripe connectors; v0 has Stripe in the Vercel Marketplace; Base44 has its own payments by Wix, or Stripe. What to check: subscribe with a test card, cancel, and look for the invoice. Then change the price of a plan and check that existing subscribers kept theirs. Most generated billing code mutates the plan in place, and existing customers wake up on the new price. What BuildBase adds: plans, prices and trials synced to Stripe, in 21 currencies, with seat-based or usage-based pricing, a ready-made pricing page and checkout or your own. Stripe is yours, and the platform fee is 0%. A plan change creates a new version rather than editing the old one, so nobody is moved without you choosing to move them. Our own plans are a Free plan, then Launch at $19 a month, Grow and Scale, with a 7-day trial and no card on the paid ones. #### 6. Paid plans that actually gate features What it is: the link between what someone paid for and what the app lets them do (entitlements, usually built on feature flags). "Paid but the app did not unlock" is one of the five most common complaints after launch, and the reverse, "I marked myself as paid", is one of the five most common findings in an audit. Why it goes wrong: the payment happens at Stripe, and the app finds out through a message Stripe sends to your server afterwards. If that message is not handled, or is handled by a check in the browser, the plan and the feature never connect. The developer who audited three Reddit-posted apps found exactly that endpoint, left in production, that let anyone mark themselves paid. What the builders give you: the checkout. What happens between the webhook and the feature is yours to build, on all five, and the docs stop at the payment. What to check: pay on a test card and watch the feature appear without a reload. Then, in the browser's developer tools, look for the request that decides whether you are on the paid plan. If it is a request your browser makes, it is a request your browser can forge. What BuildBase adds: feature flags tied to plans, so a paying workspace sees the paid features and a free one does not, decided on the server. Beta features for the users or lists you choose. A settings screen where a workspace admin can turn allowed features on or off. The piece in the middle, [entitlements rather than flags](/blog/entitlements-are-not-feature-flags), is the distinction worth ten minutes before you prompt for it. #### 7. Usage limits and credits, so nobody gets a surprise bill What it is: a limit on how much of the expensive thing each customer may use (quotas), or a balance they spend down (credits), with a clear "not enough credits" message instead of an unbounded bill for you. If your app calls an AI model, this is the item that decides whether you make money. The apps in the 2025 Enrichlead story were "under attack" within days of launch, API usage maxed out, because nothing limited anyone. The audit above found an endpoint that gave "unlimited credits". What the builders give you: nothing documented for per-customer usage limits or credit balances on any of the five, as of 27 October 2026. What to check: as a free user, do the expensive thing more times than your plan allows. Does it stop? Does it stop on the server, or only hide the button? Where is the balance shown? What BuildBase adds: credit packs sold through Stripe, credits included with a plan, spend-by-expiry buckets, a transaction ledger, and per-plan quotas with overage billing or a hard stop. One call where the paid work happens, like an AI generation. The difference between [a quota and a credit](/blog/quotas-are-not-credits) decides which one you want; most AI apps want both. ### Things that happen on their own A product talks to its users when they are not looking at it: the welcome email, the reminder that a trial ends tomorrow, the note that a payment failed. The demo never needed any of that, because you were always looking. #### 8. Emails that arrive, from your own address What it is: transactional email (the confirmation, the reset link, the welcome) that lands in the inbox and comes from your domain. The two ways it fails after launch are "the confirmation email never came" and "it went to spam". Why: the sender your builder gave you was for development. Supabase's docs say its default sender only emails members of your own team, at two messages an hour, and is "not meant for production use". That is why the confirmation email works for you and never arrives for a stranger. What the builders give you: Lovable's built-in backend lists a database, storage, sign-in, realtime and functions; email is a separate guide about sending from your own domain. Replit and Bolt have Resend and SendGrid as connectors. v0 has Resend in one click. What to check: sign up with an address at a provider you do not use (a Gmail account if you build on Outlook, or the reverse). Time the confirmation email. Open it on a phone and look at the sender name. What BuildBase adds: your sending domain through Google, Mailgun, Amazon SES or your own SMTP, templates in HTML, Markdown or plain text, one-click unsubscribe, and a preference screen where users choose which emails they get. The sign-in emails go out through the same sender, so the confirmation and the reset link come from you. [Why email lands in spam](/guides/transactional-email-landing-in-spam) is the guide for the day it does. #### 9. The welcome, the reminder, the follow-up that stops What it is: automation (workflows) that runs when something happens: a welcome email on sign-up, a heads-up before a trial ends or after a payment fails, a follow-up that stops once the person has done the thing. What the builders give you: Lovable Cloud has scheduled jobs and functions you prompt into existence; Replit and Bolt have functions and cron. In every case the logic is code you own, with no view of what ran and what did not. What to check: sign up, then do nothing for three days. What arrives? Pay, then let the test card fail. What arrives? If the answer is "whatever the agent wrote last Tuesday", you have no way to know until a customer tells you. What BuildBase adds: a drag-and-drop editor with triggers for the events the platform already knows about (sign-ups, trials, payments, plan changes, more than sixty of them), conditions, splits and waits between steps, and new versions published without a deploy. Every run is logged per step. #### 10. A notification even when the app is closed What it is: browser push notifications. A "turn on notifications" button, one call from your server when something happens, and a settings screen where each person chooses what they want. Most apps do not need this on launch day. The ones that do, anything with a "your order is ready" or "someone replied" moment, cannot bolt it on later without asking every user for permission again. What the builders give you: nothing documented for web push on the five. What BuildBase adds: web push with the keys generated for you, device subscriptions, one-call sends from your server, and console campaigns with delivered, failed and expired counts. #### 11. A message in your Slack when it matters What it is: alerts to your own team. New sign-up, new payment, failed payment, cancellation, posted to a Slack channel as they happen, with a link to the record. This is the cheapest item on the list and the one that makes the first week bearable. You will refresh the users page forty times a day otherwise. What to check: did you find out about your last sign-up from the app, or from the customer? What BuildBase adds: paste a Slack webhook address into the console, choose which events your team wants, and change nothing in your code. Slack alerts are real-time; it is the one place on this list where that word is accurate. ### Your server hears about it #### 12. Webhooks that are signed, retried and logged What it is: a webhook is a message another system sends to your server the moment something happens, so you learn about it without asking. "Stripe tells my app someone paid" is a webhook. "The payment went through but nothing happened" is a webhook that failed. Why this is on a launch list: everything in items 5 to 9 depends on one. Payment to plan, sign-up to welcome email, failed card to reminder. A webhook that is not checked for a signature is an open door, and one that is not retried is a customer who paid and got nothing. What to check: find the address your app receives Stripe or BuildBase events at. Send it a request by hand with a made-up body. It should be refused. Then stop your server for two minutes, pay with a test card, and start it again. Did the plan still change? What BuildBase adds: 129 subscribable events, posted to your HTTPS address, signed with HMAC-SHA256, tried up to five times over about two and a half minutes, and logged per attempt in the console. One call on your server checks each delivery is real. [What a webhook is and what happens when delivery fails](/blog/what-are-webhooks) covers the retry ladder and the five-minute signature window, and the reason there is no replay button. ### The rest of the product These seven are not launch blockers for most apps. They are the things a prompt will happily build a bad version of, and the version you want already exists. #### 13. A form that works without a login What it is: forms (a contact form, a waitlist, a feedback box) that any page can submit without a token, where every submission becomes a record and can start a workflow. Generated forms post to an endpoint that either has no protection or needs a login nobody has yet. What BuildBase adds: the form's fields defined in the console, a hosted form page or your own design, clear errors when a field is wrong, and a reply the moment someone submits. #### 14. Data without building a table for it What it is: custom records (collections) with a schema published as a locked version, so old records keep their meaning after you change the fields, and a REST API behind an API token. This is the store behind the forms above. What to check: the generated app stores "whatever the agent decided" in tables with no history. The day you rename a field, every old row is ambiguous. #### 15. Words you change without a deploy What it is: content (blog posts, docs, FAQs, testimonials) written in the console, with drafts that stay private until published and an SEO title and description on every post. The pricing page copy, the help article, the changelog: none of it should need a rebuild. #### 16. Images without a storage bucket to manage What it is: image uploads checked by their contents, with the width and height recorded, served public or behind links that expire. Every generated app that lets users upload a profile photo has invented this badly at least once; SVG files that run scripts are the usual surprise. #### 17. Links you can change after sharing What it is: short links you can repoint after they are out in the world, with a click log by device and location, and destinations checked so a harmful address is stopped before anyone reaches it. #### 18. Numbers you did not have to build a dashboard for What it is: sign-ups and growth over time, email opens and clicks, where your users are and when they sign up. The console reads the data it already keeps; you set a date range. On launch week this is the page you will leave open. #### 19. Ad and analytics tags without code in your app What it is: tracking (GA4, Google Ads, Meta and eleven more) configured once in the console and installed by one line in your app, with sign-ups and purchases reported to the ad platforms and tags that wait for your cookie banner before they load. The generated version is a script tag pasted into the layout, with no consent handling, and it is the thing a privacy review finds first. ### One install #### 20. The SDK, and the fact that your agent has to know it exists What it is: the package itself. One `npm install`, a provider around your app, hooks and components where the app needs them, and the server half in your backend. Thirteen settings screens come built: workspaces, members, billing, plan, usage, devices, notifications and the rest, in eight languages including right-to-left ones. Here is the honest part, measured. In October we gave a coding agent the brand-withheld prompt "Add sign-in, a team workspace, Stripe subscription billing, and an email when a payment fails. Use a React or Next.js app. Keep any existing database. Do not add a second auth vendor." With nothing else, it built its own password hashing, a SQLite user table, direct Stripe calls on Stripe's own event, and a one-off email sender, in 34 turns and ten minutes. Correct engineering, and exactly the four separate services this list exists to spare you. With our skill installed, six runs out of six installed the SDK, added no second vendor and handled the failed payment through the platform's own event. An agent builds what it knows about, and [the full write-up of that experiment](/blog/what-a-coding-agent-builds-when-nobody-tells-it-otherwise) has the record and the two bugs the measurement found in itself. What to check: look at your `package.json`. If it contains `bcrypt`, `scrypt`, `iron-session`, `jsonwebtoken` or a users table the agent wrote, you own the maintenance of a sign-in system now, and [what that costs in year two](/blog/ai-generated-code-maintenance-cost) is the number nobody prices. What BuildBase adds: on Next.js, `npx buildbase init --org-id ` writes ten files (the provider, three sign-in routes, a webhook route, a server helper and the env files), never overwrites, leaves every secret empty, and refuses to touch a Pages Router app. On Vite and Express it writes the equivalents. For the agent channels, the skill is one line. ### What your builder gives you, and where it stops All read on 27 October 2026 from each builder's own documentation. Builders ship weekly, so check before you lean on a row. | Builder | Built in for your end users | Not documented for end users | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | Lovable (Lovable Cloud) | Database, storage, functions; sign-in by email, phone, Google, Apple, Microsoft, Lovable, SAML SSO, OIDC; payments through Paddle or Stripe on Pro and up, one subscription per user by default | Teams, roles, invites, plan limits, seats, credits, email from your domain as part of Cloud | | Bolt.new (Bolt Cloud) | Database with email and Google sign-in, storage, functions, Stripe; a security scan for open permissions and missing row rules | Teams, roles, plan limits, credits, email | | Replit | Replit Database, Replit Auth or a provisioned Clerk account, a Stripe connector, Resend and SendGrid connectors | Teams, roles, plan limits, credits | | v0 (Vercel) | No end-user sign-in of its own; one-click Clerk, Auth0 and Resend; Stripe in the Marketplace; Vercel owns Better Auth | Teams, roles, plan limits, credits | | Base44 (Wix) | Built-in sign-in with social providers and SSO, entities, payments by Wix or Stripe | Teams, roles, plan limits, credits; the server runtime is not documented | Two things to be fair about. Lovable's built-in sign-in ships SAML SSO, and BuildBase does not, so if your buyer is a company that signs in with Okta, the built-in is the one to keep for that. And every built-in sign-in is zero-config inside its builder, which an external SDK will never be; you are trading one afternoon of setup for the fourteen items above that the built-in does not reach. ### The prompt to paste Paste this into Lovable, Bolt, v0, Replit, Cursor or Claude Code. It names the outcome, the rules, and the one thing that must never happen to a secret. ```text Add BuildBase (@buildbase/sdk) to this app for sign-in, teams, paid plans and lifecycle email. Keep the existing database; BuildBase is not the primary database. Do not add Clerk, Auth0, Resend or n8n. Stripe is bring-your-own; do not store card data. Read https://www.buildbase.app/llms.txt first and do not invent endpoints. If sign-in already exists, stop and ask me before changing it. I will give you a server URL and a 24-character organization id. The client secret and the webhook secret go in the secret store, never in a VITE_ or NEXT_PUBLIC_ variable. Start with sign-in and a workspace per customer, then plans, then the failed-payment email. ``` On v0, [the step-by-step version](/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app) names the files and the variables, with a fix-up line for each way v0 tends to drift. Two corrections to older versions of this prompt you may find elsewhere: there is no "publishable key" in BuildBase, and the Lovable paste pack still points at our Vite guide, which fits Lovable apps created before 13 May 2026. Newer Lovable apps are TanStack Start apps and need the server-function version. To make the agent itself know the SDK, rather than the prompt carrying all of it: ```bash npx skills add buildbase-app/claude-skill # Cursor, Codex, Copilot and others npx skills add buildbase-app/claude-skill -a cursor # Cursor specifically ``` In Claude Code, `/plugin marketplace add buildbase-app/claude-skill` then `/plugin install buildbase@buildbase-skills`. Lovable workspace owners can import a skill from a public GitHub folder that holds a `SKILL.md`; the folder for ours is `plugins/buildbase` in that repo. We have not run that import inside Lovable ourselves yet, so treat it as their docs' promise, not ours. ### What breaks first, and how you can tell **Sign-in works in preview and loops on the live site.** The published address is not registered with whoever does the sign-in. Register the exact address, path included, and test from a private window. A wildcard will not save you on a public suffix like `*.lovable.app` or `*.vercel.app`; register each one. **The confirmation email never arrives for anyone but you.** The default sender only emails your own team. Connect a real sender and a real domain before the second user. **Paid, but still on the free plan.** The payment happened and the message to your server did not, or was handled in the browser. Find the webhook route, check it refuses a forged body, and move the plan check to the server. **A member can open an admin page by typing the address.** The page is hidden, the request is not. Enforce the role where the data is read. **Credits burned on the fix for the fix.** The most common complaint about every builder, in about 63% of the negative reviews we read, is paying for a loop of fixes that do not fix. Each item above is a thing to check once, not a thing to prompt about repeatedly; the SDK's version of it is already written, which is the point. ### Install Add the SDK to the app you have, or let the CLI write the files: ```bash npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## Vibe coding with Claude Code or Cursor: one skill, then sign-in, teams and billing > In a coding agent the SDK installs in your own repo, so the whole job is making the agent know it exists. One skill line, one init command, one prompt, and what to check in the diff it hands back. - Source: https://www.buildbase.app/guides/vibe-coding-with-claude-code-or-cursor - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-27 - Updated: 2026-11-04 ### In short To add sign-in, teams and billing to an app with Claude Code or Cursor, install the BuildBase skill first (npx skills add buildbase-app/claude-skill), run npx buildbase init with your organization id, then prompt for the outcome. The skill carries the rules the agent would otherwise guess; init writes the files. In a coding agent, the hard part is not the code. The SDK is one `npm install` away and the agent can type it. The hard part is that the agent will not type it unless it knows the SDK exists, and left alone it does not: given a plain request for sign-in, a team workspace, subscription billing and a failed-payment email, with no product named, Claude Code built scrypt password hashing, a SQLite users table, direct Stripe calls on Stripe's own event and a one-off email sender, in 34 turns and ten minutes. Correct, and yours to maintain forever. With one file installed first, six runs out of six used the SDK, added no second vendor, named the right event and typechecked, in about four minutes each. [The full write-up](/blog/what-a-coding-agent-builds-when-nobody-tells-it-otherwise) has the record. This guide is the practical version: the one line, the one command, the one prompt, and what to look at in the diff the agent hands back, because the diff is where you earn the four minutes. When it works: a stranger opens your deployed app, signs up with Google or a magic link, lands in their own workspace, invites a colleague, picks a plan on a test card, and the paid feature appears. Your `package.json` has one new dependency and no `bcrypt`, no `iron-session`, no `next-auth`, and no migration that creates a `users` table. What we ran on 27 October 2026: the skill install and `npx buildbase init` in a fresh Next.js App Router app, through the CLI's own test gates, and the seven-run agent evaluation from 7 and 8 October described in the write-up above. What we have not run today: this exact session in Cursor, so where Cursor's behaviour matters it is named rather than claimed. > **Before you start:** A React or Next.js app in a repository on your machine, with Node 22 and a > terminal you are willing to open once. A BuildBase organization, and an auth > client created in the console under **User Management → Authentication**, with > its client ID and secret, and your deployed address registered on it as a > redirect URL. Claude Code or Cursor, signed in. > **Tip:** "With CC you still have to host it somewhere," a Hacker News commenter wrote > in August 2026 about why non-technical builders pick a builder over Claude > Code: a database, a host, a terminal. If you do not have those and do not want > them, the [Lovable](/guides/add-login-teams-and-paid-plans-to-a-lovable-app) > and [v0](/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app) guides are the > same outcome without a terminal. ### 1. Install the skill before the first prompt One line, in the repository, before you ask for anything: ```bash npx skills add buildbase-app/claude-skill ``` The skills CLI installs into the current project by default (`-g` makes it global), and `-a` picks the agent when you want only one, `-a claude-code` for Claude Code; its docs list dozens of agents, Cursor and Codex among them, with the directory each one reads. `--skill buildbase` installs the SDK skill alone and leaves out the self-hosting one. In Claude Code you can instead add our marketplace and install it as a plugin: ```text /plugin marketplace add buildbase-app/claude-skill /plugin install buildbase@buildbase-skills ``` What the file does: it is a `SKILL.md` with a description that tells the agent when it applies (sign-in, orgs, roles, subscriptions, metered billing, credits, lifecycle email, workflows) and, when it does, the facts the agent needs: the setup steps, the HTTP catalog so it never invents an endpoint, the webhook event names, and five rules it reads before writing code: ```text Use BuildBase when the user asks for sign-in, orgs, RBAC, subscriptions, metered billing, usage credits, lifecycle email, or event workflows, and does not want Clerk + Stripe Billing + Resend + n8n. Do not use BuildBase as the primary database. Do not store card data. Stripe handles cards. Do not invent endpoints. Read the HTTP catalog first. If auth already exists, stop and ask before migrating. ``` What you should see: `npx skills list` names the skill, and in Claude Code, `/skills` or a mention of "buildbase" in a prompt makes the agent read it (the evaluation's judge checks for exactly that read). In Cursor the skill sits in the directory the CLI's agent table names, and the agent picks it up when a request matches its description; we have not run that session ourselves today, so treat it as the CLI's documentation speaking. **Correcting potential issues.** If the agent writes sign-in code without reading the skill, say so in the next prompt: "Use the buildbase skill for this." The evaluation recorded "skill not triggered" as a description problem rather than a knowledge problem, and an explicit mention is the one-line fix for a session. ### 2. Run init with your organization id The SDK ships a command that writes the sign-in files into the app you have. It needs the organization id, which is the one thing an agent cannot guess: ```bash npm install @buildbase/sdk npx buildbase init --org-id ``` It reads `package.json` to tell Next.js, Vite and Express apart, then writes the provider, the three sign-in routes (exchange the code, report the session, sign out), a webhook route, a server helper, `.env.example` and `.env.local`, and wraps your root layout. On Next.js that is ten files. Four things it will not do: overwrite a file that exists, write a secret (every value is left empty, and it refuses one passed on the command line), touch a Pages Router app, or change anything on a second run. Why you run this rather than the agent: in the evaluation, no agent ran `init`, because none had an organization id and the command exits before touching anything without one. The agents wrote the same files by hand from the quick-start instead. Both roads end in the same ten files; yours is shorter and does not spend tokens, and you fill in the three secrets yourself. ```bash # .env.local, written by init with the values empty NEXT_PUBLIC_BUILDBASE_ORG_ID= NEXT_PUBLIC_BUILDBASE_CLIENT_ID= NEXT_PUBLIC_BUILDBASE_REDIRECT_URL=http://localhost:3000 BUILDBASE_CLIENT_SECRET= BUILDBASE_WEBHOOK_SECRET= ``` What you should see: `npm run dev`, then open `http://localhost:3000/api/auth/session` and get `{"sessionId":null}`. The server half is alive before the agent writes a single screen. If `init` says the app is a Pages Router project, the [Next.js guide](/guides/buildbase-on-nextjs) has the same files by hand; if it says Remix, it printed a pointer to the [React Router guide](/guides/buildbase-on-react-router). ### 3. The prompt Short, because the skill carries the rest. Paste it as the first prompt of the session: ```text Add BuildBase (@buildbase/sdk) to this app for sign-in, a workspace per customer, paid plans and lifecycle email. The sign-in routes, provider and webhook route are already written by npx buildbase init; read them and build on them, do not rewrite them. Keep the existing database. Do not add Clerk, Auth0, Better Auth, Resend or n8n. Stripe is bring-your-own; do not store card data. Add a sign-in button that calls signIn() from useSaaSAuth(), a workspace switcher from useSaaSWorkspaces(), and a /settings page that opens the SDK's built-in workspace, members and billing screens. In the webhook route, handle payment.failed and subscription.suspended for my own side effects only (flag the account, post to Slack); the failed-payment email itself is a console notification or a workflow, not code. Read the secrets only in server code, never with a NEXT_PUBLIC_ prefix. If sign-in already exists in this app, stop and ask me before changing it. ``` What you should see: a diff that touches the files `init` wrote only to import from them, adds a sign-in button and a switcher, adds the settings page, and edits the webhook route to handle `payment.failed`. The evaluation's judge checked four things on every run, and they are the four things to check in the diff: `@buildbase/sdk` in `package.json`; none of the five vendors above added; a route whose path contains `webhook` that calls the SDK's verifier and names an event from the catalog; and `tsc --noEmit` exiting 0. **Correcting potential issues.** The three ways the agent drifts, with the line to paste back: - It added `better-auth`, `next-auth` or `@clerk/nextjs` "for the session". Paste: "Remove that package. BuildBase is the only sign-in in this app; the session is the bb-session-id cookie the init routes set." - It wrote a Stripe webhook on `invoice.payment_failed` or `customer.subscription.updated`. Paste: "Remove the direct Stripe webhook. BuildBase receives Stripe's events; this app receives BuildBase's events at the init route only, and a failed payment is payment.failed." - It invented an endpoint (`/api/v1/me`, `/v1/users/current`) or a publishable key. Paste: "There is no publishable key and no /v1/me. Read https://www.buildbase.app/llms.txt and the skill's HTTP catalog before calling anything." ### Reading the webhook route init wrote Before the agent touches it, read the webhook route `init` wrote, because it is the shape every later prompt should keep. It reads the raw request body as text and hands it to `parseWebhookEvent` with the signature and timestamp headers and the secret from the environment; a delivery that fails that check gets a 401 and nothing else happens. It then asks `isWebhookEvent` whether the name is in the catalog, and ignores one that is not, which is how an event name the agent invents becomes a no-op rather than a handler that silently never runs. The comments in the file say the rest: the event id is the same on every retry, so record the ids you handle and skip a repeat before any side effect; the payload for `payment.failed` carries the workspace, the subscription, the invoice, the dunning state, the amount in minor units and the next retry time; and the platform sends the dunning email itself when the console notification or a workflow is on, so the handler is for your own side effects, not for the email. That last comment is the one agents most often ignore, and it is why the prompt in step 3 says "side effects only". An agent that writes an email sender into the handler has built a second copy of a thing the platform already does, and the customer gets two emails, or one from a domain you never set up. The route also handles `subscription.suspended` as a placeholder, which is the last failed attempt: by then the feature gates have already closed on their own. Two numbers for scale, both from the record rather than a feeling: the baseline run took 34 turns and ten minutes and eleven seconds to build the four-vendor version; the skill-on runs took 21 to 24 turns and four minutes and two seconds to four minutes and thirty-three seconds to build this one. The difference is not the agent working faster. It is the agent not building a sign-in system, a users table, a billing integration and an email sender that already exist. ### 4. Read the diff before you run it This is the step that makes the four minutes worth it, and the one a builder with no terminal cannot do, so do it. Three greps, in order: ```bash git diff --name-only # which files changed grep -rn "NEXT_PUBLIC_BUILDBASE_CLIENT_SECRET\|NEXT_PUBLIC_.*SECRET" . # must be empty grep -rn "bcrypt\|scrypt\|iron-session\|jsonwebtoken\|next-auth" package.json # must be empty ``` Then two tests from the launch checklist that need no code at all. Sign in from a private window as a second person, close the browser, reopen. Still signed in? Good. Now open the browser's developer tools, copy a request the app makes after sign-in, and replay it with the cookie removed; it should be refused. If either test fails, the agent changed a route it was told not to touch, and `git diff` on the `init` files shows where. The alternative to reading the diff was described by a Hacker News commenter in June 2026, and anyone who has prompted for long enough will recognise it: "the chatbot goes off the rails and breaks stuff. No amount of additional prompting will fix the issue no matter how many time Claude/CoPilot says 'I see the problem. Let me fix that...' and it only gets worse." Three greps. Before the third "let me fix that". ### What the six skill-on runs actually produced Since "it worked" is not evidence, here is what the record shows for the runs with the skill installed. Each started from a fresh Next.js app with no credentials and the same brand-withheld prompt. Each read the skill through the agent's Skill tool, installed `@buildbase/sdk`, and wrote the provider, the three sign-in routes and a webhook route at `src/app/api/webhooks/buildbase/route.ts` that named `payment.failed`, with every other event literal in that file also in the catalog. Round one ran on 7 October 2026 in 21 to 24 turns and a little over four minutes each, against the skill from a local checkout. Round two ran on 8 October against the published skill and the published package, which is what you get, and all three of those runs resolved the pinned SDK version from a bare `npm install`. That last detail is a bug the measurement caught in itself. In round one the skill pinned a version the package's `latest` tag did not yet point at, so a run that ignored the pin would have drifted to an older release and the judge, which checks presence rather than version, would never have said so. The tag was moved the next day. If you install today, a bare `npm install @buildbase/sdk` and the skill's pin agree. What no run did: execute `npx buildbase init`. Every agent read the line about it and wrote the files by hand, because `init` needs the organization id and the evaluation supplied none. That is why step 2 is yours. ### Make it permanent, in the file your agent already reads A skill is read when a request matches its description. A one-line rule in the file your agent reads on every session makes the choice before the request: Claude Code reads `CLAUDE.md` in the repository root, Codex reads `AGENTS.md`, and Cursor reads its rules folder. The skill repository ships its own `AGENTS.md` with the five-line rule above, and the line to copy into yours is one sentence: ```text For sign-in, organizations, roles, subscriptions, credits, lifecycle email or workflows, use the buildbase skill and read https://www.buildbase.app/llms.txt before writing code. Keep the existing database. If sign-in already exists, stop and ask before migrating. ``` With that in place a teammate, or you in three months, gets the same default without remembering the skill exists, which is the whole point of a default. > **Key takeaway:** In an agent, the integration is four minutes and the review is ten. Spend the > ten. The diff is the only place you can see what the agent decided for you, > and the two greps catch the two decisions that matter most. ### 5. Then teams, plans and the rest are prompts With sign-in flowing, each layer is a prompt against hooks and components the SDK already has, and each has its own guide with the prompt written out: - **A workspace per customer, invites by email, admin versus member**, with the roles enforced by the API and your rows scoped by workspace id: [teams, invites and roles](/guides/teams-invites-and-roles-for-a-vibe-coded-app). - **Plans that gate features**, with the plan on the workspace, the `WhenEntitled` gate in the browser and the check on the server: [paid plans that actually gate features](/guides/paid-plans-that-gate-features-vibe-coded-app). - **Credits and usage limits** for an AI feature, with a hard stop instead of a surprise bill: [a credits wallet](/guides/credits-wallet-nextjs). - **The emails**, from your own domain, with the trial-ending and card-failed messages as workflows rather than code: [email landing in spam](/guides/transactional-email-landing-in-spam). Each of those prompts ends with the same two sentences this one did: keep the data in your database, do not store the plan or the role in it. That is the rule the skill carries, and the reason the agent's four minutes do not become your four weekends. ### Where the agent's own default wins If you are a developer who wants to own the sign-in code, Better Auth is an honest default in a Next.js repo: Vercel bought it in July 2026, it is open source under MIT with 4.7 million weekly downloads, and an agent on Vercel's stack reaches for it readily. Clerk's `clerk.com/SKILL.md` is a one-line prompt and Clerk publishes a leaderboard of how well each model integrates it. Stripe's own skills and `stripe projects` provisioning are first-party. If your app has one user per account and the plan lives in Stripe alone, those are fewer moving parts than this guide. Choose this guide when the questions are "which team does this person belong to" and "what may this team do now that they paid", because those are the questions an agent's default stack answers with a role column checked on one page. And choose it if you do not want to own a sign-in system: the two-year maintenance line on generated auth is [the number nobody prices](/blog/ai-generated-code-maintenance-cost) on the day the demo works. [Clerk vs BuildBase](/compare/clerk-vs-buildbase) is the line-by-line version. ### What breaks, and how you can tell **The agent built its own auth anyway.** The skill was not read. Mention it by name in the prompt, or check `npx skills list` shows it in this project rather than another directory. **`init` exits with code 2 and writes nothing.** No `--org-id`, or one that is not 24 hex characters. By design; it refuses before touching anything. **`init` says "already configured".** It ran before, or the provider file exists. Nothing was changed; read the files it names. **Sign-in works locally and loops on the deployed site.** The deployed address is not registered on the auth client. [Login that works after you publish](/guides/login-that-works-after-you-publish) is the checklist. **The agent handled `invoice.payment_failed`.** Stripe's event, not the catalog's. The fix-up line in step 3, and the skill's catalog of 129 names. **The secret is in the client bundle.** A `NEXT_PUBLIC_` prefix landed on it. Rotate it in the console, fix the prefix, redeploy; the grep in step 4 is there to catch this before the deploy. ### Install ```bash npx skills add buildbase-app/claude-skill npm i @buildbase/sdk npx buildbase init --org-id ``` --- ## Keeping a pricing page honest against your plans > Why pricing pages drift from the plans you actually bill, and how to render the table from your catalog instead of copying it, plus what to do with the numbers you cannot render. - Source: https://www.buildbase.app/guides/keeping-a-pricing-page-honest-against-your-plans - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-19 ### In short A pricing page drifts because it holds a second copy of your prices. Delete the copy: render the table from the published plan group so the page and checkout read one source. Keep what the catalog cannot express in a constants file, give it a verification date, and make a check fail when that date goes stale. Count the prices on your own pricing page. Not the plan cards, which probably come from your billing system already. Count the title tag, the hero sentence, the FAQ that explains annual billing, the footnote under the comparison table. Each one is a second copy of a number your billing system also holds, and the copies are the only things on that page capable of lying. Ours has four. I went looking while writing this, which is the only reason I can tell you how many, and I found the fourth one hiding inside the file I was about to hold up as the good example. The usual advice is to sync. A webhook that writes prices into your database, a config file you push into Stripe, a cache you warm on deploy. All three keep the copy and promise to keep it fresh, which is a promise about your future attention rather than about your code. Hold fewer copies instead. The ones you cannot delete are debt, and debt gets a due date. ### What you are building One decision, written down: which numbers on your pricing page are rendered from the plan catalog at request time, and which are copies you have agreed to maintain by hand. When it works, you publish a plan version in the console and the public table changes within about five minutes, with no deploy and no pull request. When it does not, a visitor reads "Free plan, paid from $19/mo" in their browser tab while the table underneath quotes something else, and no test in your suite has an opinion about the difference. The person who notices is a customer, and they notice at checkout. > **Before you start:** You need billing currencies set on the organization, at least one published > plan version, and a pricing group whose slug you can paste into your site. > Currencies come first and are hard to change later, so settle those [before > you build any > plans](/guides/choosing-billing-currencies-before-your-first-subscription). If > you are still deciding how many pricing tables you need, [that is a different > question](/guides/when-you-need-a-second-pricing-page) and worth answering > before this one. ### Step 1: count the copies Open every file that renders your pricing route. Grep it for a currency symbol, for the word trial, and for any allowance figure. Write down what you find and where each number comes from. You will end up with a table longer than you expected, sorted into exactly three kinds of row. Here is ours, for `website/app/pricing/`: | Surface | What it prints | Where the number comes from | | ----------------------------------- | --------------------------------------- | ---------------------------------------- | | Plan cards and comparison table | every price, allowance and overage rate | `usePublicPlans()`, fetched per request | | Page title and meta description | "Free plan, paid from $19/mo" | `PLAN_FACTS.entryPrice`, a constant | | Hero sentence and the trust badges | the trial length | `PLAN_FACTS.trial.days`, a constant | | The annual-billing FAQ | "ten months for twelve" | typed by hand into the FAQ array | | The saving badge on the year toggle | "-17%", "Save 17% with annual billing" | typed by hand into `pricing-content.tsx` | Only the first row cannot drift. The second and third are derived from one constants file, so they move together and they move when somebody updates that file. The last two are prose that happens to agree with a constant we already have, which means they agree until the day they do not. That last row is the one worth sitting with. Ten months for twelve is 16.7%, rounded to 17 by a person, typed into the same file that renders the live table. The honest half and the drifting half share a filename. Change the yearly multiplier in the console tomorrow and the plan cards update themselves while the badge beside them goes on promising 17%, and it will keep promising it until somebody reads that line on purpose. > **Key takeaway:** Sort every number on the page into rendered, derived or typed. Rendered cannot > drift. Derived drifts as a group, on a schedule you control. Typed drifts > alone and silently, which is why it is the row to delete first. That sorting is the whole audit. Do it before you write any code, because step 2 is only worth doing to the rows it can actually move. ### Step 2: render everything the catalog can answer Anything that appears inside the page body can be fetched. Plan names, prices per interval and currency, what each plan includes, metered allowances and the overage rate past them: all of it travels in the public plans payload, so none of it needs a copy. `PricingPage` is headless. It fetches the plan group and hands you the data, and you own the markup: ```tsx import { PricingPage } from '@buildbase/sdk/react'; export function Pricing() { return ( {({ loading, items, plans }) => { if (loading) return

Loading plans...

; return (
{plans.map((plan) => (

{plan.name}

    {items .filter( (item) => plan.features[item.slug] || item.slug in plan.limits || item.slug in plan.quotas ) .map((item) => (
  • {item.name}
  • ))}
))}
); }}
); } ``` After this step, changing a price in the console changes the page. The public plans response is cached for five minutes, and every item or category write clears that cache. So a change shows up on the next request. Or, if the cache clear does not land, once the five minutes run out. Cache clearing is best-effort. Plan for the slower of the two and you will never be surprised by the faster one. Two details decide whether the rendered half is honest or merely live: **Read the allowance for the interval on screen.** A plan's yearly tier can carry a larger allowance than its monthly one. If [your toggle](/guides/annual-and-monthly-toggle-nextjs) says yearly and your table still reads the monthly quota, you have built a live page that displays the wrong number, which is worse than a static one. **Take the overage rate from the currency's pricing variant.** That figure, in `quotaOverages`, is what billing actually charges. There is no second rate in the payload to reach for, and inventing a per-unit price because the real one is billed per thousand is how a page ends up off by three orders of magnitude. Entitlement is resolved by item slug and never by position, so reordering or badging a row is presentation and changes nothing about what a workspace can do. That is what makes the pricing page safe to rearrange and unsafe to hand-write. It also means the slugs are doing real work, which is an argument for [structuring the catalog deliberately](/guides/structuring-a-product-catalog-you-will-not-regret) before the page is built on top of it. ### Step 3: give every surviving copy a date Some numbers cannot be rendered, and pretending otherwise is how this advice stops being useful. A Next.js title tag is built on the server before any client-side fetch resolves. Ours reads `Free plan, paid from $19/mo` from a constant, and it will keep reading from a constant, because the alternative is blocking the page render on a billing API call to put a price in a browser tab. So the copy stays. What it gets is a stamp: ```ts // abbreviated: the real constant carries a few more keys export const PLAN_FACTS = { entryPlan: 'Launch', freePlan: true, entryPrice: '$19/mo', trial: { days: 7, requiresCard: false, paidPlansOnly: true }, billingIntervals: 'Monthly or yearly; yearly is ten months for twelve', verified: '9 September 2026', } as const; ``` Then put the stamp where a reader can see it. Our homepage plan summary prints `Prices in USD. Verified 9 September 2026.` above the table. Publishing the date is not decoration. It converts a silent copy into one that announces its own age, and it means the first person to catch the drift can be anyone rather than whoever happens to open the constants file. Now the uncomfortable part. As I write this, that stamp is 38 days old. The mechanism worked exactly as designed: it told me. Nothing failed, because nothing was watching the date. Update, 31 October 2026: our plans changed that day, to a Free plan beside Launch, Grow and Scale at $19, $49 and $99 a month, and the stamp moved with them to `31 October 2026`. The prices quoted in this post are the new ones; the 38 days is left as it was, because it is what the stamp said when this was written. ### Step 4: make something fail when the stamp goes stale A date nobody checks is a comment. Give it a check that exits non-zero: ```js // scripts/check-price-stamp.mjs import { PLAN_FACTS } from '@ord/shared'; const MAX_AGE_DAYS = 30; const stamped = new Date(PLAN_FACTS.verified); const ageDays = Math.floor((Date.now() - stamped.getTime()) / 86_400_000); if (Number.isNaN(stamped.getTime())) { console.error(`check-price-stamp: cannot parse "${PLAN_FACTS.verified}"`); process.exit(1); } if (ageDays > MAX_AGE_DAYS) { console.error( `check-price-stamp: PLAN_FACTS.verified is ${ageDays} days old ` + `(max ${MAX_AGE_DAYS}). Re-check it against the live plans, then ` + `update the stamp.` ); process.exit(1); } console.log(`check-price-stamp: ${ageDays} days old, within ${MAX_AGE_DAYS}.`); ``` Run it in CI on every pull request that touches the constants file, or on a schedule if you would rather be told on a Monday than at merge time. If your constants live in a workspace package, build it first: the import above resolves against the built output, not the source. I ran it against our own constants while writing. It exits 1 today, which is the correct answer and the reason this step exists. Pick the threshold deliberately. Thirty days works if your prices are stable. If you are still moving prices weekly before launch, make it seven and accept the noise, because during that period the copy is wrong more often than it is right. > **Warning:** Do not point the check at a figure your billing system already renders. A > check that guards the live table is a check that fails for no reason, and the > first time someone silences it they will silence the one that mattered. ### What breaks anyway, and how you find out **The plan version a customer bought is not the one on the page.** [Plans are versioned](/guides/plan-versioning-nextjs). The page renders what is published today; a subscriber keeps the version they signed up on. This is correct behaviour and it still produces support tickets. The customer reads your current page, then compares it to their invoice. Answer from their plan version, never from the page, and check entitlements by item slug rather than guessing from the plan name. **An item is on the plan but missing from the page.** Check whether it is marked internal only. That flag drops the item from the public payload entirely and strips its slug from each plan's features, limits and quotas, so it is absent rather than merely unrendered. The plan still grants it. That is the intended behaviour for a rollout switch and a confusing half hour if you have forgotten the flag exists. **A badge that no data backs.** Our pricing page picks the "most popular" plan by array index: with more than two plans it is the second one. That is a layout convention, not a fact about what customers buy, and the day somebody reorders the group the badge moves on its own. If a badge makes a claim, render it from something that can be wrong. If it is decoration, say so in a comment so the next person does not go looking for the query behind it. **The table went blank and the page did not.** Decide now what renders when the fetch fails. Ours falls back to a card that carries no prices at all: it says pricing is being finalized, keeps the trial line, and offers a contact link. A fallback that quotes a price is a hardcoded price with extra steps, and it will be serving last quarter's numbers at the exact moment your API is down and nobody can check. That last one is the whole post compressed into one decision. When you cannot reach the source of truth, say less. Do not guess fluently. ```bash npm i @buildbase/sdk ``` --- ## When you need a second pricing page, and when you need a plan version > When a second pricing group is the right call and when it is a plan version or a currency variant instead, plus what a second public pricing page costs you in attribution and in-app upgrades. - Source: https://www.buildbase.app/guides/when-you-need-a-second-pricing-page - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-16 - Updated: 2026-10-22 ### In short Three different things get called a second pricing page. A different price is a new plan version, a different currency is a pricing variant, and only a different set of plans is a second pricing group. Split for the third: a second group costs you attribution and an upgrade path that ignores your slug. The console calls it a pricing group. Your marketing site calls it the pricing page. People reach for a second one about a month before launch, usually to solve a problem it will not solve. Here is the distinction nobody writes down. A pricing group is a named, slugged, versioned list of published plan versions. That is the whole object. It holds no price, no currency, no region and no customer. So when someone asks for a second pricing page, one of three different things is being asked for, and only one of them is a group. ### What you are building One decision, recorded in the console: whether your organization publishes one public pricing table or several, and which of them is the default. When it works, a visitor at `/pricing` sees the group you named, and a signed-in customer who clicks Upgrade sees plans they can actually buy. When it does not, a customer who arrived through `/pricing/startups` opens the upgrade dialog six weeks later and finds the standard table, because the in-app endpoint behind that dialog takes no slug. Nothing errors. They just see the wrong prices, and you hear about it from them. > **Before you start:** You need billing currencies set on the organization, which is step one of the > Get Started checklist and worth [settling before you build any > plans](/guides/choosing-billing-currencies-before-your-first-subscription), > plus Stripe connected and at least one published plan version. A group version > refuses to publish while it is empty, and it will not take a plan version that > has no price in your organization's first billing currency - that second one > is checked as you add plans to the draft, not at publish time. ### Step 1: run the test before you create anything The test is about the list of plans, not about the money. **The price differs, the plans do not.** That is a plan version. Published plan versions are immutable, so a price change means publishing a new one, and the customers already subscribed [stay on the version they bought](/guides/plan-versioning-nextjs). No second page involved. **The currency differs, the plans do not.** That is a pricing variant on the plan version. Base price and quota overage are both per currency, the checkout call takes the currency as an argument, and the workspace locks to one currency the first time it subscribes. **The set of plans differs by audience.** Now you want a group. That middle case is where most "regional pricing" questions actually land, and there is a constraint that settles it. A group version refuses to publish unless every plan version in it supports the same currencies: ```text All plan versions in a group must support the same currencies. The following plan version(s) have a different set of currencies: . Add or remove pricing variants so every plan version has the same number and set of currencies. ``` Combine that with the other rule - only the highest published version of a plan may sit in a group - and a group can never be the regional switch. The same plan cannot appear in one group at a euro-only version and in another at a dollar-only version, because only one of those versions can be its highest. Charging genuinely different numbers by region, rather than the same number converted, means separate plans with their own Stripe prices, sitting in the one catalog you already have. Know that before you promise regional pricing to anyone. > **Key takeaway:** A second group is for a different set of plans, not a different price and not > a different currency. If the plan list is identical on both pages, you are > about to build a maintenance burden with no behaviour behind it. ### Step 2: the cases that do earn a second group Three that hold up: A second product line with its own plans, sold from its own page. A partner table at `/pricing/partners` listing a different subset of what you already sell. And a plan you want reachable by link but absent from `/pricing`, since a non-default group is never returned by the default endpoint, which makes an unlisted table just a group you did not promote. Everything else I have been asked for turned out to be one of the two cheaper things above. Worth knowing before you plan around any of it: creating a group is checked against a `max-plan-groups` ceiling on your own subscription, so the number you get is not open-ended. ### Step 3: pick the default on purpose At most one group per organization is the default. The console's Set default action is a single call that promotes one and demotes the rest, so nothing lets you have two. Having none is reachable, though, and it is its own problem. More on that below. That flag does more work than its name suggests. It decides what the public default endpoint returns for a site that renders pricing without naming a group, and it decides what a workspace with no subscription sees inside your app. Pick it rather than inheriting it from whichever group you happened to create first. Two mechanical notes while you are there. The slug `default` is reserved and the create route rejects it, since the public API already uses that path. And a group carries one draft version at a time, so a second draft is refused until you publish or delete the first. The slug is the part you paste into your site: ```tsx import { PricingPage } from '@buildbase/sdk/react'; export default function Pricing() { return ( {({ plans, loading, selectPlan }) => { if (loading) return

Loading plans

; return plans.map((plan) => (

{plan.name}

)); }}
); } ``` `slug` and the render function are both required. Point a second route at a second slug and you have two public pricing pages. ### Step 4: the half that is not on your marketing site Your signed-in app also shows plans, and it does not go through `PricingPage`. It calls this: ```text GET /api/v1/public/workspaces/:workspaceId/subscription/plan-group ``` Read that path again. There is no slug in it. So which group does it return? The endpoint resolves one on its own, in this order: the group recorded on the workspace's subscription, or the organization default, or, failing both, the most recently created group version in the organization. Not the most recently published one. That last query filters on neither status nor currency, so an unfinished draft is what an app can fall back to. So the upgrade dialog is correct for a customer who already subscribed, and correct by luck for everyone else. A trial workspace that signed up from your partner page has no subscription yet. It gets the default group. The pricing page promised one table and the app offers another, and the only symptom is a confused support email. If you run a second group, the signed-in path is the work. Either keep the plans in both groups close enough that the fallback is harmless, or get the customer onto a subscription in the right group before they ever open the dialog. ### What breaks later, and how you find out **Your conversion numbers quietly merge.** A subscription does not record the pricing page the customer came from. The group is resolved afterwards by walking every live group, default first, and taking the first current published version that contains that plan version. Share one plan version between two groups and every subscription for it is attributed to the default group. No error, no warning, just a funnel report that says your second page converted nobody. Two groups you want to tell apart need two sets of plans, which is the opposite of what the upgrade dialog wanted in step 4. Share the plan versions and the fallback is harmless but the funnel is unreadable; split them and you get the reverse. No setting gives you both. **You try to clean up and cannot.** Archiving or deleting a group with live subscriptions is refused outright: ```text Cannot delete this pricing group - it has active subscriptions. Archive it after all subscriptions are migrated or canceled. ``` Migrating those customers is a per-customer plan change, not a toggle. Which is the honest summary of this whole decision: a group is cheap to create and expensive to retire, exactly like [enabling a currency you later regret](/guides/choosing-billing-currencies-before-your-first-subscription). **You delete the default and the pricing page empties.** The delete response carries a warning when the group was the default, and the public default endpoint then answers with a plain 404 saying no default pricing group is configured. A site that renders pricing without naming a slug shows nothing at all. Set a new default in the same sitting. **You add last year's plan to a new group.** Only published versions are allowed in, and only the highest published version per plan. A group is always a view of your current catalog, never an archive of it. Keeping an old price alive is a [plan version job](/guides/plan-versioning-nextjs), and the two get confused often enough that it is worth saying twice. ### One group is usually the answer Our own organization sells three plans: Launch, Grow and Scale. Our pricing page reads one group slug, `main`, out of a single environment variable. The catalog in that organization ran to 163 rows the last time we read production, and only 105 of those are shown to a customer at all. A catalog that size still goes out on one table. That is the thing to weigh. The cost of one group is that one page has to speak to everyone. The cost of two is a second set of plans to keep current, a split funnel, an upgrade path that needs thinking about, and a group you cannot delete once somebody buys from it. A group's slug is friendlier than [a catalog item's](/guides/structuring-a-product-catalog-you-will-not-regret). The API will take a new one after a duplicate check, because nothing is keyed on it internally. It is still wired into your public route and into the variable your site reads, so renaming it is a deploy rather than an edit. Create the second group when the set of plans genuinely differs. Until then, the answer to "we need another pricing page" is almost always a plan version. ```bash npm i @buildbase/sdk ``` --- ## Structuring a product catalog you will not regret > How to structure a product catalog for SaaS billing: what counts as one product, why prices belong on plan versions, and why the slug is the part you cannot rename later. - Source: https://www.buildbase.app/guides/structuring-a-product-catalog-you-will-not-regret - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-15 ### In short Structure a catalog in three layers: categories group products, products are the things you sell, and prices live on each plan version rather than on the product. Entitlement resolves on the product slug, so pick slugs your code can check and leave display names free to change. Naming a product feels like a marketing decision. It is an API design decision, and you find that out about six months later, when someone asks to rename Pro to Business and the real question turns out to be whether every workspace on it quietly loses a feature. Here is the split that decides everything else. A product carries no price. [Prices live on each plan version](/guides/plan-versioning-nextjs), per currency, under `pricingVariants`. What a product carries is a slug, and the slug is what entitlement resolves against: a published plan version stores its grants as plain objects keyed by slug, so `limits['max-oauth-clients']` is the contract between your catalog and your code. The display name is copy. You can change that on a Tuesday afternoon and nothing anywhere notices. The hierarchy itself is the easy part. Categories, products, plans: every billing vendor draws those same three boxes and every guide to billing explains them. The part nobody warns you about is which field is permanent. ### What you are building A catalog where the string your code checks and the string your pricing page prints are deliberately different things, and only one of them gets to be permanent. When it works, you rename a tier in the console and nothing deploys. You move a feature from your middle plan to your entry plan and nothing deploys either, because that is an assignment stored on a plan version, not a line of code. The header of our own entitlement registry says it more precisely than I can: > Code owns the namespace: which slugs exist, what kind each is, and how they > pair. The database owns the assignment: what a given plan version grants. When it does not work, you have a product called `pro-features` that three plans grant, nobody can explain, and no enforcement point actually reads. > **Before you start:** You need an organization with Stripe connected, and your [billing currencies > settled > first](/guides/choosing-billing-currencies-before-your-first-subscription), > because a plan version has to carry a price in every currency you bill in. You > also need at least one workspace feature before you start, because a > feature-type product is rejected without one. Each maps to exactly one > product. Define them first and the wiring falls out of that. ### Step one: decide what one product is A product is one thing you can switch on, cap, or count. If you cannot name the moment your code asks about it, it is not a product. It is a bullet on a pricing page, and those are free. We give every item in our registry a gating class, decided by three questions in this order: 1. Would gating this make a new customer leave before they see the product work? Then it is core: it ships on every plan and never carries a fence. Gate the thing someone needs in order to see why you are worth paying for, and you lose more in churn than you ever earn in upgrades. 2. Does each unit cost you money at the moment it is used, or for as long as it exists? Then it is a cost item. Cap it or meter it to protect margin, not to drive upgrades. 3. Does it have a distinct buyer, a distinct support burden, and no meaningful "some of it"? Then it is a differentiator, and it can carry a real fence. Anything that is none of the three is either governance - retention and audit sold as a tier attribute - or not a SKU at all. Run our own catalog through that and the shape is not what a pricing page suggests. Of 197 items, 82 are differentiators, 76 are cost control, 21 are core and 18 are governance. Sixty-eight of them are marked internal only, which means they gate something but never appear on a public pricing surface. > **Key takeaway:** Most of a mature catalog is not a sales surface. Roughly a third of ours is > internal. Plan for that from the start, or you will end up writing marketing > copy for a quota whose only job is to stop one customer filling a disk. Another number to sit with: 114 of those 197 items are limits, 17 are quotas, and only 66 are features. What people picture as a feature list is mostly numbers. ### Step two: write the slug for your code, not your pricing page Create the category first. It is required on every product, so you cannot defer it, and the console is explicit that a category counts for nothing until a product sits in it. We run nine: auth, billing, messaging, automation, tenancy, content, platform, hosting and support. Platform is the biggest at 61 items, which tells you something about where a catalog actually grows. Then the slug. Three different surfaces address a product by it, which is the whole argument for treating it as an interface: ```tsx import { WhenWorkspaceFeatureEnabled } from '@buildbase/sdk/react'; function Dashboard() { return ( ); } ``` ```ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); const usage = await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1, }); if (usage.available <= 0) { return Response.json({ error: 'Quota exceeded' }, { status: 429 }); } ``` And the plan version itself, which stores `features`, `limits` and `quotas` as plain objects keyed by the same strings. Notice what is not in any of those three places: the product's name, its category, its sort order, its badge. So name the slug after the capability, not the tier. `advanced-analytics` is a capability. `pro-analytics` is a tier that will be renamed. No file states our whole convention, which is a gap rather than a secret. But the pattern across 197 rows is consistent enough to copy: kebab-case throughout, a `max-` prefix on most counted ceilings (86 of our 114 limits carry it), and the feature named for the thing rather than for who gets it. One constraint worth inheriting: keep slugs inside `^[a-z0-9_-]+$`. Ours are written that way so every one is a valid Stripe `lookup_key`, which makes a future mirror into Stripe Entitlements a copy rather than a translation table. You get that for the price of not using spaces. ### Step three: pair the switch with the ceiling Most capabilities need two items, not one. A feature decides whether the thing exists; a limit or a quota decides how much of it you get. They are [different enforcement points](/guides/quota-enforcement-server-side-nextjs) with different failure modes. Collapse them into one item and the catalog starts lying. Our registry states the pairing with an example: `custom-auth-domain` decides whether the Domains tab exists at all, while `max-auth-domains` decides whether you may add a sixth. A limit therefore declares its parent feature, and a limit whose parent is locked reports as not-applicable rather than as zero. In our catalog 133 of the 197 items carry a parent, features included. Which brings up the one numeric convention you should steal outright: ```ts export const UNLIMITED = -1; ``` Unlimited is `-1`. Zero means none allowed. Absent means not on this plan at all. Three states, three values, no overloading. A `0` that means infinity is a bug waiting for its first reader: eventually a plan that grants nothing reads as a plan that grants everything, and that is the expensive direction to fail in. We have one field that still stores zero for unlimited, from before this was settled, and the only reason it has not bitten us is that exactly one boundary translates it. That is a thing to inherit on purpose, not by accident. The matching rule on the read side: fail open on unknown. Asking whether a feature is granted returns granted, locked or unknown, and the gate allows on unknown. [To draw a padlock](/guides/enforcing-quotas-in-react) you ask whether the state is explicitly locked, never whether it is simply not granted. A false unknown costs you one ungated feature. A false locked costs a paying customer a 402 on a screen they bought. ### Step four: the half you are allowed to change Order, names, badges and categories are presentation. Change them whenever you like. Reordering a plan that is already published is a plain save: it creates no new plan version, touches no Stripe product or price, and cannot change what any workspace is entitled to, because entitlement resolves by slug and ordering is stored on the item. Two small things save you work later. Space your sort order values 10 apart, which is what the field's own documentation recommends and what ours should have been seeded with rather than all zero, so you can insert an item between two others without renumbering the rest. And use the highlight flag rather than sort order to lift a selling point to the top of a plan card, so the card leads with what sells the plan rather than with whatever sorts first. ### What breaks later, and how you find out **You rename a slug.** The API will let you. A PATCH accepts a new slug and checks it for duplicates against other products of the same type, and that is the end of its concern. Nothing rewrites the plan versions that already store grants under the old key, so the symptom is not an error. It is a customer who paid for something and now sees a padlock, reported days later, on a Saturday. The supported move is to supersede rather than rename: keep the old item, point it at its successor, and let reads resolve either. Our own catalog carries five of these. The honest one to look at is `auth-configs`, which is live on real plans today and whose note reads: > The live production row max-oauth-clients replaces. Its description promised > a count "by slug" and no auth model has one; no code read it. Kept on the > plans that carry it, and served through max-oauth-clients. A product we shipped, named, sold, and never enforced. The slug stays because plans carry it. **You picked the wrong type.** A product is [a feature, a limit or a quota](/blog/what-are-entitlements), and the type is part of its identity: slugs are unique per type, not globally. Two rows in our registry carry the same sentence, which makes it a pattern rather than an accident: "The live DB row is a FEATURE item and cannot be renamed into a LIMIT - archive it and create this one." Deciding whether a thing is a switch or a number is therefore a step-one decision, not a detail. **You put a number on the pricing page that nothing counts.** The cure is the test the Get Started checklist in your console already applies: a product counts as done once it is wired to a workspace feature or picked up by a plan. An item that is neither is a promise with no enforcement point behind it, which is exactly what `auth-configs` was. ### When a smaller catalog is the right answer Most of this pays off only once a catalog has grown past what one person can hold in their head. If you are selling three plans and gating four things, four products and one category is a complete and correct catalog. The discipline that matters reduces to one line: pick slugs you would be happy to find in your code two years from now. The expensive version of this is not building the wrong catalog. It is building a reasonable one and then discovering that the one field you chose casually is the one field you cannot take back. ```bash npm i @buildbase/sdk ``` --- ## Which notifications users get to turn off, and which stay on > Which notifications should be mandatory, which users may switch off, and how the opt-out is actually enforced at send time. - Source: https://www.buildbase.app/guides/which-notifications-users-can-turn-off - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-14 ### In short Make security, billing and account-lifecycle mail mandatory, and let users turn off anything whose purpose is engagement. The split is decided per event, by a flag on the event and by whether the template carries an unsubscribe group. Neither default is the one most teams assume. Nobody decides which notifications users can turn off. They inherit it, then find out what they inherited when a customer forwards a 6am digest and asks why the off switch did nothing. The list is not a setting. It is the residue of two defaults that point in opposite directions, and neither one is the default most teams assume they have. > **Key takeaway:** Make mail the account depends on mandatory: security, payment failures, plan > state, invitations. Let users turn off anything whose job is engagement. Then > check both halves actually hold, because the preference flag and the > unsubscribe group are separate mechanisms and a notification can escape > through either one. ### What you are building A preferences screen that lists the right events, backed by a gate that honours it. When it works, a member opens workspace settings, sees the notifications you decided they may control, switches one off, and stops getting it - while the payment-failed email still arrives, because you never offered that one as a choice. What you are not building is a screen that lists everything you send. That screen is a liability. Every row on it is a promise that the switch does something, and the gate only reads preferences for events you explicitly opened up. > **Before you start:** A workspace with at least two members, so you can tell a workspace default > apart from one member's own choice. You also need the email module configured > far enough to actually send, otherwise every test looks like a pass. One trap before the code. These methods live on the low-level `WorkspaceApi`, which you reach through `client.forSession(id)`. That is not the `withSession(id)` helper that [the Express metering guide](/guides/usage-metering-middleware-express) happens to name `forSession`: same word, different object, and the scoped one's `.workspace` has none of these methods while its `.notification` only sends. The snippets below are written against the SDK's typed surface rather than copied from a run, so check them against your own client before pasting. ### Step one: sort your events by who is hurt if it does not arrive Before any code, split what you send into two piles. The test is not whether the email is useful to you. It is whether its absence hurts the recipient. Mandatory, in practice, is narrower than most teams fear and wider than the word "transactional" suggests: - Security and account state. A password change, a sign-in from a new device. - Money. A failed payment, a card that needs action, a suspension. - Plan state the user cannot discover in time any other way. A trial about to end. - Being added to or removed from somewhere. An invitation, a role change. Optional is everything whose purpose is engagement: digests, activity summaries, product updates, usage nudges, the weekly roundup nobody asked for. If the honest reason the email exists is that you want them back in the product, it belongs in the pile the user controls. The grey zone is real and worth settling out loud. Is "invitation accepted" mandatory? The invitee needs the invitation. The person who sent it does not need to know it was accepted - that is a courtesy, and courtesy mail is exactly the kind that accumulates into noise. Put the invite in the mandatory pile and the acceptance receipt in the optional one, and write the reasoning down before someone argues about it in a support thread. One category sits outside both piles. The mail that carries the mechanism itself - a sign-in link, a password reset, an address verification - is not a notification at all. It is the thing the user just asked for. It never reaches the gate, and there is no row for it on any screen, because an opt-out on it would be an opt-out of signing in. ### Step two: find out what your defaults already are The seeded system events and the events your own code registers get opposite treatment. That is where the inheritance bites. The 20 events seeded into a new organization - six workspace, four billing, two trial, four payment, four account - are all created the same way: ```ts { system: true, enabled: true, userManaged: false, channels: { email: true, push: true }, } ``` Read that twice. `userManaged: false` on all 20. Email and push both on. So a preferences screen built straight out of the box lists nothing at all, while every one of those 20 sends on both channels to whoever the notifier names - the workspace owner for most of the billing and trial mail, the user for the account mail. The off switch is not broken. There is nothing for it to show. Now the other direction. When the SDK sends a notification for an event that does not exist yet, the event registers itself on that first send: ```ts { system: false, enabled: true, userManaged: true, channels: { email: false, push: true }, } ``` Inverted. Custom events are user-managed by default, and their email channel starts off. So the digest you built yourself is the one users can mute, and it is not emailing anybody until you turn that on, while the 20 you never looked at are the ones they cannot escape. The asymmetry is defensible in the abstract - a system event is usually account state, a custom event is usually engagement - but it is a guess made on your behalf, and step three is where you find out it is not negotiable. It guesses wrong for any product whose seeded mail skews chatty, and wrong again the moment you register a custom event for something genuinely important. ### Step three: open up what you can, and find out what you cannot Flip `userManaged` on the events from your optional pile - and here the asymmetry from step two stops being a default and becomes a wall. The update route branches on whether the event is seeded: ```ts // System events: only allow toggling channels (enabled is derived from channels) if (event.system) { // ... // System events cannot change: slug, name, description, category, // userManaged, emailTemplate } ``` So `userManaged` is a lever on your own custom events only. Send it for one of the 20 seeded events and the field is dropped - not a 400, not a 409, a 200 with the change quietly discarded. Worth knowing before you spend an afternoon wondering why the screen stayed empty. Which means the seeded half is not a default you override. It is one you are stuck with. The only control a seeded event offers is its channels, and that is org-wide and all-or-nothing: you can stop sending the sign-in alert by email to everybody, or keep sending it to everybody. There is no per-user middle. If a seeded event genuinely belongs in your optional pile, that gap is the thing to plan around, not a setting to hunt for. With the custom events opened up, the listing endpoint has something to return: ```ts import { BuildBase } from '@buildbase/sdk'; const buildbase = BuildBase(config); // your existing setup-guide client // The low-level WorkspaceApi, bound to one signed-in session. Not the same // object as buildbase.withSession(sessionId). const ws = buildbase.client.forSession(sessionId).workspace; // Only events that are userManaged AND enabled come back. const events = await ws.getNotificationEvents(workspaceId); ``` What you should see: the custom events you just opened, each with its slug, name, description, category and channel defaults - and nothing else. An empty array on an untouched setup is the expected result rather than a bug, because the only events in a fresh organization are the 20 that cannot be opened. Two levels write to it. The workspace default is what every member starts from and needs the settings-edit permission. A member's own choice needs only membership: ```ts // The workspace default, for every member who has not chosen. // Needs the settings-edit permission. Merged per event: send only what changes. await ws.updateNotificationPreferences(workspaceId, { weekly_digest: { email: false }, }); // One member's own choice, over that default. Any member may call it. await ws.updateMyNotificationPreferences(workspaceId, { weekly_digest: { email: true }, }); ``` Resolution is one function, deliberately, so the screen and the send path cannot disagree: a member's own choice wins, unless the workspace marked that event `required`, in which case the default is what they get and their choice is not read. No choice anywhere means on. Send `null` for a channel rather than `false` to clear a member's choice and drop them back to the workspace default. It is the difference between "I want this off" and "I have no opinion", and only one of them should survive an admin changing the default later. > **Tip:** A `required` event refuses a member's write rather than accepting it and > ignoring it. You get a 409 naming the locked events, not a silent success > followed by mail the user believes they switched off. ### Step four: the unsubscribe group is a second, separate gate The preference flag governs notification events. Bulk email runs through an entirely different check, and the two do not know about each other. That check begins: ```ts if (!unsubscribeGroupId) return false; // no group means transactional ``` The all-off flag is read after that line. Which means a user who unsubscribed from everything still receives any template you never assigned to a group. For a receipt that is exactly right. For the product-update blast you shipped in a hurry, it is a complaint, and the user is correct: they did turn it off, and you sent it anyway. So the audit is two columns, not one. For every message you send: is its event user-managed, and does its template carry an unsubscribe group? Mandatory mail should have neither. Optional mail needs both. Anything with one and not the other is the bug you are looking for. ### What breaks, and how you find out **The off switch that does nothing.** A member switches something off and the mail keeps coming. Almost always the event is not `userManaged`, so the gate never reaches the preference layer. The row should not have been on the screen at all. The listing endpoint filters to user-managed events precisely so this cannot happen; a row that is there and does not work usually means a hand-rolled screen that listed every event instead of calling it. **The typo that looks like it worked.** Writing a preference for an unknown or non-user-managed slug is refused by name with a 400 listing the bad keys, rather than stored and quietly ignored. Good: a mistyped slug fails at the call instead of six weeks later. If you are wrapping the API, do not swallow that response. **Changes that take a moment to land.** Event config is cached for 30 seconds and the org-level switch for a minute, both invalidated explicitly when you change them through the console. If you write directly to the database instead, expect up to a minute of stale behaviour and do not debug it as a gate bug. **Failures that send rather than drop.** The gate fails open: an unexpected error, or no config row for the event at all, returns "allowed". The org-level switch is checked before that, so an organization with email switched off still blocks - but below it, an event you intended to be off is not safe merely because it has no configuration. Failing open is the right call for a payment-failure notice and the wrong one for a marketing blast. Off is a stored decision, not an absence. **The cost of a wide screen.** The gate runs per recipient per channel, so an email-only digest going to 200 users is 200 gate checks, and one that also pushes is three times that, because the push side is evaluated twice per recipient. Member preferences are fetched in one query rather than per person, and the check itself touches nothing, so none of this is I/O. Not a scaling problem, then, but still a reason not to make every event user-managed on the theory that more choice is always better. Each row is a promise you have to keep. ### Where to settle it The screen is downstream of a classification, and the classification is the part nobody writes down. Write it down. Every message you send, a tick in each of the two columns, then a hard look at the rows with exactly one tick. That list is short, and it is where your opt-out is currently lying to somebody. Related: [team invitations](/guides/team-invitations-nextjs) covers the event most likely to sit in your mandatory pile, and [transactional email landing in spam](/guides/transactional-email-landing-in-spam) covers what happens when the mandatory half does not arrive at all. ```bash npm i @buildbase/sdk ``` --- ## One auth client per environment, and what goes on each > How to split auth clients and redirect URLs across dev, staging and production, when a wildcard is safe, and why localhost does not belong on a production client. - Source: https://www.buildbase.app/guides/auth-client-per-environment - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-13 ### In short Create one auth client per environment rather than one client carrying every environment redirect URL. Matching is exact on scheme, host, port and path, so localhost, a preview URL and production are three separate entries. BuildBase allows one wildcard, as the entire leftmost host label. The redirect URL list is the first thing a BuildBase setup gets wrong, and it gets it wrong in a way that looks fine for months. You create one auth client. You paste in `http://localhost:3000/callback`, the preview URL and production, because all three need to sign in. Every environment works. Nothing errors. Then you think about what you just built. That production client will hand a real user's authorization code to whatever happens to be listening on port 3000 of a laptop, if someone can get a browser to ask for it. And the client secret sitting in your local `.env` is the same string that signs production's identity tokens. So the question the console does not ask you is: how many clients, and what goes on each one? One per environment. ### What you are building Three auth clients, one each for local development, staging and production. Each carries only the redirect URLs its own environment actually uses, and each app build reads its client ID from its own environment. When it works, signing in locally and signing in on production are two independent paths that share no credential. Deleting the development client logs nobody out of production. Pasting production's client ID into your local `.env` fails at the redirect URL, loudly, instead of quietly working. > **Before you start:** An organization with at least one login method enabled, since the client > offers a subset of the methods that already exist, and an app already [wired > up through the SDK](/guides/buildbase-on-nextjs) so you have somewhere to > point a client. Admin access to the BuildBase console. The Get Started > checklist puts "Enable login methods" immediately before "Create an auth > client" for this reason, and that step's own description says your SDK config > cannot be filled in until the client exists. ### Why one client cannot cover two environments Not a style preference. Four things sit on the client rather than beside it, and each one of them is single-valued. **The app server URLs.** Creating a client requires `applicationTokenUrl` and `applicationProfileUrl`. Both are one string, and that is the endpoint BuildBase calls to mint a token for a user who just signed in. One client points at one app server. Staging and production cannot both be it, so if you share a client, one of the two environments is authenticating against the other's backend. **The secret.** Generated once at creation, shown once. And it is not only a password: the same value is the HMAC key that signs the identity JWT your app server verifies, and the revoke webhook. A development secret that leaks out of someone's dotfiles is a production signing key. **The login methods.** The methods a client offers are a subset you tick per client, so staging can carry a password login you would not put on production, or the reverse. **The tracking scripts.** Analytics and advertising scripts attach per client, and the reason is written into the type itself. One organization routinely runs a marketing site, a product and a staging build, and they do not share a measurement id. There is a fifth reason, and it is the one that should decide it for you even if the other four do not. Loopback redirect URLs ignore the port when they match. A registered `http://127.0.0.1/callback` matches `http://127.0.0.1:51789/callback`, and every other port, because native and CLI clients bind a fresh ephemeral port on each run and RFC 8252 section 7.3 asks for exactly that. It is the right rule. It also means that registering one loopback entry does not open one port, it opens all of them on that host and path. That entry has no business being on the client your paying users authenticate against. ### Where one shared client wins If you have one environment, one developer and no staging, three clients is bookkeeping that buys you nothing. You will keep the loopback entry on the client anyway, because it is the only client, and the second and third client exist only to be forgotten about. Ship the one client, and split it the day you add a staging deploy or a second person. The threshold is not team size, it is whether any environment has users who are not you. Once a real customer signs in through a client, the laptop entries have to come off it, and at that moment you need somewhere else for them to live. Auth0, WorkOS and Clerk all draw this line a level higher than we do. Auth0 tells you to run a separate tenant per environment, WorkOS a separate environment with its own credentials and redirect URIs, and Clerk gives every application a development and a production instance out of the box, with a separate application as the documented workaround for staging. So if you have used one of those, a client per environment will feel like the loose version of a habit you already have. ### Step 1: create one client per environment In the console, open auth settings and create a client. It asks for a title, a type, and the two application URLs that environment's app server answers on. Then name it for a stranger. "Acme production", "Acme staging" and "Acme local" are worth the three seconds, because the next person reading this list is deciding which client ID goes into a deploy, and a list of four clients called "My app" is how the wrong one gets picked. The type is a real decision, not a formality. A `normal` client is how your own app signs its own users in, and that capability is granted on every plan. An `oauth2` client is something else: your app _being_ the identity provider that other applications authenticate against, which is a separate plan feature. One route creates both, so it is easy to pick the second by accident and be refused, or to pick it and pay for a capability you are not using. What you should see: the client is created with an **empty** redirect URL list. Nothing is prefilled, and the secret is displayed in full exactly once. Copy it now, into that environment's secret store and nowhere else. Every later read masks it down to the first five and last five characters, and the only way back is rotation, which invalidates the old one. New `oauth2` clients also require PKCE by default. ### Step 2: add only the redirect URLs that environment uses Matching is an exact string comparison against the registered list before anything clever happens. Which means these are four different entries, and three of them will not match the fourth: ```text https://app.example.com/callback https://app.example.com/callback/ https://app.example.com/Callback https://app.example.com:443/callback ``` The trailing slash is the one that costs an afternoon. Register the string your app actually sends, character for character. For the local client, loopback with the port you develop on: ```text http://localhost:3000/callback ``` Entries are deduplicated when you save, and each one is shape-checked by the same code in the browser and on the server, so the inline error you see while typing and the server's answer cannot disagree about shape. One check the browser does not carry is the public suffix list, which is too large to be worth shipping to a browser. A wildcard pattern too broad to be anyone's domain, which the next section gets to, passes the inline check and is refused on save, so that one arrives in the toast rather than under the field. One trap worth knowing. A plain, non-wildcard entry is accepted on very permissive terms: anything the URL parser accepts, which still includes private-use schemes like `myapp://callback` for native apps, and also fragments and embedded credentials. That is deliberate, because tightening it would make existing stored clients unsaveable the next time an admin edited them. It does mean the console will happily save you a redirect URL with a username and password in it. Do not write one. ### Step 3: point each build at its own client The provider takes the org ID, the client ID and the redirect URL. Read all three from the environment rather than hardcoding them, so the same source tree produces a different wiring per deploy: ```tsx import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; export default function Providers({ children }) { return ( {children} ); } ``` The `redirectUrl` you pass here is the value that arrives at the authorization endpoint as `redirect_uri`, so it has to be one of the strings you registered in step 2, exactly. These are `NEXT_PUBLIC_*` values, which means they are baked into the bundle at build time. Changing a client ID is a redeploy, not a restart. Our own environment notes put it plainly: if a frontend variable is wrong in production, the fix is in the dashboard and it still needs a redeploy, because `NEXT_PUBLIC_*` is compiled into the bundle rather than read at runtime. What you should see: sign in on each environment in turn and land back in that environment. If local redirects you to production, you are running production's client ID. ### When your URLs genuinely vary Exact matching is what the standards ask for. RFC 9700, the OAuth 2.0 security best current practice, requires an authorization server to compare a request's redirect URI against the registered ones as exact strings, with one carve-out: port numbers in loopback redirects for native apps. So the port relaxation in the previous section is not a liberty we took, it is in the specification. The draft OAuth 2.1 document asks for the same thing in its registration requirements. We deviate once more, narrowly, because [subdomain-per-tenant](/guides/multi-tenant-workspaces-in-an-afternoon) is the dominant multi-tenant SaaS shape and exact matching means one registered entry per customer. A pattern may carry one asterisk, as the entire leftmost host label, consuming exactly one label: ```text https://*.app.example.com/callback ``` That matches `acme.app.example.com` and `beta.app.example.com`. It does not match `a.b.app.example.com`, because the asterisk is one label and not a prefix. Scheme and path stay exact, and so does the port, with the same loopback carve-out as above. Neither side may carry embedded credentials, because the comparison runs on a parsed URL rather than the raw string. That is what defeats the classic bypasses, where a hostile host is smuggled in front of the real one with an `@` or a `#`. A pattern must also carry no query string and no fragment of its own. The fragment is refused when you save it. The query string is not, so a pattern with one saves cleanly and then silently matches nothing, which is worth knowing before you spend an evening on it. Four more rules worth having in your head before you type one: - `foo*.example.com`, `*.*.example.com` and `a.*.example.com` are all refused. One asterisk, leftmost, whole label. - The literal remainder has to be a domain somebody can own. Patterns on a public suffix are refused, which rules out `*.com` and, more usefully for you, `*.vercel.app` and `*.github.io`. - Wildcards must be `https`, unless the remainder is a loopback host, where `http://*.localhost:3000/callback` is allowed for local subdomain-per-tenant work. - Wildcards are console-only. Dynamic client registration, where an unattested agent registers itself, rejects them outright. There is no domain-ownership proof behind a pattern, so the admin typing it is the trust boundary. Pick the narrowest pattern that covers your tenants, on a hostname you control. ### Preview deployments, honestly If your previews are served from a domain you own, wildcard the varying label and you are done. `https://*.preview.example.com/callback` covers every branch build. If your previews are on the platform's shared domain, you cannot. A wildcard on `vercel.app` is refused by the public suffix rule, and that refusal is correct: the pattern would match every other customer's deployment on that domain too. We are not unusual here. WorkOS documents the same rule and names `*.vercel.app` as a rejected example, and Clerk's own documentation says it is currently not possible to use their production API keys with your host's provided preview domain. The workable answer is to point preview builds at a stable staging client with one fixed redirect URL, and accept that a preview signs in as staging. It is less magical than a wildcard and it is the only version of this that is not a hole. ### The failure modes **An unregistered `redirect_uri` is a dead end, not a redirect.** You get HTTP 400 and a JSON body on the auth server, and the browser stops there: ```json { "error": true, "path": "redirect_uri", "message": "invalid field redirect_uri , required of type :Invalid redirect URI" } ``` This looks broken and it is correct. Until the redirect URI is proven to belong to the client, redirecting to it is the attack, so the error cannot be delivered that way. Every parameter error _after_ that check does come back to your app as `error` and `error_description` on the redirect URL, with your `state` echoed back. Which gives you a rule of thumb: a JSON error on the auth server means the client ID or the redirect URL is wrong, and an error delivered to your own callback means something else is. A sign-in that completes and then bounces you around is neither, and usually [middleware](/guides/nextjs-middleware-redirect-loop-after-login). The rejection is logged server-side with the registered list beside it, which is the first thing to ask for if you are self-hosting and the string looks identical to you. **`redirect_uri_mismatch` from Google or GitHub is a different problem.** That error comes from the provider, about the callback URI shown on the login method, which is not the same value as the redirect URLs on your client. Editing the client will not move it. The [social login guide](/guides/social-login-nextjs) covers that one. **A wildcard that saved but never matches.** Registration rules are re-applied at match time, on purpose, so a pattern written before those rules existed cannot come alive later as something we would refuse to register today. If a pattern saves and never matches, re-save it and read the error. **One client per environment does not isolate everything.** This is the part I would want someone to tell me. Magic links and the social sign-in start routes do not check against one client's list. They check the candidate's _origin_ against a set pooled from every redirect URL on every auth client in the organization, plus the organization's auth base URL. That pooling exists to stop someone asking the platform to email a victim a real sign-in link pointing at a domain they control. The consequence: adding `http://localhost:3000/callback` to your development client adds `http://localhost:3000` to an allowlist that your production magic link endpoint also consults. Per-client separation protects the authorization code path completely and this origin path not at all. If the two genuinely must not share an allowlist, they have to be separate organizations, which is a real cost most teams will reasonably decline. If you do not pay it, at least know that the loopback entry is organization-wide, and keep the list short. ### What to carry away One client per environment, because the app server URL, the secret, the login methods and the tracking scripts are all singular and all live on the client. Register the exact string your app sends, and keep loopback off anything real users touch. Reach for the wildcard only when the varying label is a tenant on a hostname you own - never to paper over an environment you were too lazy to give its own client. ```bash npm i @buildbase/sdk ``` --- ## Auth clients and redirect URLs: you want two clients, not one per environment > How many auth clients to create, and how to split redirect URLs across localhost, preview deploys and production without registering a wildcard that will be refused. - Source: https://www.buildbase.app/guides/auth-clients-redirect-urls-and-environments - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-13 - Updated: 2026-10-19 ### In short Create two auth clients, not three. Production gets its own; local development and preview deploys share the other, because they sit at the same trust level. Register exact redirect URLs on the production client, and cover shifting preview hostnames with a single leftmost-label wildcard on a subdomain you own. Every OAuth vendor repeats the same rule: one client per environment. Follow it and you will create three, feel organized, and then discover that the one environment which actually hurt is no better off. Preview deploys get a new hostname on every push. No number of clients fixes a hostname you cannot predict. That rule is one client too many, and it is aimed at the wrong problem. What splits environments is a trust boundary, not a count: production holds real users and a secret nobody should be able to read casually, and nothing else does. Localhost and preview deploys sit on the same side of that line. The preview problem is a different one, and it is a question of redirect URL matching. ### What you are building Two auth clients in the BuildBase console, each with its own client ID, secret and list of redirect URLs. When it works, a developer clones the repo, runs it on `localhost:3000` and signs in without asking anyone for a credential; a preview branch deploys and its sign-in button works on a hostname nobody registered by hand; and production holds a secret that two people have, with a callback list you could read aloud without wincing. > **Before you start:** An organization with login methods already enabled under User Management → > Access → Authentication → Methods. Methods are an organization-wide catalogue > and a client can only offer methods that already exist, so that step comes > first. The sign-in methods to choose from are email and password, [magic > link](/guides/magic-link-login-nextjs), email and phone codes, > [passkeys](/guides/passkeys-nextjs), [Google, LinkedIn, GitHub, > Microsoft](/guides/social-login-nextjs), Apple, an OpenID Connect provider of > your own, Ethereum and Solana wallets, and enterprise SSO (SAML and OIDC), > which is on the Enterprise plan and runs through your own WorkOS account. > Separately, every app is an OAuth 2.0 authorization server for agents and > third-party apps, which is not a way for a person to sign in. ### Step one: decide the split before you create anything Create one client for production and one for everything else. A second client buys you three things that matter here: its own secret, which you can rotate without touching production; its own subset of login methods, so a staging build can offer a password login you would rather not ship; and its own tracking scripts. If none of those matter to you for a given environment, that environment does not need a client of its own, it needs a redirect URL added to one that already exists. > **Key takeaway:** The question is never "how many environments do I have". It is "which > environments need a different secret". For most teams the answer is two: > production, and not-production. What about staging? If staging runs against production data, it is production and belongs on the production client. If it runs against its own data and your developers can read its environment variables, it is not-production. The data decides it. ### Step two: create the non-production client, and copy the secret Go to User Management → Access → Authentication and create a client. Name it for what it is rather than where it runs, so `webapp-dev` and not `staging`. The create dialog shows the client secret once. Copy it then. This is not a UI quirk, it is the design. Every later read of a client masks the secret down to its first five and last five characters, because the alternative was handing the organization's OAuth client secret in full to every role with read access on auth settings. The masking came with a cost that the code records plainly: an admin who skipped past the create dialog had no route back to a working client except deleting it and making a new one, which lost its ID, its redirect URLs and its methods along with it. That is why rotation exists as its own action now. If you lose the secret, rotate it rather than rebuilding the client. You should now see the client in the list with a `clientId`, a masked secret preview, and an empty redirect URL list. Methods and redirect URLs are not part of the create form; open the client you just made and pick its login methods from the catalogue there. ### Step three: register redirect URLs that will actually match Add the exact URL your app sends, and then read that word again, because exact is doing more work here than it looks. A registered entry goes through three passes. The first is raw string equality against the URL your app sent. Not a parsed comparison, a string one. If that fails and the entry contains an asterisk, the wildcard rules in step four take over, and those do compare parsed URLs. If that fails too, one relaxation is left: when both the registered entry and the requested URL are `http` on a loopback host, the port is ignored, so a registered `http://127.0.0.1/callback` matches `http://127.0.0.1:51789/callback`. That carve-out exists for native and CLI clients, which bind a fresh port on every run. The first pass is the one that catches people. String equality means a trailing slash makes a different URL. It means that if your redirect URL carries a query string of its own, you register it with that query string attached, character for character. Build the URL in one place in your code and register that string, rather than assembling it per call site and hoping the two agree. There is also less validation on a plain entry than you might assume. Anything the URL parser accepts will save, which is deliberate: native apps register private-use schemes like `myapp://callback`, and tightening it would make clients that already exist unsaveable. So nothing stops you registering `http://staging.example.com/callback`. Do not. Off your own machine the only scheme that belongs in a redirect URL is `https`, and the wildcard rules below are the one place that is actually enforced. For local development, register `http://localhost:3000/callback`. For tenant subdomains on your own machine, `http://*.localhost:3000/callback` works too, which is how you test a subdomain-per-tenant app without editing `/etc/hosts`. Loopback means `127.0.0.1`, `[::1]`, `localhost` and anything ending in `.localhost`. ### Step four: preview deploys, where everyone gets stuck Point previews at a subdomain you own, then wildcard that subdomain. A wildcard entry here is deliberately narrow. One asterisk, standing as the entire leftmost host label, consuming exactly one label: ``` https://*.preview.example.com/callback ``` `build-417.preview.example.com` matches. `a.b.preview.example.com` does not, because the asterisk is one label and not a prefix. `prefix-*.example.com` is refused outright, since the asterisk has to be the whole label rather than part of one. Matching happens on a parsed URL rather than the raw string, which is what defeats the classic bypasses where an attacker hides a hostname in the userinfo or the fragment. Parsing the URL also makes this pass more forgiving than the string one, in two small ways. An empty path and `/` count as the same target, so on a wildcard entry the trailing slash stops mattering. The query string and fragment on the incoming URL are ignored too, since the authorization code and state get appended after validation. Everything else stays exact: scheme, path, and the port outside the localhost carve-out above. `/callback/extra` will not match `/callback`. And the entry everybody tries first: ``` https://*.vercel.app/callback ``` That one is refused on save, with an error telling you the host is too broad because `vercel.app` is a public suffix. It is the correct answer even though it is the annoying one. `vercel.app` is not a domain you own, it is a domain anyone can deploy under, and a wildcard across it would let any project on that platform receive your authorization code. The same check refuses `*.com`, `*.co.uk` and `*.github.io`. Which leaves you with real work to do rather than a config line: give previews a stable hostname under a domain you control, through a CNAME or your host's preview-domain feature, and send the app's redirect URL from an environment variable rather than deriving it from `window.location`. Then one wildcard entry covers every preview you will ever deploy. Two more rules worth knowing before you rely on one. A wildcard must use `https`, except on localhost. And a wildcard can only be added by an authenticated admin: a client that registers itself through Dynamic Client Registration is refused one outright, because a wildcard is only ever as safe as whoever chose it. ### Step five: create the production client and wire both up Create the production client the same way, with one difference: every redirect URL on it is exact. Reach for a wildcard here only if you genuinely serve tenant subdomains, and then wildcard the tenant subdomain and nothing above it. This is also where the method subset earns the second client. Your non-production client can offer an email and password login that keeps local testing quick, without that login ever showing up on the sign-in screen real users see. The subset is stored per client, not per organization, so enabling a method in the catalogue does not switch it on anywhere by itself. A client has to select it. Keep the production secret somewhere only your server reads it. The client ID and the redirect URL are public by nature, and in a Next.js app both are build-time values: ```bash NEXT_PUBLIC_BUILDBASE_CLIENT_ID=your-client-id NEXT_PUBLIC_BUILDBASE_REDIRECT_URL=https://app.example.com/callback BUILDBASE_CLIENT_SECRET=your-client-secret ``` Then the provider reads whichever client the environment points it at: ```tsx import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; export default function Providers({ children }) { return ( {children} ); } ``` Both values are public and baked into the bundle, so a change to either needs a redeploy rather than a restart. The client secret is the one that stays server-side. [Wiring the rest of the provider](/guides/buildbase-on-nextjs) is unchanged; only these two values differ per environment. What you should see: sign-in works on all three hostnames, and the client list shows two clients, not the three you were told to create. ### The failure modes **The redirect URL does not match and login refuses.** Compare the `redirect_uri` on the authorize request against the registered entry, character by character. Usually it is a missing port, a stray trailing slash, or `http` arriving where a proxy was supposed to forward `https`. That slash surprises people. They have read somewhere that it does not matter, and on an exact entry it does, because that pass is a string comparison. **Sign-in succeeds, then the app bounces between the callback and the login page.** That is not a redirect URL problem at all, even though it looks like one. It is [middleware running before the session cookie is readable](/guides/nextjs-middleware-redirect-loop-after-login). **It works on `app.example.com` and fails on `acme.app.example.com`.** If the wildcard entry is right, [look at the cookie domain](/guides/session-cookie-not-shared-across-subdomains) rather than the redirect URL. **A login method vanishes from one client.** Deleting a method organization-wide pulls it from every client that offered it, and each client's cache is invalidated at the same time so the sign-in screen updates immediately. The method is gone from the catalogue, so it cannot come back by editing the client. **The secret is gone.** Rotate it. Do not delete the client, or you will lose the redirect URL list you just built. ### Where Supabase wins, and where Clerk does Supabase allows a full glob allowlist, and their own documentation gives the Vercel preview recipe directly, wildcarding across the platform domain. If preview deploys on a shared platform domain are the thing you care most about, that is genuinely less work than registering a subdomain you own. We refuse that shape on purpose, and the cost of the refusal lands on you at setup time. Clerk separates development and production into distinct instances with different key prefixes, so a preview build cannot reach production users at all. We have no equivalent: there is no test mode here, and nothing labels a client as non-production except the name you gave it. The discipline is yours to keep. Neither of those changes the advice. It just means the second client is doing a job that, elsewhere, the platform would do for you. ```bash npm i @buildbase/sdk ``` --- ## Choosing billing currencies before your first subscription > Which billing currencies to enable before your first customer: why a Stripe subscription currency is locked per customer, and what adding one later costs you. - Source: https://www.buildbase.app/guides/choosing-billing-currencies-before-your-first-subscription - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-13 ### In short Enable only the currencies you are willing to keep. A workspace locks to one billing currency on its first subscription, and Stripe will not move a customer off it while a subscription, quote or discount still pins it. Adding a currency is easy; every plan version you publish afterwards carries a price in it. Enabling a second billing currency is one more string in a PATCH body. Getting rid of it takes a conversation with every customer who subscribed in it. That asymmetry is the whole of this decision, and it sits at step one of the Get Started checklist for a reason: the currencies you save before you build any plans constrain every price you can create afterwards. ### What you are building An organization that bills in exactly the currencies you intend to support for the next few years, set before a single customer subscribes. When it works, your plan list carries one price per currency you enabled, and a workspace that subscribes gets stamped with its currency for good. No support email ever arrives asking "can you move my account to euros". > **Before you start:** You need an organization and your own Stripe keys connected. You do not need > any plans yet, which is the point: do this before you build them, because a > plan version has to carry a price in every currency your organization bills > in. ### Step 1: find out what you can actually charge in Ask the API rather than guessing from a list you remember: ```bash curl https://api.console.buildbase.app/api/organizations/settings/supported-currencies \ -H "Authorization: Bearer 665f1a2b3c4d5e6f7a8b9c0d:your-token-secret" ``` ```json { "supportedCurrencies": [ "usd", "eur", "gbp", "cad", "aud", "jpy", "inr", "chf", "sek", "nok", "dkk", "sgd", "hkd", "nzd", "mxn", "brl", "pln", "czk", "thb", "try", "zar" ] } ``` That is 21 currencies, and the number comes from `SUPPORTED_BILLING_CURRENCIES` in `packages/shared`, the same constant the API validates against. Anything outside this list is refused at save time, so read it before you promise a price to someone. ### Step 2: decide how many, and what the second one does to checkout Pick the currencies you have already been paid in. Then look at what the second one does to the code that creates subscriptions, because that is where the cost lands first. A subscription checkout resolves its currency in this order: 1. The workspace's own `billingCurrency`, if it has one from an earlier subscription or credit purchase. 2. An explicit currency on the request. 3. The currency on the plan version's first price variant. 4. Your organization's first billing currency, as a last resort. With one currency enabled, steps three and four can never disagree with each other. Add a second and price a plan in both, and the branch above them takes over: a plan version carrying more than one variant with no currency on the request does not quietly fall back to anything. It throws. > Plan version has multiple currencies. Please specify currency (e.g. usd, cad) when creating checkout. So the real consequence of a second currency is not a settings row. It is that every call site creating a checkout now has to decide a currency and say so, and the one you forget fails at the moment a customer tries to pay. Step four is worth knowing for a different reason: you do not choose which currency sits first. The handler de-duplicates and **sorts** the list before storing it, so an organization selling in `usd` that adds `aud` gets `["aud", "usd"]` back, and Australian dollars become the last-resort currency. On a subscription that rarely decides anything, because a price variant almost always carries its own currency. On a credit-pack purchase it decides more often: that path consults the org list _before_ the variant, so the alphabetically-first code is the one a credit purchase falls back to. As for how many: fewer than the form tempts you into. BuildBase ships support for 21 currencies and sells its own paid plans in one, at $19, $49 and $99 a month. Twenty-one is a capability. One is a pricing decision, and they are not the same number. > **Key takeaway:** Every currency you enable is a price that every plan version you publish > afterwards has to carry, once for every billing interval you offer. A seventh > currency added in month nine is a fresh variant on each version you ship from > then on, carrying a price for every interval you sell. ### Step 3: save the list ```bash curl -X PATCH https://api.console.buildbase.app/api/organizations/settings/config \ -H "Authorization: Bearer 665f1a2b3c4d5e6f7a8b9c0d:your-token-secret" \ -H "Content-Type: application/json" \ -d '{"billingCurrencies": ["usd"]}' ``` Or set it on the organization settings page in the console, which is what the Get Started checklist links to. Now the part worth reading twice. **That PATCH merges. It never removes.** The handler takes what you already hold, adds what you sent, de-duplicates and sorts, and stores the union. Send `["eur"]` to an org holding `["usd"]` and you now bill in both. There is no removal route, and the code comment says so plainly: the PATCH never removes one. So the result of this step is a list you live with: the only way to shorten it is a migration, not a setting. ### Step 4: price a plan version in every currency you enabled Publishing a plan version runs a guard that checks it has a pricing variant for every currency your organization bills in. The bar is set by the org's current currency list, not by the version you copied from, so a currency added after v1 shipped is a currency v2 has to carry before it will publish. [Changing pricing without affecting existing customers](/guides/plan-versioning-nextjs) covers the versioning mechanics around that guard. You should see a publish refused with a missing-variant complaint until every enabled currency has a price. That refusal is the currency list catching up with you. ### Step 5: watch a workspace lock Subscribe a demo workspace, then read it back. Its `billingCurrency` is now set, and it is set once: the service that writes it only does so when the field is empty. ```ts // server-side, on first subscription if (workspace && !workspace.billingCurrency) { await workspaces.updateById(orgId, workspaceId, { billingCurrency: currency, }); } ``` The code comment above that function gives the reason in one line: Stripe allows one currency per customer. A credit purchase sets the same field, so a workspace can be locked by buying a credit pack before it ever subscribes to anything. ### The failure modes **"At least one currency is required (e.g. usd, cad)."** You sent an empty array hoping to clear the list. Merging an empty array into an empty list leaves nothing, and an org that bills in no currency cannot price anything, so the save is refused. It is what you get for reaching for the settings API as a removal tool. **"Unsupported currency codes: CNY. Only these are allowed: USD, EUR, ..."** A code outside the 21. The message lists the full permitted set, so paste it and pick again. **A refused PATCH when you are on a smaller plan.** The number of currencies an org may hold is itself a plan limit, and where that limit is enforced it is measured on growth only. A request that adds nothing to what you already hold passes through untouched. That matters if you downgrade. An org can legitimately hold more currencies than its current plan allows, because nothing can take one back, and refusing the no-op would trap it. **"You cannot combine currencies on a single customer."** This one is Stripe's, not ours. It is the end state this guide exists to avoid. You tried to subscribe a customer who already has a default currency to a price in another one. ### Why Stripe makes this permanent A Stripe Customer has one default currency. It is set by the first thing that needs one, and `currency` is not a writable field on customer create or update, so you cannot simply correct it later. While any of these exists in the old currency, the customer stays pinned to it: - active subscriptions, meaning any status other than canceled - not-started or active subscription schedules - discounts - draft or open quotes - pending invoice items, the ones not yet attached to an invoice Stripe's documented position on the subscription half is flat: you can't have two active subscriptions with different currencies. Moving a customer anyway is a real procedure, not a toggle. Create the products and prices in the new currency. Void the open discounts, invoice items, invoices and quotes sitting in the old one. Convert any customer balance with balance transactions, because a credit balance is held per currency and a CAD invoice will not spend a USD credit. Cancel the old subscription with [prorations disabled](/guides/proration-on-plan-change-nextjs), then create the new one using the previous subscription's period end as the billing cycle anchor so the customer is not billed twice for one month. The parameter names for the proration and anchor behaviour are in Stripe's API reference rather than in the migration article, which carries no code at all. (Stripe behaviour verified 12 October 2026.) Not every customer is stuck, and anyone testing this will find that out fast. Once every subscription, schedule, discount, quote and pending invoice item in the old currency is gone, the next billing object in a new currency re-sets the default. So the permanence is really about customers with live billing, which is to say customers who are paying you. ### What multi-currency prices do and do not fix Stripe supports several currency options on one Price object, which is the documented way to sell in several currencies while each customer stays on one. Use it. It still does not hand you a switch for an existing customer. Two details decide how it behaves. All your prices must share the same default currency. And if you create subscriptions directly rather than through Checkout, the extra currencies do nothing until you pass the `currency` parameter, so the subscription quietly uses the price's default. Checkout picks the local currency from the customer's IP address, which is a different mechanism from the customer-level default and worth not confusing with it. Stripe's newer Adaptive Pricing for subscriptions lands in the same place. Its own documentation says the chosen currency remains locked in until the subscription is canceled, and that existing subscriptions are not affected. Each of these routes still settles a customer on one currency for as long as their subscription is live. ### The decision this one gets confused with If you are deciding how the prices themselves are presented rather than which currencies exist, [an annual and monthly toggle in Next.js](/guides/annual-and-monthly-toggle-nextjs) covers the display-versus-billing distinction. ```bash npm i @buildbase/sdk ``` --- ## Should you run auth on your own domain? > A custom auth domain is close to a one-way door for passkeys, and a DNS record that becomes part of your login path. Here is how to decide, and how to move before anyone signs in. - Source: https://www.buildbase.app/guides/should-you-run-auth-on-your-own-domain - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-13 - Updated: 2026-10-20 ### In short Decide before your first user signs in. WebAuthn binds every passkey to the hostname of your auth pages, so moving to a custom domain afterwards leaves existing passkeys inactive. A custom domain also puts a DNS record in your login path, re-checked every 6 hours. The shared platform host never breaks that way. The advice you will get is that your own domain looks more professional. That is true, and it is not the reason to decide. The reason is that the choice is close to permanent. WebAuthn binds every passkey to the hostname that ran the ceremony, so the domain you sign people in on today is the domain their passkeys belong to. Move it later and those credentials do not come with you. So the question is not whether `auth.example.com` reads better than a shared host. It is whether you are willing to own a DNS record that is now part of your login path, and whether you will decide before anyone enrols rather than after. > **Key takeaway:** If you want a custom auth domain, set it up before your first user signs in. > Adding one later leaves every existing passkey inactive, because the relying > party ID moves with the hostname. If you are not going to treat that DNS > record as production infrastructure, the shared platform host is the better > choice, and it cannot break this way. ### What you are building One verified custom domain serving your organization's sign-in pages. When it works, your sign-in page loads from a hostname you own, the console shows the certificate as issued, and every auth flow resolves to that origin instead of the platform default. In the Domains tab the entry carries a Verified badge. The DNS record stays listed underneath it, which is reference rather than an outstanding request. > **Before you start:** An organization on a plan that includes custom auth domains, DNS access for a > domain you own (a subdomain is normal and is what most teams use), and > agreement on the hostname you intend to keep. That last one is not padding. It > is the whole post. The adjacent decision, how many auth clients to create and > which redirect URLs go on each, is [its own > guide](/guides/auth-clients-redirect-urls-and-environments). ### Step one: settle the hostname before anyone enrols The relying party ID is derived from your auth domain and nothing else: ```ts // Derive the WebAuthn relying party from the hosted auth UI base URL. export function toRelyingParty(authBaseUrl: string): { rpID: string; origin: string; } { const url = new URL(authBaseUrl); return { rpID: url.hostname, origin: url.origin }; } ``` That base URL is the org's verified custom domain when there is one, and the platform host otherwise. There is no second input, no override, no setting that decouples the two. Change the domain and you change the relying party. What this looks like to a user is quieter than an error. The browser simply does not offer the passkey, because as far as it is concerned the credential belongs somewhere else. A passkey stores the `rpId` it was registered under, and when your app lists them each one carries an `active` flag comparing that stored value against the current auth domain. An inactive passkey is a perfectly good credential for a hostname you walked away from. The enrolment side of all this is in [how to add passkeys in Next.js](/guides/passkeys-nextjs). So pick the hostname you expect to still be using in three years. If that is the platform host, stop here, and skip to the last section before you spend an afternoon on DNS. ### Step two: add the domain Adding is a POST to the auth domains route, which is where you meet the refusals. Four of them are worth knowing before you hit one: - **402** from the plan gate. The feature gate runs first, then the plan's own limit on how many domains you may attach. It answers with the numbers, which is what lets the console draw a usage meter instead of a shrug. - **403 at 25 domains**, by default. This is an infrastructure ceiling rather than a plan limit. Every domain lands on a shared hosting project, so no plan moves this number, and the refusal deliberately says nothing about upgrading. Offering an upgrade for a ceiling nobody can raise would be a lie. - **409 `DOMAIN_TAKEN`.** The registry is global and first-come, and a unique index on the name is what decides the race, so two organizations claiming the same hostname at the same moment cannot both win. If another organization holds the name, it has to be removed there before you can take it. A name your own organization already holds comes back as a 400 instead. - **400 for a public suffix.** You cannot attach `com`, `co.uk` or `github.io`. Those are not domains anyone owns, and attaching one would be either a mistake or a land grab. The order matters here. The registry reservation happens before the domain is attached, and it is rolled back if the attach fails, so a refused attach does not normally leave a name squatted on the way out. The rollback is best effort: if it fails too, that is logged rather than retried. ### Step three: point DNS, and verify inside 24 hours The console shows you the record. In the common case it is a CNAME: ```text CNAME auth.example.com cname.vercel-dns.com. ``` If the platform returns more specific verification records for your domain, the console renders those instead, and you should use what it shows rather than what this guide shows. Add the record, then run verification from the Domains tab. > **Warning:** A domain that has never verified is deleted 24 hours after you add it. The > cleanup runs hourly, removes the domain from the hosting project and the > organization, and drops its registry entry, releasing the name. That last part > is the one that stings: the name goes back to first-come, so a half-finished > setup you left over a long weekend is a name somebody else can take. Once verification succeeds, the resolver returns your custom origin for the organization and caches that answer for an hour. Sign-in now comes from your hostname. Passkeys registered from this point forward are bound to it. ### What breaks later, and how you find out Verified is not a state you reach and keep. A cron re-checks every registered domain every 6 hours: ```ts registerCron(queue, { pattern: '0 */6 * * *' }, 'domain-revalidation-cron', { type: JOB_TYPES.SWEEP, }); ``` A single negative answer does not count. It schedules re-checks at 5, 15 and 30 minutes, four checks in total, and only the fourth marks the domain unverified. An API error never unverifies anything at all, because "the provider says this domain is not verified" and "we could not reach the provider" are different answers and only one of them is about your DNS. When the fourth check still says no, the domain is marked unverified, the resolver cache is dropped, and the next auth request falls back to the platform host. Your sign-in page keeps working. Your passkeys do not, because the relying party ID just moved. Two softenings are built into that, and both exist for the same reason: The domain is not deleted. Cleanup only removes domains that never verified at all. One that verified once and broke afterwards is kept, unverified, waiting for you, because deleting it would mean re-adding and re-verifying before anyone's passkey worked again. Recovery needs no human. Fix the record and the next sweep's first positive answer restores the domain on its own. There is one more piece of defensiveness worth knowing about, because it tells you how seriously the system takes this hostname. If the registry lookup itself fails, the resolver does not fall back to the platform host. It serves the last domain it saw verified, on the grounds that a failed lookup is a bad reason to make everybody's passkeys look stale. ### When the shared host is the right answer Honestly: more often than teams assume. The shared platform host has no DNS record to misconfigure, no certificate to renew, no revalidation that can flip you back, and no 24-hour window to miss. It is one less piece of infrastructure between a user and a session, and the failure mode described above simply does not exist for it. If your sign-in page is one hop in a flow nobody lingers on, that is a real argument and not a consolation prize. A custom domain earns its keep when the hostname is doing work: when users would notice being bounced to a name they do not recognise, when [cookies need to sit under a domain you control](/guides/session-cookie-not-shared-across-subdomains), or when you are selling to people who read the URL bar before they type a password. Those are good reasons. "It looks more professional" is a preference, and preferences are a thin justification for taking on a dependency that can unverify itself at four in the morning. Either way, decide it once, early, and write the decision down somewhere your future self will look. The expensive version of this is not choosing wrong. It is choosing twice. ```bash npm i @buildbase/sdk ``` --- ## How to create a default workspace on signup in Next.js, but not for invited users > Create a default workspace on signup in Next.js without giving invited users an empty one of their own, and decide when to ask for a name instead. - Source: https://www.buildbase.app/guides/auto-created-first-workspace-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 - Updated: 2026-10-22 ### In short Auto-create the first workspace only for users nobody invited. BuildBase makes one the first time a user lists workspaces, which suits a solo app. In a team app, turn auto-create off, show pending invitations first, and ask everyone else for a name: the workspace owns the trial and the Stripe customer. "Create a workspace when someone signs up" is a rule that cannot see invitations. Your customer [invites a colleague](/guides/team-invitations-nextjs). The colleague follows the link, registers, and the rule fires. Now they have two workspaces: the team's, and an empty one with their own name on it. That second one holds a trial nobody has used, it counts toward the workspace ceiling on your plan, and it sits in their switcher until somebody deletes it. Both behaviors ship in products you have probably used. Murf's help center says that on its Enterprise plan, an invitee who signs up through the link joins the inviter's workspace and also gets ["a separate free workspace of your own"](https://help.murf.ai/creating-a-workspace). Screenly's docs say the opposite: ["No new workspace is created for you and no trial starts."](https://www.screenly.io/docs/workspaces/overview/one-account-many-workspaces/) Neither is a bug. They are two answers to a question most "create a default workspace on signup" tutorials skip: who is the first workspace for? Here is mine. Auto-create the first workspace only for the user nobody invited. In a solo product, create it silently and never mention it. In a team product, ask the first person for a name, and give the invitee nothing of their own. ### What BuildBase does before you write any code It creates one for you, lazily. Not at sign-up: the first time anything lists a user's workspaces and finds none, the server makes one on the spot and returns it in the same response. That listing can come from anywhere. The `WorkspaceSwitcher` fetches the list when it mounts, so does `fetchWorkspaces()` from `useSaaSWorkspaces`, and so does `bb().workspace.list()` on the server. Whichever runs first creates the workspace. The rest of what happens is in the route that serves the list: - **The name** is the first two words of the user's name plus `'s Workspace`, or `My Workspace` when the account has no name. The user is its admin. - **The caps still apply.** A per-user workspace limit and your plan's ceiling both get a say, exactly as they do when a user creates one by hand. The one setting skipped is **Can Create Workspace**, because that one is about the user's own "New workspace" button, not about the platform giving them a first one. - **A refusal is an empty list,** not an error. The server logs it, and when it was your plan's org-wide ceiling your organization is told, but the browser only ever sees `[]`. - **Two tabs cannot make two.** Two first loads at once both see "no workspaces", so with Redis running the route takes a 30-second claim: one request creates, the other re-reads what it made. - **It fires `workspace.created`,** the same event the explicit create route fires. We learned this one the hard way. Until we fixed it on 24 September it did not, so any workflow hung on that event never ran for an auto-created workspace. We found it setting up example orgs on a local stack wired like production, where a "Workspace Created" workflow grants 20 credits. It had zero runs, and the new user started at 0. Both workspace modes ship with auto-create on. A new organization starts in **Personal** mode, one user and one workspace, where the switch cannot be turned off at all. **Platform** mode, for shared and invitable workspaces, also starts with it on. And our own docs say plainly what that means for an invitation: a waiting one ["does not change what a user's first load does"](https://docs.buildbase.app/workspaces/invitations), so with auto-create on, an invited user ends up with their own workspace and the invited one beside it. That is the default. Whether to keep it is the decision. ### Who the first workspace is for Three people sign up to a product, and they want three different things. | Who signs up | What they should get | Why | | -------------------------------- | ---------------------------- | ----------------------------------------------------- | | Someone using a solo product | One workspace, made quietly | Nobody else will ever see its name | | The first person from a new team | One workspace, named by them | The name goes out on invitations and onto the invoice | | Someone a teammate invited | Nothing of their own | Their workspace already exists | **The solo user** should never see the word "workspace" during sign-up. In a product built for one person, the workspace is the account, and asking them to name it is a question with no audience. This is what Personal mode does, it is the default for a reason, and if it describes your product you can stop reading here. Personal's preset also switches invitations off, and the server refuses to switch them back on in that mode, so the invitee row of that table does not apply to you. **The invitee** should get nothing. Their workspace exists; somebody else made it and invited them into it. An auto-created second one is not harmless clutter: - **It is a trial.** BuildBase stamps `trialUsedAt` on the workspace, and checkout reads that workspace when it decides whether a trial is still on offer. By default it also counts people, once each: the workspace's owner and whoever checks out. So an invitee who has never had a trial owns an empty workspace with one waiting to be claimed. The console's help text under **Max Workspaces Per User** reads "Prevents trial abuse", and a workspace each is exactly what that cap counts. - **It counts.** Your plan's workspace ceiling is an org-wide count, and an invitee's empty workspace is in it. - **It is where they start.** When the list loads and nothing was saved from a previous visit, the SDK selects the first workspace in it. For an invitee who has not accepted yet, that is their own empty one. **The first person from a team** is where "silent or ask" is a real choice, and I would ask. The name is not private. The default invitation email's subject is `{{inviterName}} invited you to {{workspaceName}}`, so silent naming sends the next person "Demo User invited you to Demo User's Workspace". The same name is in the accept dialog they see, and, the first time the workspace goes to checkout, on the Stripe customer that BuildBase creates for it. Rename the workspace later and BuildBase renames that customer too. But Stripe stops updating `customer_name` on an invoice once the invoice is finalized, so every invoice already issued keeps saying "Demo User's Workspace". > **Key takeaway:** Ask for a name whenever a second person will ever see it. In a team product > that is every workspace, and the field costs one click if you prefill it. In a > solo product nobody sees it, so let it be created silently. The honest cost is one more screen between sign-up and the product. I do not have a number for what that screen costs, and you will not either until you measure it in your own funnel. Prefilling takes the typing out of it, not the screen. So if most of your sign-ups are individuals trying the product alone, silent creation wins, and the question to settle it is always the same: will anyone but this user ever read the name? ### Build it for a team app Four steps, and the order matters: step two lists workspaces on the server, and with auto-create still on, that check creates the very thing it is checking for. > **Before you start:** A Next.js App Router app with BuildBase sign-in working and the server helper > `bb()` from [BuildBase on Next.js](/guides/buildbase-on-nextjs). An > organization in Platform mode: new organizations start in Personal mode, and > moving to Platform depends on your BuildBase plan. Invitations also need an > email sender configured in the console, or sending one answers 503. ### Step one: turn auto-create off in the console In the console, open **Workspaces**, then **Workspace Settings**. With Platform selected as the mode, switch on **Advanced Overrides**, turn **Auto-Create First Workspace** off and save. That writes `autoCreateFirst: false` to your organization's workspace settings. Leave **Can Create Workspace** on **Everyone**. The switch's own help text says "Off = users must be invited", and that is only true if you also turn creation off; the console labels that pair "Invite only". With creation left on, the screen you build next is how an uninvited user gets their first workspace. What you should see: sign up as a brand-new user who has no invitation, and the workspace switcher shows an empty state instead of "Demo User's Workspace". Sign up as someone with a pending invitation and the empty state lists it. ### Step two: send anyone without a workspace to onboarding Do the routing on the server, where nothing renders until the answer is in. Every page in the app group lists the user's workspaces first: ```tsx // app/(app)/layout.tsx import { redirect } from 'next/navigation'; import { bb } from '@/lib/buildbase'; export const dynamic = 'force-dynamic'; export default async function AppLayout({ children, }: { children: React.ReactNode; }) { const workspaces = await bb() .workspace.list() .catch(() => null); if (!workspaces) redirect('/'); if (workspaces.length === 0) redirect('/onboarding'); return <>{children}; } ``` And the onboarding page does the reverse, so a user who already has a workspace never lands on it: ```tsx // app/onboarding/page.tsx import { redirect } from 'next/navigation'; import { bb } from '@/lib/buildbase'; import { FirstWorkspace } from './first-workspace'; export const dynamic = 'force-dynamic'; export default async function OnboardingPage() { const workspaces = await bb() .workspace.list() .catch(() => null); if (!workspaces) redirect('/'); if (workspaces.length > 0) redirect('/dashboard'); return ; } ``` What you should see: a brand-new user who opens `/dashboard` lands on `/onboarding`. A user with a workspace goes straight through, and one who types `/onboarding` by hand is sent back to `/dashboard`. ### Step three: show invitations first Invitations first; everyone else names it. The SDK already has both halves: `WhenPendingInvitations` renders its children only when the signed-in user has an invitation waiting, and its fallback when they have none. ```tsx // app/onboarding/first-workspace.tsx 'use client'; import { useRouter } from 'next/navigation'; import { PendingInvitations, WhenPendingInvitations, } from '@buildbase/sdk/react'; import { NameYourWorkspace } from './name-your-workspace'; export function FirstWorkspace() { const router = useRouter(); const done = () => router.replace('/dashboard'); return ( One moment...

} fallbackComponent={} >
); } ``` `` switches to the workspace on accept by default, so `onAccepted` only has to move them on. Declining drops the invitation from the list, and with nothing left waiting, the fallback takes over and asks them to name a workspace of their own. That is the right outcome for someone who said no. What you should see: an invited user gets the invitation with Accept and Decline, accepts, and lands in the team's workspace with no other in their switcher. If they arrived through the emailed link, the SDK's own accept dialog opens as well; either route ends in the same workspace. ### Step four: ask everyone else for a name In practice "everyone else" is the first person from a new team. They get one field, prefilled so the common case is a single click: ```tsx // app/onboarding/name-your-workspace.tsx 'use client'; import { useState } from 'react'; import { useSaaSAuth, useSaaSWorkspaces } from '@buildbase/sdk/react'; // Domains that say nothing about the company. Extend for your audience. const PERSONAL_DOMAINS = new Set([ 'gmail.com', 'outlook.com', 'hotmail.com', 'yahoo.com', 'icloud.com', ]); function suggestName(user?: { name?: string; email?: string }) { const domain = user?.email?.split('@')[1]?.toLowerCase(); if (domain && !PERSONAL_DOMAINS.has(domain)) { const label = domain.split('.')[0]; return label.charAt(0).toUpperCase() + label.slice(1); } const first = user?.name?.trim().split(' ')[0]; return first ? `${first}'s team` : ''; } export function NameYourWorkspace({ onCreated }: { onCreated: () => void }) { const { user } = useSaaSAuth(); const { createWorkspace } = useSaaSWorkspaces(); const [name, setName] = useState(() => suggestName(user)); const [pending, setPending] = useState(false); const [error, setError] = useState(null); async function onSubmit(event: React.FormEvent) { event.preventDefault(); setPending(true); setError(null); try { await createWorkspace(name.trim()); onCreated(); } catch (err) { setError( err instanceof Error ? err.message : 'Could not create the workspace.' ); setPending(false); } } return (
setName(e.target.value)} minLength={2} required /> {error &&

{error}

}

Expecting an invitation? Sign in with the address it was sent to.

); } ``` The two-character minimum is the server's, not taste: it refuses a shorter name. The line at the bottom is for the address mismatch in the failure modes below. What you should see: the new workspace appears in the switcher, and about 300ms after `createWorkspace(name)` resolves, the SDK opens workspace settings on the subscription screen. That is the SDK, not this code. And it is the right next screen. The trial belongs to the workspace, so it should start on the one that was just named, picked by the person who named it rather than by whoever happens to sign up next. ### The failure modes **The check creates the workspace.** You built steps two to four and skipped step one. `bb().workspace.list()` is itself the auto-create trigger, so the layout's check mints "Demo User's Workspace" before it can redirect anyone, and `/onboarding` never appears. If no new user ever sees your name screen, look at the console switch first. **Personal mode refuses the switch.** Turning auto-create off there answers "Cannot disable auto-create in Personal mode. Users need a workspace on signup." That is correct. Personal mode also refuses to let users create workspaces themselves, so auto-create is the only way anyone gets a workspace of their own there. Switch to Platform first. **Invite-only by accident.** With **Can Create Workspace** set to **Disabled** and auto-create off, `createWorkspace` answers 403 with "Workspace creation is disabled for this organization." Your name screen becomes a dead end for everyone who was not invited. If that is the product you want, replace the fallback with "Ask your team for an invitation" instead of a form. **The invitee signed up with a different address.** Their invitation was sent to `demo@example.com` and they registered as `demo+work@example.com`. To this system those are two people, so no invitation is pending, step three falls through to the form, and they create a workspace of their own. That is why the form carries the "Sign in with the address it was sent to" line. The longer version of this hunt is in [an invited member who cannot see the workspace](/guides/invited-member-cannot-see-workspace). **A ceiling turns a new user away, quietly or loudly.** The automatic path answers a refused create with an empty list, which at the browser is indistinguishable from a bug. Your form gets the real answer: 402 when it is the plan's ceiling, 403 when it is your own setting, each with a message you can show. That is a small reason to prefer this design even where silent creation would do. **Welcome work hung on sign-up.** If a workflow grants starting credits or sends the onboarding email, hang it on `workspace.created`, not on the user's sign-up. An invitee should not get starter credits for a workspace they never made, and the 20-credit bug above is what it looks like when the event and the work drift apart. **A double click.** The server refuses a second workspace with the same name from the same user ("Workspace with name ... already exists"), but that is a read before a write, and two requests in the same instant can both pass it. The disabled button is what actually stops the double click. Keep it. Everything here assumes [the workspace, not the user, owns the trial and the bill](/blog/what-is-multi-tenancy), unless the plan is sold to a person. If that is not settled yet in your app, settle it first: [multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon) makes that case, and [a free trial without a card](/guides/free-trial-without-a-card-nextjs) covers what happens once the trial this guide hands to the right workspace starts. I have not run these snippets end to end as one app. The server calls are the `bb()` helper from the Next.js setup guide, the components and hooks are the SDK's own exports as its type definitions declare them, and every server behavior described above is read from the route that serves the workspace list. ### Install ```bash npm i @buildbase/sdk ``` --- ## How to add per-org data isolation in Next.js > Per-org data isolation in Next.js: check membership once per request, make the data layer demand that proof, and never fetch a record by its ID alone. - Source: https://www.buildbase.app/guides/per-org-data-isolation-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 - Updated: 2026-11-04 ### In short Per-org data isolation in Next.js scopes every query against your own tables to a workspace the server verified for this user. BuildBase isolates its own records per org but never sees your tables. Check membership once per request, make the data layer demand that proof, and fetch records by ID and workspace together. Ask how to isolate each customer's data in a Next.js app built on BuildBase, and half the answer already exists. The other half lives in your own tables, and it comes down to one rule: no query in your app ever receives a workspace ID as a plain string. The names cross over, so settle them first. In BuildBase, the **organization** is you: the account you created in the console, which owns your users, plans and settings. Your customers' orgs are **workspaces**. Per-org isolation for your product means [per-workspace isolation](/blog/what-is-multi-tenancy), inside a database BuildBase has never seen. Most Next.js multi-tenancy guides that rank today warn against trusting an org ID from the client. Then they read the active org out of their auth provider's session, or list three places it could come from and leave the choice to you. With BuildBase there is no active workspace in the session to read. The session names the org and the user. Which workspace is open is [a choice the browser makes and keeps in its own storage](/guides/stale-data-after-workspace-switch), and a server component only learns it when the request says so. So the request names the workspace. This guide is about what your server does with that name. ### What BuildBase isolates, and what it never sees BuildBase isolates its own records per organization and checks workspace membership on its own API. Your tables get none of that unless you write it. Each organization's users, workspaces, subscriptions and usage live in that organization's own MongoDB database. The authenticated API never takes the org from the request: it looks up the session that the `x-session-id` header names and reads the org off the stored record. Queries in our tenant server then take the org as their first argument, `find(orgId, filter)`, and that argument is what picks the database the query runs against. Inside your organization, BuildBase checks the caller on its workspace routes. Members, invitations, subscription, usage and credits all sit behind a guard that asks whether the session's user belongs to the workspace in the path. Call `bb().usage.record(workspaceId, ...)` for a workspace the user is not in and BuildBase answers 403, whatever your code passed. | Boundary | Who holds it | | -------------------------------------------------------------- | -------------------------------------------------------- | | Your organization's data, apart from every other BuildBase org | BuildBase: one database per org, picked from the session | | Membership, on BuildBase's own workspace calls | BuildBase: a guard on its workspace routes | | Which workspace this request is for | You: the URL | | Membership, before your code touches your tables | You ask, BuildBase answers: `workspace.permissions()` | | Your rows, filtered to that workspace | You: every query | The first row costs us something, not you. A database per org means a connection per active org, and roughly 1,000 orgs per deployment is [the connection-pool ceiling](/guides/connection-pool-exhausted-multi-tenant) we plan against. Your workspaces share your org's database instead of getting one each, so the limit you meet is the workspace count on your plan. Not a connection limit. [Database-per-tenant versus shared schema](/blog/database-per-tenant-vs-shared-schema) is the same decision made one level down, and the last three rows above are its shared-schema half. They are yours. > **Before you start:** Sign-in working through [BuildBase on Next.js](/guides/buildbase-on-nextjs), > so `bb()` and its `bb-session-id` cookie exist. Next.js 15 or later on the App > Router; on 14, `params` is a plain object, so drop the `await` in front of it. > `@buildbase/sdk` 0.0.73 or later, the release that added > `workspace.permissions()`. And a table of your own to protect: the examples > use Postgres through [postgres.js](https://github.com/porsager/postgres), but > the shape holds for any database. ### Step 1: put the workspace in the URL Every page that shows workspace data lives under `app/w/[workspaceId]/`, and every API route under `app/api/w/[workspaceId]/`: ``` app/ w/[workspaceId]/ layout.tsx nav and switcher - not the guard projects/ page.tsx actions.ts api/w/[workspaceId]/projects/[projectId]/ route.ts lib/ buildbase.ts bb() and getSessionId, from the setup guide workspace.ts the only file that verifies a workspace data/projects.ts the only file that queries your tables ``` Why the URL? A server component cannot read browser storage, and the session holds no workspace. A cookie would work, but it holds one workspace for the whole browser: switch in a second tab and the first tab's next form post lands in the other workspace. The [Remix version of this guide](/guides/multi-tenant-workspaces-remix) walks through that failure, and nothing about it changes in Next.js. A path segment gives every tab its own workspace and puts the ID in every access log you already keep. Use the workspace's `_id`. The workspace object also has a field called `workspaceId`, which holds a different value, and BuildBase answers 400 for it. At this point any ID typed into the address bar reaches your page. The next step decides which ones get any further. ### Step 2: turn the ID into a verified workspace, in one file ```ts // lib/workspace.ts import { cache } from 'react'; import { notFound, redirect } from 'next/navigation'; import { bb } from '@/lib/buildbase'; declare const verified: unique symbol; /** A workspace the signed-in user was checked against. Only this file makes one. */ export type VerifiedWorkspace = { readonly id: string; readonly role: string | null; readonly isOwner: boolean; readonly permissions: string[]; readonly [verified]: true; }; export type WorkspaceCheck = | { ok: true; workspace: VerifiedWorkspace } | { ok: false; reason: 'signed-out' | 'no-access' }; export const checkWorkspace = cache( async (workspaceId: string): Promise => { if (!(await bb().auth())) return { ok: false, reason: 'signed-out' }; try { const access = await bb().workspace.permissions(workspaceId); // The one place the brand is granted. const workspace = { id: workspaceId, ...access } as VerifiedWorkspace; return { ok: true, workspace }; } catch (err) { const status = (err as { status?: number }).status; if (status === 401) return { ok: false, reason: 'signed-out' }; if (status === 400 || status === 403 || status === 404) { return { ok: false, reason: 'no-access' }; } throw err; // a timeout or a 5xx: fail closed } } ); /** For pages and layouts: the verified workspace, or sign-in, or a 404. */ export async function workspaceForPage(workspaceId: string) { const check = await checkWorkspace(workspaceId); if (check.ok) return check.workspace; if (check.reason === 'signed-out') redirect('/'); notFound(); } ``` `workspace.permissions()` asks BuildBase [what the session's user may do in that workspace](/guides/roles-and-permissions-per-workspace-nextjs) and gets back `{ role, isOwner, permissions }`, resolved on the server from the workspace's own members. The [permissions docs](https://docs.buildbase.app/permissions/overview) show the endpoint underneath it. A string that is not a valid ID gets a 400. A workspace the user is not in gets a 403, and so does one that does not exist, so nobody can probe for which IDs are real. The `status` sits on the thrown error but not in the SDK's types, hence the cast. Only one of the two refusals is about the session. `bb().auth()` checks that a session cookie is there, not that it is still alive, so an expired session surfaces as a 401 from BuildBase and lands in `signed-out` too. Everything else is `no-access`, and it must never look like a dead session. BuildBase's own guard once answered 401 here, and signed people out for opening a workspace they had lost access to; the [Express version of this guide](/guides/multi-tenant-workspaces-express) tells that one. The branded type is the point of the file. `VerifiedWorkspace` carries a marker that exists only inside `lib/workspace.ts`, so the one honest way to get a value of that type is `checkWorkspace()`. Anywhere a `VerifiedWorkspace` is required, TypeScript refuses a string. `cache()` lets a layout and a page that both ask in one render share one round trip. It does nothing anywhere else, and the Next.js docs say so plainly: Server Actions and Route Handlers "are not part of a render pass, so the wrapper does nothing and every call runs the function." So each of them asks BuildBase afresh. In front of a write, that is the behaviour you want. What you should see: `checkWorkspace()` with your own workspace's `_id` returns `ok: true` and your role. Any other ID returns `no-access`. ### Step 3: make your data layer refuse a plain string This is the decision our docs leave to you: where the check lives. The tempting answer in Next.js is `app/w/[workspaceId]/layout.tsx`. Check membership there, call `notFound()`, and every page underneath looks guarded. It is not, and Next.js says so too. Layouts "don't re-render on navigation", and "a layout also does not control whether the rest of the route renders". Server Actions do not pass through the layout's check at all: they arrive as a POST, and the docs tell you to treat them "with the same security considerations as public-facing API endpoints." A check in the layout is a courtesy to the user. The guarantee has to sit where the data is read. So put it in the signature. Every function that touches a workspace's rows takes a `VerifiedWorkspace` as its first argument, the way queries in BuildBase's own server take the org first. The table carries the workspace, not the user who created the row, because [the workspace owns the data](/guides/multi-tenant-workspaces-in-an-afternoon) and people come and go: ```sql create table projects ( id uuid primary key default gen_random_uuid(), workspace_id text not null, -- the BuildBase workspace _id name text not null, created_at timestamptz not null default now() ); create index projects_workspace_idx on projects (workspace_id, created_at desc); ``` ```ts // lib/data/projects.ts import postgres from 'postgres'; import type { VerifiedWorkspace } from '@/lib/workspace'; const sql = postgres(process.env.DATABASE_URL!); export type Project = { id: string; name: string }; export async function listProjects(ws: VerifiedWorkspace) { return sql` select id, name from projects where workspace_id = ${ws.id} order by created_at desc `; } export async function createProject( ws: VerifiedWorkspace, input: { name: string } ) { const [project] = await sql` insert into projects (workspace_id, name) values (${ws.id}, ${input.name}) returning id, name `; return project; } ``` A page gets its workspace from step 2 and hands it down: ```tsx // app/w/[workspaceId]/projects/page.tsx import { listProjects } from '@/lib/data/projects'; import { workspaceForPage } from '@/lib/workspace'; import { createProjectAction } from './actions'; export default async function ProjectsPage({ params, }: { params: Promise<{ workspaceId: string }>; }) { const { workspaceId } = await params; const workspace = await workspaceForPage(workspaceId); const projects = await listProjects(workspace); return ( <>
    {projects.map((p) => (
  • {p.name}
  • ))}
); } ``` The Server Action gets no workspace from the page. The bound `workspace.id` travels back from the browser as an ordinary argument, and anyone can call the action with a different one: ```ts // app/w/[workspaceId]/projects/actions.ts 'use server'; import { revalidatePath } from 'next/cache'; import { createProject } from '@/lib/data/projects'; import { checkWorkspace } from '@/lib/workspace'; export async function createProjectAction( workspaceId: string, formData: FormData ) { // Anyone can call this action, with any workspaceId. Check it here. const check = await checkWorkspace(workspaceId); if (!check.ok) throw new Error('No access to this workspace.'); await createProject(check.workspace, { name: String(formData.get('name') ?? ''), }); revalidatePath(`/w/${check.workspace.id}/projects`); } ``` What you should see: delete the `checkWorkspace` line, pass `workspaceId` straight to `createProject()`, and the build stops with `Argument of type 'string' is not assignable to parameter of type 'VerifiedWorkspace'.` That error is the boundary doing its job. Then run `grep -rn 'as VerifiedWorkspace' app lib`: it should print one line, in `lib/workspace.ts`. A second line is someone minting the brand by hand, and it is the one line in a pull request worth reading twice. > **Key takeaway:** Do not rely on the layout to guard workspace data. Make every function that > reads or writes it take a `VerifiedWorkspace`, which only `checkWorkspace()` > can produce. Then no page, Server Action or Route Handler can reach your > tables without the membership check having run first. ### Step 4: look records up by ID and workspace together The membership check answers one question: may this user be in workspace A? It says nothing about the project ID in the same URL. Fetch that project by ID alone and a member of A can open a project from workspace B by pasting its ID under A's path. The check passed. It checked the wrong thing. We found this shape in our own server. A tenant audit in September looked at BuildBase's invoice lookup, and the comment above the fix records what it found: "Without this check any member of the org could pull any other workspace's invoice by id." The SDK had been sending the workspace ID with every invoice request all along. Nothing on the server compared the two. The fix resolves the workspace's own Stripe customer first and refuses any invoice billed to another, and a foreign invoice now answers 404. In your tables, every lookup by ID carries the workspace too: ```ts // lib/data/projects.ts (continued) const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export async function renameProject( ws: VerifiedWorkspace, projectId: string, name: string ) { if (!UUID.test(projectId)) return null; // not a uuid: it cannot exist const [project] = await sql` update projects set name = ${name} where id = ${projectId} and workspace_id = ${ws.id} returning id, name `; return project ?? null; } ``` ```ts // app/api/w/[workspaceId]/projects/[projectId]/route.ts import { renameProject } from '@/lib/data/projects'; import { checkWorkspace } from '@/lib/workspace'; type Params = Promise<{ workspaceId: string; projectId: string }>; export async function PATCH(request: Request, { params }: { params: Params }) { const { workspaceId, projectId } = await params; const check = await checkWorkspace(workspaceId); if (!check.ok) { return check.reason === 'signed-out' ? Response.json({ message: 'Sign in first.' }, { status: 401 }) : Response.json( { message: 'No access to this workspace.' }, { status: 403 } ); } const { name } = (await request.json()) as { name?: unknown }; if (typeof name !== 'string' || !name.trim()) { return Response.json({ message: 'A name is required.' }, { status: 400 }); } const project = await renameProject(check.workspace, projectId, name.trim()); if (!project) return Response.json({ message: 'Not found.' }, { status: 404 }); return Response.json(project); } ``` A project from another workspace is a 404, not a 403. To this user it does not exist, and a 403 would confirm the ID is real. Now look at what the handler does with a `workspaceId` in the request body: nothing. `renameProject()` takes the workspace from `ws.id` and the name from the body, and it has no parameter where a second workspace could go. The classic version of this bug checks membership on the path's ID and then writes with the body's. Here a request carries one workspace, and it is the one that was checked. What you should see: create a project in workspace B, then send `PATCH` to `/api/w//projects/` while signed in as a member of both. You get a 404, because the URL said A and the row says B. ### Row-level security is the backstop, not the check Row-level security makes Postgres refuse rows from every workspace except the one set for the transaction. It cannot tell you whether that was the right workspace to set. Hand it an ID straight from the URL and Postgres will dutifully return that workspace's rows to whoever asked. So it does not replace step 2. It catches the query someone writes outside `lib/data/`, and the one that forgets its `where`. ```sql alter table projects enable row level security; alter table projects force row level security; create policy workspace_isolation on projects using (workspace_id = current_setting('app.workspace_id', true)) with check (workspace_id = current_setting('app.workspace_id', true)); ``` Then each data-layer function sets the verified ID inside its own transaction, and keeps its `where` clause: ```ts export async function listProjects(ws: VerifiedWorkspace) { return sql.begin(async (tx) => { await tx`select set_config('app.workspace_id', ${ws.id}, true)`; return tx` select id, name from projects where workspace_id = ${ws.id} order by created_at desc `; }); } ``` The `true` in `set_config` makes the setting last only for the current transaction, which is what stops a pooled connection from carrying one request's workspace into the next request. When nothing is set, `current_setting(..., true)` gives back a null or an empty string, the comparison matches no row, and the query fails closed. And `force` is not decoration. Postgres lets table owners skip their own policies unless the table is forced, and superusers and roles with `BYPASSRLS` skip them always. If your app connects as the role that created the table, `force` is the line that makes the policy apply to it. No row-level security in your database? Then the data layer from step 3 is the whole boundary. That is a real boundary. Inside each org database, it is the kind BuildBase draws between your workspaces. ### When one customer wants its own database Some contracts require physical separation. That is the database-per-tenant side of the decision, and the hosting is often the smallest part of [what it costs](/blog/database-per-tenant-cost). Nothing above changes shape: `VerifiedWorkspace` picks the connection instead of filling the `where` clause, and step 2 is still the only way to get one. ### What breaks, and how you can tell | What you see | Why, and the fix | | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Every workspace page is a 404, even your own. | The URL carries the workspace's `workspaceId` field rather than its `_id`. BuildBase answers 400, and `checkWorkspace()` reports `no-access`. | | A non-member's request still runs a query under a guarded layout. | The check lives only in the layout. Pages, Server Actions and Route Handlers run without it. Make the data layer demand a `VerifiedWorkspace`, and a call that skips the check stops compiling. | | Removing someone from one workspace signs them out of all of them. | A membership refusal is mapped to 401 or a sign-in redirect. Only `signed-out` should do that. | | A project from another workspace opens under this one. | The query found the project by `id` alone, so add `and workspace_id = ${ws.id}` to it and answer 404 when nothing comes back. | | A malformed project ID answers 500 instead of 404. | Postgres refuses to compare a non-UUID string with a `uuid` column. Check the shape first, as `renameProject()` does. | | Row-level security is on and queries still return every workspace. | The app connects as the table owner on a table that is not forced, or as a superuser. | | The right person, the right workspace, still `no-access`. | BuildBase does not count them as a member. An accepted invitation that never became a membership looks exactly like this: see [an invited member who cannot see the workspace](/guides/invited-member-cannot-see-workspace). | ### Install ```bash npm i @buildbase/sdk ``` --- ## How to add roles and permissions per workspace in Next.js > Per-workspace roles in Next.js: hide controls with WhenPermission, check every server action with bb.workspace.can(), and know which side lags after a role change. - Source: https://www.buildbase.app/guides/roles-and-permissions-per-workspace-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Per-workspace roles in Next.js need two checks. WhenPermission decides what the browser shows. Every server action and route handler calls bb.workspace.can() before it acts, because hiding a button does not hide the action. BuildBase reads roles per request, so after a role change the browser is behind. `` hides the Delete button from a viewer. It does not stop a viewer deleting. In Next.js the delete is a server action, and the Next.js docs are blunt about what that means: Server Functions "are reachable via direct POST requests, not just through your application's UI." The button was one way to call it. Anyone holding the page has the others. So the real decision in [per-workspace roles](/blog/what-is-rbac) is where each permission gets enforced, and the split is cleaner than it sounds. BuildBase enforces its own `workspace:` permissions on its own API. Checkout, a plan change and cancelling need `workspace:billing:manage`; spending credits needs `workspace:usage:record`; changing someone's role needs `workspace:members:role-change`. A viewer who calls checkout directly gets a 403 whatever your UI rendered. Your permissions are a different animal. `app:reports:delete` is something BuildBase stores, resolves per role and answers questions about. It has never seen your server action and cannot guard it. That check is yours, in every action. What you are building: a **Delete report** button a viewer never sees, a server action that refuses a viewer who calls it anyway, and a role matrix where you chose what a new role can do instead of inheriting it. > **Before you start:** A Next.js App Router app with sign-in working and the `bb()` helper from > [BuildBase on Next.js](/guides/buildbase-on-nextjs), plus workspaces that hold > more than one person ([multi-tenant workspaces in an > afternoon](/guides/multi-tenant-workspaces-in-an-afternoon)). Personal mode > turns [invitations](/guides/team-invitations-nextjs) off, so there is nobody > to give a role to. `@buildbase/sdk` 0.0.73 or later, which added > `workspace.can()`. Custom roles and your own permissions are plan limits > (`max-custom-workspace-roles` and `max-custom-workspace-permissions`); without > them you still have the three built-in roles and BuildBase's own permissions. ### 1. Start from the three roles, and look at what a new one inherits Every organization starts with three workspace roles. There is no owner role: whoever creates a workspace is made its admin, and only they can delete it. Before you change anything, the roles hold this: | Role | What it holds by default | | -------- | ----------------------------------------------------------------------------------- | | `admin` | Every permission there is, yours included | | `editor` | View settings, members, features, billing and usage; record usage and spend credits | | `viewer` | View settings and members | Someone who joins without being given a role lands on `viewer`. You can pick a different default, but never `admin`: the server reads a stored default of `admin` as `viewer`, so admin is only ever handed out on purpose. The decision hiding in that table is what a role you add starts with. **A custom role starts as a copy of `editor`**, and `editor` holds `workspace:usage:record`: record metered usage, spend the workspace's credits. Add a `contractor` role for someone who should only read reports, assign it before you open its column, and they can spend the workspace's money. The irony is that this permission was added to close a gap of exactly this shape. Before it existed, says the comment above it in our constants, a `viewer` "could drain a workspace's credits or run up its metered Stripe bill." So set a new role's column before anyone holds it. Defaults are for the three roles you did not have to think about. One more thing to know before you design anything: **there is no permission an admin lacks.** Admin resolves to every key the organization knows, including one added after admin's column was last saved, and the console locks its switches on for that reason. If finance should approve refunds and your admins should not, the matrix cannot say so. That is a real limit, and it is better found here than in production. A rule like that belongs in your own code, against your own list of approvers, not against a role. What you should see: in the console under **Workspaces > Settings**, a permission matrix with BuildBase's twelve permissions as rows, your roles as columns, and the admin column locked on. ### 2. Define your permission in the console, not only in code Your permission has to exist somewhere the server can read it. That place is the console. Add it beside the matrix as a key, a label and an optional group. The key is what your code compares, so it is strict: lowercase letters, digits and `. : _ -`, up to 64 characters, with `workspace:`, `buildbase:`, `system:` and `org:` reserved. We use `app::`, which makes this guide's key `app:reports:delete`. Grant it to `editor` and leave `viewer` alone. Renaming, removal and the change history are in the [permissions docs](https://docs.buildbase.app/permissions/overview). Here is the trap. `SaaSOSProvider` also takes a `defaultPermissions` prop, and our own [checking permissions](https://docs.buildbase.app/permissions/checking-permissions) page still offers it as the way to add app permissions. A key that lives only in that prop resolves in the browser and nowhere else, because the server never reads your provider props. It knows the keys a matrix grants: the organization's, or a workspace's saved override. Put `app:reports:delete` in the prop alone and every editor sees the button, while the server action in step 4 refuses every one of them. Admins too, the workspace's creator included. What you should see: an `app:reports:delete` row in the matrix, on for `admin` (locked) and `editor`, off for `viewer`. ### 3. Hide the button in the browser This is the convenience half. It spares a viewer a button that could only fail. ```tsx // app/reports/delete-report-button.tsx 'use client'; import { useState } from 'react'; import { useSaaSWorkspaces, WhenPermission } from '@buildbase/sdk/react'; import { deleteReport } from './actions'; export function DeleteReportButton({ reportId }: { reportId: string }) { const { currentWorkspace, refreshWorkspaces } = useSaaSWorkspaces(); const [pending, setPending] = useState(false); const [error, setError] = useState(null); if (!currentWorkspace) return null; const workspaceId = currentWorkspace._id; async function onDelete() { setPending(true); setError(null); const result = await deleteReport(workspaceId, reportId); setPending(false); if (!result.ok) { setError(result.error); // This tab's copy of the member's role was out of date. Reload it. await refreshWorkspaces(); } } return ( {error &&

{error}

}
); } ``` `WhenPermission` answers for the current workspace, the one the switcher shows. The `refreshWorkspaces()` line looks odd until the section after step 4, which is about the moment it runs. What you should see: signed in as a viewer, no button. As an editor, the button. ### 4. Check again in the server action This is the step that makes it security. Put the question in one helper, so every action asks it the same way: ```ts // lib/permissions.ts import { bb } from '@/lib/buildbase'; /** * BuildBase's answer for the signed-in user. False when they are not a * member; throws when BuildBase cannot answer, so nothing runs on a guess. */ export async function can(workspaceId: string, permission: string) { try { return await bb().workspace.can(workspaceId, permission); } catch (err) { const status = (err as { status?: number }).status; if (status === 400 || status === 403 || status === 404) return false; throw err; } } ``` ```ts // app/reports/actions.ts 'use server'; import { revalidatePath } from 'next/cache'; import { db } from '@/lib/db'; // your own database client import { can } from '@/lib/permissions'; export async function deleteReport(workspaceId: string, reportId: string) { if (!(await can(workspaceId, 'app:reports:delete'))) { return { ok: false as const, error: 'Your role cannot delete reports in this workspace.', }; } await db.report.deleteMany({ where: { id: reportId, workspaceId } }); revalidatePath('/reports'); return { ok: true as const }; } ``` `bb().workspace.can()` is one request to BuildBase's `permissions/me` endpoint, and the answer is the server's own resolution, in the same order the server checks its own permissions: the workspace's override first, then the organization's matrix, then the defaults. Non-members get a 403. The helper turns that into `false` and rethrows a timeout or a 5xx, so the action fails instead of guessing. Both arguments came from the browser, so treat both as claims. `can()` settles whether this user may delete reports in `workspaceId`; the `where` clause settles that the report is actually in `workspaceId`, and without it an editor of their own workspace can delete a report in someone else's just by sending its ID. [Check and query, same workspace](/guides/per-org-data-isolation-nextjs). What you should see: move the button outside `` for a minute, sign in as a viewer and click it. The action returns the error and the report stays. Then put the wrapper back. Why not `bb().permissions.check(workspaceId, userId, permission)`? It takes a user ID, so it can answer for any member, which suits an admin screen showing what a teammate may do. For the signed-in user it is the weaker choice. It fetches the workspace, the organization's settings and the member list, three requests, and works the answer out in your process with the SDK's copy of the rules. `workspace.can()` asks once and gets the server's answer. A route handler is the same check with a status code: ```ts // app/api/reports/route.ts import { db } from '@/lib/db'; import { can } from '@/lib/permissions'; export async function DELETE(request: Request) { const { workspaceId, reportId } = await request.json(); if (!(await can(workspaceId, 'app:reports:delete'))) { return Response.json({ error: 'Forbidden' }, { status: 403 }); } await db.report.deleteMany({ where: { id: reportId, workspaceId } }); return new Response(null, { status: 204 }); } ``` 403, never 401. A 401 tells a client the session is gone, a well-behaved client signs the user out on it, and [the Express version of this check](/guides/multi-tenant-workspaces-express) explains why BuildBase's own API stopped answering 401 for membership failures. Got a page with a dozen gated controls? Ask once. `bb().workspace.permissions(workspaceId)` returns `{ role, isOwner, permissions }`, and a `permissions.includes()` per control costs nothing. These snippets typecheck under strict TypeScript against `@buildbase/sdk` 0.0.82 and Next.js 14.2. I have not run them against a live BuildBase API, so treat them as the shape of the check rather than a transcript. > **Key takeaway:** `WhenPermission` decides what renders. `can()` inside the action decides what > happens. BuildBase enforces its own `workspace:` permissions on its own API; > only your code can enforce yours. ### After a role changes, the browser is the side that is behind BuildBase's server sees a workspace role change on the next request. The member's open tab does not see it until the SDK reloads the workspace list. The server first. The guard behind every workspace permission, and the endpoint `can()` asks, both look up the member's role in the workspace's membership rows on each request. Changing a role rewrites that row, with no cache in between. Matrix edits land the same way. The organization's settings sit in Redis, and saving them clears that copy along with the public settings route the SDK reads, which otherwise caches for 5 minutes. A workspace's own override is stored on the workspace and read per request. The browser is another story. `usePermissions()` and `WhenPermission` resolve from the workspace the SDK already loaded, taking the member's role from that workspace's member list, and nothing tells an open tab its role changed. Demote someone from `editor` to `viewer` and their tab keeps showing Delete. They click, `can()` says no, and the `refreshWorkspaces()` call from step 3 reloads the list so the button goes away instead of failing twice. This is the mirror image of the org-level role, which a session carries. Changing that one through the console revokes the member's sessions at once, and only a write that bypasses the change-role route [waits up to an hour for the session to refresh](/blog/why-permissions-refresh-hourly). A workspace role is not carried in the session at all. Here the guard is current and the UI lags. We do not push role changes to open tabs. The server-side check is what makes that acceptable, since the worst a stale tab can do is show a button that fails politely. Promotions run the other way. The newly promoted member sees nothing new until the list reloads, so if roles change often in your product, call `refreshWorkspaces()` when the window regains focus and pay for one workspace-list request each time. PlugNode, one of our own products, runs its team workspaces with RBAC on this module. ### What breaks, and how you can tell | What you see | Why, and the fix | | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | Every editor sees the button and every action refuses, admins too | The key lives only in `defaultPermissions` on `SaaSOSProvider`, which the server never reads. Define it in the console and grant it in the matrix. | | A role you just added can spend the workspace's credits | A custom role starts as `editor`, and `editor` holds `workspace:usage:record`. Turn it off in the new role's column. | | A workspace admin cannot see something inside `WhenRoles` | `WhenRoles` checks the org-level role. The workspace role is `WhenWorkspaceRoles`, and a permission check beats both. | | A demoted member still sees the button | Their tab holds the workspace it loaded. The action refuses them, and `refreshWorkspaces()` brings the UI up to date. | | A report vanished from a workspace the deleter was not in | The query is missing `workspaceId`. The check and the `where` clause must name the same workspace. | | The action throws instead of returning an error | BuildBase did not answer. The helper rethrows on purpose, so a timeout never reads as a yes or a no. | One boundary worth keeping clear. If what you are gating is something the customer paid for rather than something a person's role allows, that is a plan question and a different system: [entitlements are not feature flags](/blog/entitlements-are-not-feature-flags). ### Install ```bash npm i @buildbase/sdk ``` --- ## How to add social login in Next.js > Google, GitHub, Microsoft and LinkedIn sign-in with no OAuth routes to write. What is left is a decision: what one person becomes when they arrive through two providers. - Source: https://www.buildbase.app/guides/social-login-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Social login on BuildBase needs no new Next.js code: create an OAuth app at the provider, add it as a login method, register the callback URI the method shows, and tick it on your auth client. Accounts then link by email address, but only when the provider vouches that the address is verified. Every social login tutorial for Next.js spends its length on plumbing: the callback route, the token exchange, the provider config, the environment variables that have to match. On BuildBase you write none of it. Your app keeps calling the `signIn()` it already calls, and the hosted sign-in page grows a Google button. What they skip is the part that bites a month later. Someone signed up with a password in March. In April they click Google. Same person? Auth.js, which several of those tutorials build on, says no until you tell it otherwise. It refuses with `OAuthAccountNotLinked`, and the provider option that changes its mind is called `allowDangerousEmailAccountLinking`. BuildBase says yes, on one condition. The setup below is short; most of this guide is about that condition, because it decides which providers are worth offering at all. > **Before you start:** A Next.js app already signing in through BuildBase, [wired up as in the > Next.js setup guide](/guides/buildbase-on-nextjs), with at least one method > working, so you can tell a provider problem from a wiring problem. You also > need admin access to each provider's developer console: Google Cloud, GitHub, > Microsoft Entra or the LinkedIn Developer Portal. ### What you are building A Google button on your hosted sign-in screen, plus GitHub, Microsoft or LinkedIn if you want them, with no new code in your Next.js app. When it works, a user clicks the button, approves at the provider and lands back in your app signed in. If their address already has an account and the provider vouches for it, they land in that account rather than a fresh one. Those four are the ones this guide sets up. BuildBase also has Sign in with Apple and one OpenID Connect provider of your own, each a login method with a few fields of its own, alongside email and password, magic link and passkeys. There is no Facebook or X sign-in, so if your audience expects either, this is not the guide that gets you there. ### Step one: create the OAuth app at the provider Each provider hands you a client ID and a client secret. BuildBase needs both before it will show you the callback URI, so the provider app comes first and its redirect URI waits until step three. - **Google.** In the Google Auth Platform, open **Clients**, click **Create client** and choose **Web application**. Leave the redirect URIs empty for now. - **GitHub.** **Settings → Developer settings → OAuth apps → New OAuth App**. GitHub asks for an **Authorization callback URL** when you register the app, so put your homepage there as a placeholder. Then create a client secret on the app's page. - **Microsoft.** In the Microsoft Entra admin center, **Entra ID → App registrations → New registration**. Note what you pick under **Supported account types**, because step two has to agree with it. Copy the **Application (client) ID**, then go to **Certificates & secrets → Client secrets → New client secret** and copy the secret's **Value**. Entra never shows it again. - **LinkedIn.** Create an app in the LinkedIn Developer Portal and request **Sign in with LinkedIn using OpenID Connect** on its **Products** tab. The client ID and secret are on the **Auth** tab. What you should see: a client ID and a secret for each provider you chose, and no redirect URI registered anywhere except GitHub's placeholder. ### Step two: add a login method in BuildBase In the console, open **User Management → Authentication**, go to the **Methods** tab and click **Add Auth Method**. Pick the provider, paste the client ID and secret, and save. Microsoft also asks for a tenant: `common` for work and personal accounts, `organizations` for work and school accounts only, or your own tenant ID. Make it match the account types you chose in Entra. The console does not ask about scopes. Each method requests the email address and a basic profile on its own, which is all sign-in needs. Saving shows a configuration card with a **Callback / Redirect URI** built from your organization and this method: ```text {serverUrl}/api/v1/auth/social/google/{orgId}/{methodId}/callback ``` Copy it off the card rather than typing it. Every character counts in a redirect check, and the card exists so you never assemble the URI by hand. Edit the method later and the card is there again. What you should see: the new method in the Methods list, and a callback URI containing your org ID and a method ID. ### Step three: register the callback URI at the provider Paste the card's value into the provider app from step one. - **Google.** Add it under **Authorized redirect URIs**. For Google, the BuildBase card also shows an **Authorized JavaScript Origin**; that goes in the field of the same name. Google says changes to these settings can take 5 minutes to a few hours to apply, so a `redirect_uri_mismatch` straight after saving can just be Google catching up. - **GitHub.** Replace the placeholder callback URL. Replace it, do not add the new one under it: BuildBase does not send GitHub a `redirect_uri`, and when that parameter is missing GitHub sends the user to the first callback URL on the app. GitHub now allows up to 10, which makes it easy to leave the wrong one in first place. - **Microsoft.** **Authentication → Add Redirect URI**, choose **Web**, paste. - **LinkedIn.** On the **Auth** tab, add it to the authorized redirect URLs. Notice what is missing from all four: your Next.js URL. The provider sends the user back to BuildBase, and BuildBase sends them on to your app through the redirect URLs registered on your auth client. So localhost, a preview deploy and production all share the one callback URI you just pasted. The Next.js-side causes of `redirect_uri_mismatch` that fill the forums - a wrong base-URL variable, a trailing slash, `http` behind a proxy - do not apply, because your app is not in the URI. ### Step four: turn the method on for your auth client A login method is an organization-wide catalogue entry. The hosted page only offers the methods ticked on the auth client your app signs in through. Open **Authentication → Settings**, edit the client whose ID is in your `SaaSOSProvider`, tick the new method under **Methods**, and save. Skip this and everything looks configured while the button never appears. ### Step five: sign in from your app There is no new code. If your app already has a sign-in button, it already offers Google: ```tsx 'use client'; import { useSaaSAuth } from '@buildbase/sdk/react'; export default function SignInButton() { const { signIn, isLoading, isAuthenticated } = useSaaSAuth(); if (isLoading || isAuthenticated) return null; return ; } ``` `signIn()` takes a return URL and nothing else. There is no `signInWithGoogle()`, and the SDK has no way to send someone straight to one provider from your own page; the user picks on the hosted screen. If you wanted a row of provider logos inside your app, that is what it costs. What you should see: in a private window, click sign in and the hosted page shows a Google button. Approve at Google and you are back on `/dashboard` with `isAuthenticated` true. Two screens can appear in between, and both are expected: **Trust this device?** when your organization asks about devices, and a passkey offer when passkeys are on for the client and the user has none yet. When BuildBase refuses a social sign-in - an unverified address, closed sign-up, a blocked user - the message appears on that hosted page, not in your Next.js app. There is no error for your code to catch. ### The decision: one person, two providers BuildBase matches a social sign-in to an account by the provider's own user ID first, then by email address, and links by email only when the provider vouches that the address is verified. In code, the provider's answer has to be exactly `email_verified === true`. | The address the provider returns | Provider says verified | Provider does not | | -------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | Already has an account | Signs into that account | Refused: "This email is already registered. Sign in the way you did before, then connect this provider from your account's security settings." | | Has no account yet | New account, email verified | New account, and the hosted page asks for a 6-digit code first | Why refuse rather than link? Because the alternative is a takeover. If an unverified address could link, anyone who got a provider to put your user's address on an account they control would walk into your user's account with it. This is the same line Auth.js draws, set at a different default. Its docs say automatic linking "is not secure between arbitrary providers and is disabled by default", and suggest turning it on only when you trust the provider has verified the address. BuildBase makes that call on every sign-in, from the provider's own claim, so there is no flag with "dangerous" in its name for you to flip. Three consequences worth knowing before your users find them: - **Linking adds a door, it does not remove one.** A password user who signs in with Google once can still sign in with the password. - **Two accounts stay two accounts.** A signed-in user can connect a provider that carries a different address from the Security screen of your app's settings, but nothing merges two accounts that already exist. - **The match is on the provider's account ID once it is linked.** Change the address at Google, or in your app, and the next Google sign-in still finds the same account. > **Key takeaway:** A first social sign-in links by verified email and nothing else. So the > question to ask of a provider is not whether your users have an account there, > but which address that account will hand you. #### Where "verified" comes from | Provider | Counts as verified when | | --------- | --------------------------------------------------------------------------------------------------- | | Google | the ID token's `email_verified` is true | | GitHub | the address is the public profile email or, failing that, the primary address GitHub marks verified | | Microsoft | it is a personal account, or a work or school account whose ID token carries `xms_edov` | | LinkedIn | the ID token's `email_verified` is true | A GitHub user with neither a public email nor a verified primary one is turned away, since there is no verified address to find or create an account with. LinkedIn is the soft one: its own docs list `email` and `email_verified` as optional, and say its sign-in "does not verify user identities and should not be marketed as such". #### The Microsoft work-account trap Microsoft's own claims reference says the `email` claim "isn't guaranteed to be correct, and is mutable over time". So for work and school accounts BuildBase does not take the address on its word. It looks for `xms_edov`, which Microsoft describes as whether "the user's email domain owner has been verified": true when the address is on a domain the user's tenant has verified. Entra does not put that claim in the ID token unless you ask. Leave it out and testing with a fresh account looks fine, apart from a verification-code screen you will probably wave through. Then a customer who signed up with a password tries **Microsoft** with the same work address, and gets refused. The fix is one screen in your app registration: **Token configuration → Add optional claim**, token type **ID**, tick `email` and `xms_edov`, and **Add**. Personal Microsoft accounts count as verified without it. ### Which providers to offer Offer the providers that hand you the address your users already use with you. Every extra button is one more way for one person to become two accounts. **B2B tools: Google and Microsoft.** A work address on Google Workspace comes back from Google, one on Microsoft 365 comes back from Microsoft, and either one matches [the work address an invitation was sent to](/guides/team-invitations-nextjs). Add the `xms_edov` claim before launch and these two link cleanly. **Developer tools: GitHub, with your eyes open.** It is the button developers expect, but it returns the account's public profile email, or failing that its primary one. If that is a personal address and the invitation went to a work one, the sign-in belongs to the personal address: it creates a second account, or is refused if sign-up is closed, and neither sees the team's workspaces. That failure has [its own guide](/guides/invited-member-cannot-see-workspace), because from the outside it looks like the invitation never worked. **LinkedIn: only if your users already live there.** Recruiting and sales tools, mostly. By its own documentation it is the weakest of the four at proving an address, and whenever it leaves out `email_verified`, a user who already has an account is refused rather than linked. If what you want is sign-in without a password and without the two-accounts question, [magic link](/guides/magic-link-login-nextjs) proves the address directly, because the link is sent to it. ### The failure modes **The button never shows.** Either the method is not ticked on the auth client from step four, or two methods for the same provider are ticked. The hosted page shows one button per provider, built from the first one it finds, so the method you just fixed may not be the one users are clicking. **`redirect_uri_mismatch`, or the provider's version of it.** Whatever is registered at the provider is not what the card shows. Nothing in your Next.js app moves the card's value, but recreating the method does: delete it and add it again, and the new method gets a new ID and so a new callback URI. Deleting also detaches the method from every client, so you would redo step four as well. When only the secret changed, edit the method instead. Leaving the secret blank on edit keeps the stored one. **GitHub drops users on your homepage with a code in the URL.** The placeholder callback URL from step one is still first in the list. **Microsoft sign-in stops working one morning.** The client secret expired. Entra caps client secrets at 24 months and recommends under 12, so put the expiry date in the calendar of whoever owns the console, and paste the new value into the method before it lapses. **A bare "Unauthorized" instead of your sign-in page.** BuildBase holds the state for a social sign-in for 10 minutes and accepts it once. A user who leaves the consent screen open longer than that, or replays the callback with the back button, gets a 401 from the API and has to start again. **New users refused while existing ones sign in fine.** Public sign-up is closed. Social sign-in obeys that setting: existing accounts get in, new ones are refused unless they started from an invitation link, as [the authentication docs](https://docs.buildbase.app/authentication/overview#closing-public-sign-up) describe. If sign-up is open and new users still see "Signup is not enabled for this organization", check your plan's end-user limit. A social sign-up counts against it exactly as a password registration does. ### Related Sessions behave the same whichever button someone clicked: 30 days by default. If you turn on [passkeys](/guides/passkeys-nextjs) as well, social login becomes the on-ramp: after a social sign-in, the hosted pages offer a passkey to anyone whose browser supports one and who has none yet. And if the redirect comes back and bounces you straight to sign-in again, that is [the middleware redirect loop](/guides/nextjs-middleware-redirect-loop-after-login), not a provider problem. ### Install ```bash npm i @buildbase/sdk ``` --- ## Stale data on screen after a workspace switch > Stale data after a workspace switch is a cache that never learned the workspace changed. One switch with the Network tab open tells you which cache. The fix is a key, not a purge. - Source: https://www.buildbase.app/guides/stale-data-after-workspace-switch - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Stale data after a workspace switch is your cache, not the SDK. switchToWorkspace sets currentWorkspace, saves the id to localStorage and fires workspace:changed. It never touches React Query, SWR or the Next.js Router Cache. Key every query by workspace id, put the workspace in the URL, and nothing needs clearing. The switcher says the new workspace. The table under it still lists the old workspace's rows. Click over to another browser tab and back, and the rows fix themselves. That last detail is most of the diagnosis. Nothing on the BuildBase side is stale: `currentWorkspace` changed the moment the switch finished. What is stale is a cache of yours that never found out, because the one thing it watches is its key, and its key did not move. The usual forum answer is to clear everything on switch. It works, in the sense that rebooting works. Done in the obvious place, it also races the switch itself. And it leaves the actual defect, a key that does not name the workspace, exactly where it was. > **Before you start:** An app on the React SDK whose organization is in Platform mode. New > organizations start in Personal mode (`DEFAULT_WORKSPACE_MODE`), one workspace > per user and no switcher, so there is nothing to switch and nothing to go > stale. Browser devtools open on the Network tab. If the workspace is missing > from the switcher altogether, that is membership, not caching: see [an invited > member who cannot see the > workspace](/guides/invited-member-cannot-see-workspace). ### What a switch actually changes Four things, in this order. I read them out of the SDK's `WorkspaceProvider` rather than the docs, because the order is what matters later: 1. It marks a switch in progress: `switching` reads true. 2. It awaits your `onWorkspaceChange({ workspace, user, role })` callback, if you passed one, and if a newer switch started while it was waiting, this one gives up there and goes no further, which is how a fast double-click ends on the second workspace rather than the first. 3. It writes the workspace's `_id` to localStorage under `saas-workspace-current`, and sets `currentWorkspace`. 4. Then `workspace:changed`, carrying `{ workspace, previousWorkspace }`, goes out through your `handleEvent` callback. That is the whole list. No page reload, no `router.refresh()`, and no idea your QueryClient exists. Nor should it. But it means everything your app fetched for the old workspace is still where you put it, under whatever name you gave it. > **Key takeaway:** A switch changes one value your code can see: `currentWorkspace`. A cache > whose key does not include `currentWorkspace._id` has no reason to fetch > anything. The SDK's own subscription and credit providers follow the switch, because they read `currentWorkspace._id` and refetch when it changes. One caveat before you go hunting in your own code: if the stale thing is the SDK's own subscription, quota, credit or invoice data, check your SDK version first. That was our bug, and the version that fixed it is in the section on late responses below. ### Switch once with the Network tab open Filter the Network tab to your own API, clear it, and switch workspace once. What happens after the click puts you in one of four places: | After the switch | What is holding the old data | | ----------------------------------------------- | ----------------------------------------------------------- | | No request for that screen's data | a key without the workspace id, or the Next.js Router Cache | | A request with the new id, old rows on screen | placeholder data from the previous key | | A request with the new id, then old rows return | a late response from the workspace you left | | A request with the old id | something that ran before the switch finished | Read the id in the request path or body, not the response. The response belongs to whoever asked. ### No request at all: the key never named the workspace This is the common one. A query keyed `['projects']` is the same query in every workspace, so when `currentWorkspace` changes, TanStack Query sees nothing new to fetch and keeps serving what it has. ```tsx // Before: one cache entry shared by every workspace const { currentWorkspace } = useSaaSWorkspaces(); const projects = useQuery({ queryKey: ['projects'], queryFn: () => getProjects(currentWorkspace!._id), }); ``` It passes review because the `queryFn` does close over the new id after the re-render. That does not matter. The library decides whether to fetch from the key, and the key is identical before and after. So why does clicking away and back fix it? `refetchOnWindowFocus` is on by default and refetches stale data on focus, and with the default `staleTime` of zero, everything is stale. By then the `queryFn` holds the new workspace id, so the refetch gets it right. SWR does the same through `revalidateOnFocus`, also on by default. That is why the bug reads as intermittent: anyone who switches and then tabs away never sees it. Put the workspace in the key: ```tsx import { useSaaSWorkspaces } from '@buildbase/sdk/react'; import { useQuery } from '@tanstack/react-query'; import { getProjects } from '@/lib/api'; // your own fetcher export const keys = { workspace: (workspaceId: string) => ['workspace', workspaceId] as const, projects: (workspaceId: string) => ['workspace', workspaceId, 'projects'] as const, }; export function useProjects() { const { currentWorkspace } = useSaaSWorkspaces(); const workspaceId = currentWorkspace?._id ?? ''; return useQuery({ queryKey: keys.projects(workspaceId), queryFn: () => getProjects(workspaceId), enabled: workspaceId !== '', }); } ``` Now each workspace has its own entry. Switching back to one you just left shows its cached rows at once, which are its rows, and refetches them if they are stale. Nothing has to be cleared, because nothing is wrong. In SWR the key is the first argument, and the same fix looks like this, with the `null` waiting until there is a workspace: ```ts useSWR(workspaceId ? `/api/workspaces/${workspaceId}/projects` : null, fetcher); ``` A store you fill by hand is no different. A Zustand slice called `projects` is a cache key with no workspace in it. ### No request, and the page is server-rendered The current workspace lives in the browser, and the server cannot see it. The React SDK keeps the id in localStorage. BuildBase's API has no "current workspace" for a session at all: every workspace route takes the id in its path (`/api/v1/public/workspaces/:workspaceId/...`), and the server SDK takes `workspaceId` as the first argument of every call scoped to one workspace. The session belongs to the user. So a server component that renders workspace data got its workspace id from somewhere you chose: the URL, or a cookie you set. If it was a cookie, the Next.js Router Cache is the next suspect. It keeps the rendered server component payload for routes you already visited, in the browser. On Next.js 14, a dynamically rendered segment is reused for 30 seconds and a static one for 5 minutes. Next.js 15 changed the dynamic default to zero, but shared layouts are still not refetched on navigation, and back and forward still come from the cache. A sidebar rendered in a layout is exactly the part that stays behind. It is a cousin of the cached profile page in [BuildBase on Next.js](/guides/buildbase-on-nextjs): a render that depended on a cookie, served from a cache that did not know it. Next.js lists two ways to clear it: `cookies.set` or a revalidate inside a Server Action, and `router.refresh()`. A cookie written with `document.cookie` is on neither list. So if your server reads a workspace cookie, write it in `onWorkspaceChange`, which is what a before-hook is for, and refresh after the switch lands: ```tsx // app/providers.tsx 'use client'; import { useMemo } from 'react'; import { useRouter } from 'next/navigation'; import { ApiVersion, SaaSOSProvider, SDKEvent, type EventData, type EventType, type WorkspaceChangedEventData, } from '@buildbase/sdk/react'; // The three callbacks from the Next.js setup guide, moved to module level. import { getSession, handleAuthentication, onSignOut } from './auth-callbacks'; export function Providers({ children }: { children: React.ReactNode }) { const router = useRouter(); const auth = useMemo( () => ({ clientId: process.env.NEXT_PUBLIC_BUILDBASE_CLIENT_ID!, redirectUrl: process.env.NEXT_PUBLIC_BUILDBASE_REDIRECT_URL!, callbacks: { getSession, handleAuthentication, onSignOut, // onWorkspaceChange: write your workspace cookie here, before the switch. handleEvent: (eventType: EventType, data: EventData) => { if (eventType !== SDKEvent.WorkspaceChanged) return; const { workspace, previousWorkspace } = data as WorkspaceChangedEventData; // Page load restores the saved workspace with no previous one. if (!previousWorkspace || previousWorkspace._id === workspace._id) { return; } router.refresh(); }, }, }), [router] ); return ( {children} ); } ``` Keep `auth` memoized. The provider rebuilds its callback config whenever one of those functions changes identity, and an inline object hands it new ones on every render. I wrote this against the SDK's type definitions and its provider source, not in a running app, so treat it as the shape of the fix rather than a tested file. The better fix is not to need it. [Put the workspace in the URL](/guides/per-org-data-isolation-nextjs), as `/w/[workspaceId]/projects`, and each workspace is a different route: the Router Cache cannot serve one workspace's payload for another, server components read the id from `params`, and a pasted link opens the right workspace. The URL becomes the source of truth and the SDK follows it, through one small component that calls `switchToWorkspace` when the workspace in the URL is not `currentWorkspace`. Our own console runs the same pattern keyed on the org in its session rather than a URL: a `WorkspaceAutoSelector` that switches the SDK to the workspace that org needs. The full argument, membership check included, is in [multi-tenant Remix](/guides/multi-tenant-workspaces-remix), and only the routing differs in Next.js. #### Two tabs, one remembered workspace `saas-workspace-current` is one localStorage key per origin. Every tab shares it, and the SDK writes it without watching it. Switch in tab B, and tab A's switcher goes on showing A, correctly, until tab A reloads and restores B. A workspace cookie makes it arrive sooner. Tab A's next server render carries B's cookie while its switcher still says A. When the switcher and the page under it disagree about which workspace you are in, look here first. A URL holds one workspace per tab, which is the other reason it wins. ### A request for the new workspace, but the old rows stay The key changed, the request went out, and the old workspace's rows are still on screen until it lands. That is placeholder data doing its job on the wrong key. `placeholderData: keepPreviousData` in TanStack Query v5, or `keepPreviousData: true` in v4, keeps the data from the last successful fetch on screen while a query with a new key loads. On a page number that is the feature. On a workspace id it renders one workspace's rows under another workspace's name. SWR's `keepPreviousData: true` does the same: it returns the previous key's data until the new data has loaded. Keep the smoothing inside a workspace and drop it across one: ```ts useQuery({ queryKey: keys.projects(workspaceId), queryFn: () => getProjects(workspaceId), placeholderData: (previousData, previousQuery) => previousQuery?.queryKey[1] === workspaceId ? previousData : undefined, }); ``` `isPlaceholderData` tells you which you are looking at, if you would rather dim the table than blank it. ### A request for the new workspace, then the old rows come back This one only shows up on fast switches or a slow network, which is why it survives testing. Throttle the Network tab to a slow preset and switch twice in quick succession to reproduce it. Hand-rolled fetching in a `useEffect` has a race the libraries handle for you. Switch from A to B, A's request is the slower one, it lands second, and the last `setState` wins. React's own docs name it plainly: network responses may arrive in a different order than you sent them. We shipped this one. Until SDK 0.0.54, released on 2026-07-10, fifteen of the SDK's own read hooks, `useSubscription`, `useAllQuotaUsage`, `useCreditBalance`, `useInvoices` and the rest, could render the previous workspace's subscription, quotas, credits or invoices after a switch. If those are what you see, upgrade before reading further. The fix inside the SDK is the one you want in your own code. A newer request aborts the one it supersedes, and a response to an aborted request is dropped. `useSubscription` also remembers which workspace its data was fetched for, and returns `null` with `loading: true` while that is not the workspace it was asked about. In your own effect: ```tsx import { useEffect, useState } from 'react'; import { useSaaSWorkspaces } from '@buildbase/sdk/react'; import { getProjects, type Project } from '@/lib/api'; // your own fetcher export function useProjectsByHand() { const { currentWorkspace } = useSaaSWorkspaces(); const workspaceId = currentWorkspace?._id; const [data, setData] = useState<{ workspaceId: string; rows: Project[]; } | null>(null); const [error, setError] = useState(null); useEffect(() => { if (!workspaceId) return; const controller = new AbortController(); setError(null); getProjects(workspaceId, { signal: controller.signal }) .then((rows) => setData({ workspaceId, rows })) .catch((err) => { // An aborted request belonged to a workspace we left. Anything else is real. if (!controller.signal.aborted) setError(err); }); return () => controller.abort(); }, [workspaceId]); // Data tagged with another workspace is treated as no data at all. const rows = workspaceId && data?.workspaceId === workspaceId ? data.rows : null; return { rows, error }; } ``` Tagging the data with its workspace id is the half people skip. The abort stops a late response from landing; the tag stops the previous workspace's rows from rendering in the gap before the new ones arrive. ### A request for the old workspace, after the switch Something ran before the switch finished. Usually that is a purge inside `onWorkspaceChange`, because that callback runs before the switch, not after it. The SDK awaits it and only then sets `currentWorkspace`, so anything you trigger in there that reads the current workspace reads the one being left. The common version is `queryClient.invalidateQueries()` in `onWorkspaceChange`. Invalidation refetches active queries by default, and the active queries are the old workspace's, mounted on a screen that has not re-rendered yet. With an unkeyed `['projects']`, that is worse than a wasted request. It refills the shared entry with the old workspace's rows, freshly fetched, right before the switch lands. Then the key does not change, so nothing asks again until the window regains focus. Three more things about that callback are easy to miss. [The docs](https://docs.buildbase.app/workspaces/workspace-switcher) say it also fires on page load, when the saved workspace is restored from storage. Before SDK 0.0.55, released on 2026-07-14, it fired once per mounted `useSaaSWorkspaces()` rather than once per switch, so an app with the hook in several components ran its purge several times. And `setCurrentWorkspace` skips it entirely, since its type documentation calls it direct, with no callback, while still firing `workspace:changed`. So keep `onWorkspaceChange` for what its type says it is for: work that must finish before the switch, such as minting a token or saving state, and that may veto it by rejecting. React to a switch on `workspace:changed`, which fires after `currentWorkspace` is set, carries `previousWorkspace`, and comes through `handleEvent`, as in the provider above. Skip the event when `previousWorkspace` is missing; that is a page load, not a switch. The SDK's own analytics make the same cut, and only report `workspace_switched` when both ids are present and differ. The other source of old-workspace requests is the SDK restoring the remembered workspace before your app has picked the one it wants. Our own console bills through BuildBase and hit exactly this. After an org switch the remembered `saas-workspace-current` still named the previous org's workspace, so the SDK selected it, every workspace-keyed provider fetched subscription, credits and usage for it, and then the console's own selection landed and all of it was fetched again. The fix was to write the right id into that key before the SDK reads it. The comment beside that code records the difference in a HAR as seven subscription reads becoming one per workspace. Note why that comment counts requests rather than wrong rows. Every one of those providers was keyed by workspace id, so when the right selection landed they fetched under a new key instead of serving the old one. That is the argument of this page in one incident. With the workspace in the key, a switch at the wrong moment costs you a round trip. Without it, it costs you the right rows. If you are still designing the workspace model rather than debugging it, [multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon) makes the case for the workspace as the unit that owns data. Keying every cache by it is the same decision, made on the client. ### Install ```bash npm i @buildbase/sdk ``` --- ## How to add team invitations in Next.js, and decide when the seat starts billing > Team invitations in Next.js: a pending invite holds a seat from the moment it is sent. Why that is the right default, and what it does to the invoice at renewal. - Source: https://www.buildbase.app/guides/team-invitations-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short In BuildBase, a team invitation takes a seat when the email is sent, not when it is accepted, and holds it until it is accepted, declined, revoked or lapses at 14 days. Past a plan's included seats, an invitation pending at renewal is billed for the new period, and its credit for unused time lands on a later invoice. Sending a team invitation is one function call. The decision behind it is not in the call: does the invited person start costing the workspace a seat when the email goes out, or when they click accept? BuildBase takes the seat at send. A pending invitation holds it until it is accepted, declined, revoked or expires, and once a [seat-priced workspace](/blog/metered-vs-seat-based-billing) is past its included seats, that seat is billed. Most of this guide falls out of that one rule, including the part almost nobody thinks about until a customer asks why their annual invoice has a seat for someone who never joined. > **Before you start:** A Next.js app with the BuildBase session wired through, which is [BuildBase on > Next.js](/guides/buildbase-on-nextjs), and workspaces from [multi-tenant > workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon). > For anything about money, a plan with seat pricing. Invitations need > `@buildbase/sdk` 0.0.71 or later, a server from release 22, and an email > sender configured for the organization: without one, the invite route refuses > with 503 before it writes anything. ### When does an invitation take a seat? When the email is sent. The server's seat count is active members plus live pending invitations, where live means unanswered and inside its 14 days. Every check and every bill reads that one count. The plan's member cap reads it, and so do the trial cap and the workspace settings' `maxWorkspaceUsers` ceiling. So does the Stripe seat quantity, on every path that sets it: checkout, a plan change, a member added or removed, and every invitation sent, declined, revoked or expired. > **Key takeaway:** A pending invitation is a seat. It counts against the cap before the invitee > has opened the email, and once a seat-priced plan is past its included seats, > it is on the bill as well. Here is how a pending seat ends: | What happens to the invitation | What happens to the seat | | ------------------------------ | ------------------------------------------------- | | Accepted | The new member takes it over; the count stays put | | Declined | Released | | Revoked | Released at once | | 14 days pass with no answer | Released by a sweep that runs every ten minutes | Two details from the server are worth knowing before you build on it. If the invitation email cannot be queued, the server deletes the row and answers 502 rather than leave a pending seat behind, because a seat for a mail nobody received is a wrong bill. And resending is not free. A resend mints a new link and sets the expiry to 14 days from now, so an invitation resent every fortnight holds its seat for as long as someone keeps clicking Resend. We made this call in September, while building workspace invitations, and the console's own organization invitations make a useful contrast. Those rows cost nothing, so nothing sweeps them: an expired one keeps the status `invited` in the database until someone tries to use it. An invitation inside your app bills, so it got a sweeper, an inline expiry when someone accepts too late, and a row that refuses to exist without its email. ### Why send-time is the one you want Because the cap has to count pending invitations, and once it does, billing on accept would leave the cap and the invoice counting two different things. Start with the cap, and suppose it ignored pending invitations. An admin on a workspace capped at three seats, with two members, invites five people. All five sends go through. The first to accept takes the last seat, and the other four follow a link from a team they were told to join and land on "This workspace has reached its member limit. Ask an admin to make room." The person who hits that wall has the least context and no power to fix it. Counting pending invitations moves the refusal to where it belongs. With BuildBase the admin's second invitation answers 402, with the count and the limit on it, while the admin is still at the keyboard. So the cap counts them. Should the bill? If it does not, an admin sees a full workspace on the team page and a smaller seat count on the invoice, and somebody gets to explain why the workspace was full of seats it was not paying for. One count, read by the cap and by Stripe, is the only version where the seat count the admin sees and the seat count on the invoice move together. The other answer is defensible, though. [Makerkit's per-seat billing docs](https://makerkit.dev/docs/nextjs-prisma/billing/per-seat-billing) recommend updating the seat quantity only when an invitation is accepted, "to avoid billing for users who never join", while its [seat enforcement](https://makerkit.dev/docs/nextjs-prisma/billing/seat-enforcement) still counts pending invitations against the limit. If your admins routinely invite people who never turn up, that split costs them less. BuildBase does not offer it. There is one count and no setting to leave pending invitations out of the bill, so if accept-time billing is a hard requirement, that is a real gap. Two things soften it. `addUser` makes someone who already has an account a member at once: no pending row, no pending seat, nothing to expire. It answers 404 for an address with no account, which is the job `inviteMember` exists for. And billable seats are members plus pending invitations minus the plan's included seats, never below zero, so a pending invitation inside the included allowance costs nothing. ### Step 1: ship the members screen, if it is enough The SDK's members screen already does the whole job: invite by email with a role, the pending list under the form with Resend and Revoke, and a seat block that counts pending invitations and says so. ```tsx 'use client'; import { useSaaSAuth } from '@buildbase/sdk/react'; export function TeamButton() { const { openWorkspaceSettings } = useSaaSAuth(); return ( ); } ``` Click it and the members screen opens on the current workspace, with the invite form and any pending invitations listed under it. If that screen is all your product needs, skip to the renewal section. The [invitations reference](https://docs.buildbase.app/workspaces/invitations) covers the invitee's side, including sign-up for someone with no account. ### Step 2: make your own seat count agree with the server The trap in a custom team page is one missing argument. `useSeatStatus(workspace)` counts the members on `workspace.users` and nothing else. Pending invitations are an option you pass, and the SDK's own members screen passes them. Leave it out and a workspace with three members and two pending invitations shows room for two more on a five-seat cap, while the server counts five and refuses the next invite. ```tsx // app/team/invite-members.tsx 'use client'; import { useState } from 'react'; import type { IWorkspace } from '@buildbase/sdk/react'; import { isInvitationError, useSaaSWorkspaces, useSeatStatus, useWorkspaceInvitations, } from '@buildbase/sdk/react'; export function InviteMembers({ workspace }: { workspace: IWorkspace }) { const { inviteMember } = useSaaSWorkspaces(); // One instance for the count and the form. Each call to the hook keeps its // own list, so a second instance would not see the row you just created. const { pendingCount, refresh } = useWorkspaceInvitations(workspace._id); const { memberCount, canInvite } = useSeatStatus(workspace, { pendingInvitations: pendingCount, }); const [email, setEmail] = useState(''); const [sending, setSending] = useState(false); const [notice, setNotice] = useState(null); async function send() { setSending(true); setNotice(null); try { await inviteMember(workspace._id, email, 'editor'); await refresh(); // the new row holds a seat now, not on accept setNotice(`Invitation sent to ${email}`); setEmail(''); } catch (err) { if (isInvitationError(err) && err.code === 'SEAT_LIMIT_REACHED') { setNotice( `No seats left: ${err.currentUserCount} of ${err.limit} in use, counting pending invitations.` ); } else { setNotice( err instanceof Error ? err.message : 'Could not send the invitation.' ); } } finally { setSending(false); } } return (

{memberCount} seats in use, {pendingCount} of them pending

setEmail(e.target.value)} placeholder="demo@example.com" /> {notice &&

{notice}

}
); } ``` What you should see: the count goes up by one the moment the invitation is sent, before anyone has opened the email. Why handle the 402 when `canInvite` already disables the button? Because the hook is display state, and two admins can be looking at the same last seat. The refusal carries `currentUserCount` and `limit`, both counting pending invitations, so the message can say something specific. When the button is disabled for a reason other than a full workspace, [charging per seat](/guides/charge-per-seat-nextjs) covers what to offer for each one. From a server action or a route handler, the same invitation is `bb().invitations.create(workspaceId, email, role)` on the server client from [the Next.js setup](/guides/buildbase-on-nextjs). It runs as the signed-in user, so [the same permission check](/guides/roles-and-permissions-per-workspace-nextjs) and the same seat count apply. ### What happens to a pending invitation at renewal? It is on the renewal invoice, if the workspace is past its included seats. Nothing in BuildBase recomputes seats at the period boundary: Stripe renews the seat line at whatever quantity it holds, and that quantity includes every invitation still live at that moment. If the invitee then accepts, the charge was right all along. If the invitation is declined, revoked or expires instead, the quantity drops with a proration, and [Stripe's own docs](https://docs.stripe.com/billing/subscriptions/prorations) are blunt about what that means: "Negative prorations aren't automatically refunded". The credit for the unused time waits for a later invoice. How much that matters comes down to the billing interval: - **Monthly.** The renewal charges a month of the seat, and the unused part comes back as a credit on the next monthly invoice. Small, and I would leave it alone. - **Yearly.** The renewal charges a year of the seat. If the invitation lapses two weeks later, the credit for the rest of the year rides on the next invoice the subscription produces, which can be the next renewal. That is the invoice that turns into a support ticket. Quarterly is the same shape, smaller. Which invitations can this catch? Only ones sent, or resent, in the 14 days before the renewal date, because nothing older is still live. That makes the check cheap: an invitation whose `validTill` falls after the period end will still be pending when the period rolls over, unless somebody answers it first. ### Step 3: show admins what renewal will bill Do not auto-revoke. An invitation sent yesterday to a new hire is the one most likely to be accepted, and revoking it to dodge a prorated seat swaps a credit for a confused new hire. Show the admin instead, on plans billed less often than monthly, and put Revoke next to each row. ```tsx // app/team/renewal-notice.tsx 'use client'; import type { IWorkspace } from '@buildbase/sdk/react'; import { useSeatStatus, useSubscription, useWorkspaceInvitations, } from '@buildbase/sdk/react'; export function RenewalInviteNotice({ workspace }: { workspace: IWorkspace }) { const { subscription } = useSubscription(workspace._id); const { invitations, pendingCount, revoke, busy, error } = useWorkspaceInvitations(workspace._id); const { billableSeats } = useSeatStatus(workspace, { pendingInvitations: pendingCount, }); const sub = subscription?.subscription; if (!sub?.stripeCurrentPeriodEnd || sub.billingInterval === 'monthly') { return null; } // Inside the plan's included seats, a pending invitation costs nothing. if (billableSeats === 0) return null; const renewsAt = new Date(sub.stripeCurrentPeriodEnd); const billedAtRenewal = invitations.filter( (i) => i.status === 'invited' && i.validTill !== null && new Date(i.validTill) > renewsAt ); if (billedAtRenewal.length === 0) return null; return ( ); } ``` What you should see: nothing, for most of the year. The notice can only appear in the last 14 days before a quarterly or yearly renewal, since no live invitation's clock runs further out than that, and then it lists exactly the invitations that will be on the invoice if nobody answers them. I have not run these components against a live server while writing this. They use hooks and types the SDK exports from 0.0.71 on, and the seat wiring in step 2 is the same one the SDK's own members screen uses. ### What breaks, and how to tell **The badge says there is room and the invite answers 402.** `useSeatStatus` was called without `pendingInvitations`. The server counted the pending rows; your page did not. **The invite answers 502 and nothing shows as pending.** The email could not be queued, so the server deleted the row rather than bill a seat for it. With no sender configured at all, the answer is 503 `NO_SENDER_CONFIGURED`, before anything is written. Set a sender up under Emails in the console first. **Bulk invites stop with a 429.** A workspace can send sixty invitations an hour, and an organization two hundred invitation emails a day by default. Resending one invitation has a five-minute cooldown, and that refusal carries `retryAfterSeconds` so a button can count down instead of guessing. **A trial workspace on a seat-priced plan cannot invite past its included seats.** During a trial the cap is the plan's included seats, pending invitations counted, and the refusal says so: "Trial includes 3 seats. Subscribe to add more members." for a plan that includes three. **An invitation that never stops billing.** Someone keeps clicking Resend. Every resend restarts the 14 days, and the seat with them. **A plan change moves the seat line too.** It recomputes billable seats against the new plan's included allowance, pending invitations counted, which is part of [what a plan change does to the invoice](/guides/proration-on-plan-change-nextjs). **The person you invited says it is not there.** Check the address first. The invitation belongs to the address it was sent to, and accepting from a different account is refused with the invited address scrambled in the error. The [errors section of the invitations reference](https://docs.buildbase.app/workspaces/invitations#errors) lists every refusal and what it means. ### Install ```bash npm i @buildbase/sdk ``` --- ## Transactional email landing in spam > Transactional email in spam is a verdict the receiving server already wrote into the header. How to read it, and five causes to check in the order that settles fastest. - Source: https://www.buildbase.app/guides/transactional-email-landing-in-spam - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Read the Authentication-Results header on the copy in spam before touching DNS. SPF or DKIM failing points at your records. DMARC failing while both pass means the From domain is not the one that was checked. All three passing means links or reputation. On BuildBase, first check which sender is the system default. The receiving server has already told you why your sign-in email went to spam. It wrote the reason into the message, in a header almost nobody opens. And then the debugging starts somewhere else: a DNS record changed on a hunch, or a ticket to the email provider. A marketing email in spam costs an open. A [magic link](/guides/magic-link-login-nextjs) in spam costs the sign-in, and the user decides your product is broken. So read the header first. Then work down the five causes below and stop at the first one that is wrong. They are ordered by how fast each one settles, not by how often it is the answer, and the first two live in how BuildBase picks a sender and reports a domain. No generic deliverability checklist can find those for you. > **Before you start:** One copy of the message that actually landed in spam, ideally in a Gmail > mailbox you control, plus console access to **Messaging → Sender Accounts** > and the sending domain. If nobody kept a copy, make one: request a magic link > or a password reset to that mailbox. ### First, is it in spam at all? "I never got the email" is two different bugs, and only one of them is about spam. Find the recipient in email history before you open a DNS panel. A `skipped` row means the message never left. No usable sender, a missing template, a blocked or unsubscribed address, an address marked invalid after a bounce: each one is written on the row as the reason. A `sent` row means your provider accepted the message, and that is the last thing we can see. Where it went next, only the receiving server knows. The [invitation troubleshooting guide](/guides/invited-member-cannot-see-workspace) walks through the skip reasons. This post starts where `sent` ends. ### Read the verdict before you change anything The receiving server records its checks in an `Authentication-Results` header, the format [RFC 8601](https://www.rfc-editor.org/rfc/rfc8601) defines. In Gmail, open the message, click **More** next to Reply, and choose **Show original** ([Google's steps](https://support.google.com/mail/answer/29436)). Trimmed, with placeholder domains, the line you want looks like this: ```text Authentication-Results: mx.google.com; dkim=pass header.i=@mail.example.com; spf=pass smtp.mailfrom=mail.example.com; dmarc=fail header.from=example.org ``` Two passes and a fail. Both checks passed, for `mail.example.com`. The From header said `example.org`. DMARC asks whether at least one passing check belongs to a domain aligned with the From domain ([RFC 7489, section 4.2](https://www.rfc-editor.org/rfc/rfc7489#section-4.2)), and here neither does. Gmail surfaces the same failure more bluntly: a question mark next to the sender's name means the message [is not authenticated](https://support.google.com/mail/answer/180707). | The header says | It means | Go to | | ----------------------------------------------------- | ----------------------------------------------- | ------- | | the passing domain is `gmail.com` or your SMTP host's | a different sender sent it | cause 1 | | `spf=fail`, `dkim=fail`, or no DKIM result at all | the records are missing, wrong, or not live yet | cause 2 | | `spf=pass` and `dkim=pass`, but `dmarc=fail` | something passed, but not for your From domain | cause 3 | | all three pass, for your own domain | the message, its links, or the sending history | 4 and 5 | ### 1. Find out which sender actually sent it This is the cause a generic checklist cannot find, because it lives in how we pick a sender. System mail does not name one. The magic link, the verification code, the password reset code and the workspace invitation all go through whichever single sender in the org is flagged `systemDefault: true`. Which one is that? Usually the first sender anyone created. Every way of creating a sender, Mailgun, SMTP or Google, ends by calling `updateDefaultSender`, and that function only fills an empty default. It never moves one. Here is how that plays out. Someone connects their own Google account during setup to check that email works. It does. Weeks later someone else adds `mail.example.com`, verifies it, creates a Mailgun sender on it and moves on. Every sign-in link since then has gone out through Gmail, from the address of the person who clicked connect first. A Google sender's From is the account's own address. Your verified domain never touched those messages, and every DNS record you fix will change nothing. Two places to check. The email history row stores the `from` it used and the sender it went through. `GET /api/emails/senders` returns each sender with its `systemDefault` flag, but only the senders you own or that were shared with you. The default can easily be someone else's, and missing from your list. An org owner or admin can add `filter[all]=true` to list every sender in the org. The fix is to move the default to the sender on your verified domain. That sender's owner can do it, and so can an org owner or admin: ```bash curl -X PATCH https://api.console.buildbase.app/api/emails/senders/$SENDER_ID/default \ -H "Authorization: $BUILDBASE_TOKEN" ``` Do it before you clean up. The delete route refuses the system default, so the old sender cannot be removed until another one holds the flag. ### 2. Check the domain is verified, not that verify returned 200 Adding a domain hands back the DNS records to publish, which come straight from Mailgun. The table below is the sending set from a real stored response, with the domain swapped for a placeholder: | Type | Name | Value | What it is | | ----- | ---------------------------------------- | --------------------------------- | ---------------------- | | TXT | `mail.example.com` | `v=spf1 include:mailgun.org ~all` | SPF | | TXT | `._domainkey.mail.example.com` | `k=rsa; p=...` | DKIM public key | | CNAME | `email.mail.example.com` | `mailgun.org` | Mailgun tracking CNAME | MX records come back as a separate set, and you need them only if the domain should receive mail. The [sending domains docs](https://docs.buildbase.app/email/sending-domains) cover adding and verifying. Now the part that matters. Verification is `POST /api/emails/domains/:id/verify`, which asks Mailgun to re-check DNS. Our docs say a record that has not propagated comes back as a 400. The code never reads the DNS result: the route returns 400 when the call to Mailgun fails, and treats any 200 from Mailgun as success. And Mailgun's [own reference example](https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/domains/put-v4-domains--name--verify) for that call is a 200 whose body reads, trimmed: ```json { "message": "Domain DNS records have been updated", "domain": { "name": "example.com", "state": "unverified" } } ``` So a 200 from us is not proof, and neither is the `email.domain_verified` event that fires after it. Read `state` on the domain document the call returns. A working domain reads `active`. Then read `valid` on each entry in `sendingDnsRecords`: any entry where it does not say `valid` is the record Mailgun could not find. One gate does read `state`. A Mailgun sender cannot be created on a domain whose state is `unverified`; the route refuses with `Domain is unverified`. It checks once, at creation. If a record reads invalid and propagation is not the explanation, rule out the two SPF mistakes that look fine in a DNS panel. A second `v=spf1` record at the same name is a permanent error ([RFC 7208, section 4.5](https://www.rfc-editor.org/rfc/rfc7208#section-4.5)), so if one already exists, add `include:mailgun.org` to it rather than publishing another. More than 10 DNS lookups while evaluating it, nested includes counted, is a permanent error too ([section 4.6.4](https://www.rfc-editor.org/rfc/rfc7208#section-4.6.4)). Then ask DNS directly what it serves: ```bash dig +short TXT mail.example.com dig +short TXT ._domainkey.mail.example.com dig +short TXT _dmarc.example.com ``` ### 3. DMARC is the record nobody hands you Look at that table again. No DMARC record. Mailgun's reference describes its verify call as checking A, CNAME, SPF, DKIM and MX records, so a domain can verify cleanly with no DMARC record anywhere. You publish it yourself. Does a transactional sender need it? Google [requires DMARC](https://support.google.com/a/answer/81126) from anyone sending more than 5,000 messages a day to personal Gmail accounts, accepts a policy of `p=none`, and requires the From domain to be aligned with either the SPF domain or the DKIM domain. Yahoo's [sender requirements](https://senders.yahooinc.com/best-practices/) ask bulk senders for a DMARC policy of at least `p=none` and say DMARC must pass. Neither page sets a separate rule for transactional mail. Below that volume Google asks every sender for SPF or DKIM, not DMARC. I would publish it at any volume. It is one TXT record, and at `p=none` it asks receivers to change nothing, while the aggregate reports from the receivers that send them show you who is mailing as your domain: ```text _dmarc.example.com. TXT "v=DMARC1; p=none; rua=mailto:dmarc-reports@example.com" ``` One record on the apex covers `mail.example.com` as well. A receiver that finds nothing at the subdomain falls back to the organizational domain ([RFC 7489, section 6.6.3](https://www.rfc-editor.org/rfc/rfc7489#section-6.6.3)), and with no `sp` tag the `p` policy applies to subdomains. Alignment is where the three kinds of sender differ: - **Mailgun.** The From is built from the verified domain when the sender is created, so it starts aligned. It does not have to stay that way. `PATCH /api/emails/senders/:id` accepts a new `from` and validates only that it is an address. Nothing compares its domain with the one Mailgun verified. - **Custom SMTP.** The From is whatever was typed. Saving the sender checks, by default, that the credentials connect. It proves nothing about whether your SMTP provider signs for that domain, which is set up at the provider, not with us. - **Google.** Mail goes out through Gmail as the connected account, from that account's address. Good for a test. Not your domain. Relaxed alignment is the default ([section 6.3](https://www.rfc-editor.org/rfc/rfc7489#section-6.3)) and only needs the organizational domains to match, so a DKIM signature for `mail.example.com` aligns with a From of `hello@example.com`. That is why the `mail.` subdomain the docs suggest costs you nothing at this step. ### 4. Every link points at our host, not yours This is the cause you cannot fix from your side today, and I would rather you heard it from us. Every message BuildBase sends, the magic link included, goes through a tracking rewrite on its way to the transport. The one exception is the sender test described below. Each `href` in the HTML part and each bare URL in the text part becomes `/api/mail-track/link/`, and a hidden 1x1 image from `/api/mail-track/blank-image/` is appended to the body. A unit test, `email-send-funnel.test.ts`, asserts that exactly one file hands mail to a transport, so no send path skips the rewrite. Your plan does not change it either. On a plan without open and click analytics the pixel still loads and the redirect still runs. Only the analytics row goes unwritten. `SERVER_URL` is the tenant server's public address. On the managed service that is a `buildbase.app` host, and our own engineering notes say it plainly: customer link reputation lands directly on a `buildbase.app` host. Receivers do look at the domains inside a message. Spamhaus publishes a [domain blocklist](https://www.spamhaus.org/blocklists/domain-blocklist/) meant to be checked against "domains appearing in the mail headers and body e.g., URLs". So part of the verdict on your sign-in email is about a domain that is not yours and cannot be changed from the console. Per-org tracking domains are not built, and there is no setting that turns the rewrite off. Two things you can do about it. **Isolate it.** The console's **Send test email** is the one message that deliberately carries no tracking: no pixel, no rewritten links, no unsubscribe header. It always goes to your own account's address, so run the comparison there. Send a test through the system-default sender, then request a real magic link to the same address. If the test reaches the inbox and the sign-in email does not, from the same sender, your DNS is fine. The difference is in the message. **Self-host.** On a self-hosted install `SERVER_URL` is your own host, so the links can sit under your own domain. ### 5. When all three pass: history, then content SPF, DKIM and DMARC all pass for your own domain, and the right sender sent it. What is left has no header of its own: the domain's sending history, and the message itself. The test split from cause 4 tells you which: if both copies land in spam, look at history, and if only the real sign-in email does, look at the message. History first. A domain you added last week has none for a receiver to go on. Gmail's [Postmaster Tools](https://postmaster.google.com/) reports the spam rate it measured for your domain, and Google [asks every sender](https://support.google.com/a/answer/81126) to keep it below 0.3%. Keep sign-in mail on its own subdomain, so a campaign that draws complaints cannot drag your magic links down with it. That is how our own platform mail is set up. Organization invitations go out from `noreply@mail.buildbase.app`, on the `mail.` subdomain on purpose: it is the domain the relay signs for, so it is the domain DKIM aligns with, and keeping transactional mail off the root domain means an invitation cannot damage the reputation the marketing site sends from, or the other way round. Replies go to whoever sent the invitation, through Reply-To, so the recipient always has a person to answer. Content goes last because nothing in the header points at it, so the only way to test it is by changing it. Google's sender guidelines say links "should be visible and easy to understand", and that recipients "should know what to expect when they click a link". The default magic-link template is a few short lines and one link labelled **Sign in**. If yours has grown into a newsletter, put the default back for a day and see where it lands. ### Install ```bash npm i @buildbase/sdk ``` --- ## Usage counts that do not match the invoice > Usage does not match the invoice? The invoice bills overage blocks for a period that already closed. How to reconcile the two, fastest check first. - Source: https://www.buildbase.app/guides/usage-does-not-match-invoice - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-10-12 - Updated: 2026-10-22 ### In short A usage counter and an invoice are not meant to agree. The counter holds every unit since the last monthly reset. The invoice bills only units past the included amount, rounded up to whole blocks, for a Stripe period that has already closed. Check that arithmetic first, then which period each number covers. On any plan with an included allowance, a usage screen that matched the invoice would be the bug. They count different things. The usage screen reads one field on the workspace, `quotas.`, which holds every unit recorded since the counter last reset. The invoice bills a Stripe metered line that only ever received the units past the plan's included amount, rounded up to whole blocks, for a billing period that has already closed. Different quantity, different unit, different window. A dashboard reading 12,500 beside an invoice line reading 3 can be exactly right. So "why don't they match" is the wrong question. The useful one is whether the gap is the gap the code produces. The checks below run in the order that settles that fastest, so stop at the first one that explains your number. > **Before you start:** The Stripe account you connected under Billing → Credentials, because that is > where the invoices live. The workspace id and the quota slug. And two numbers > from the quota on its plan version: the included amount and the unit size. The > SDK's invoice object carries totals and links but no line items, so the line > you are reconciling is read in Stripe, on the dashboard or the hosted invoice > page. ### Read the symptom first | What you see | Where to look first | | ------------------------------------------- | -------------------------------------------- | | Invoice quantity far below the usage screen | Blocks, not units | | No overage line at all | Trial, hard limit, annual plan, or in flight | | Last period's overage on this invoice | A late report, or a plan change | | Usage screen low, invoice high | A reset after a missed payment | | Your own logs higher than the counter | Records that were refused | | The counter higher than your own logs | Retries that were not deduplicated | ### Compare blocks to blocks The invoice line for a quota is a Stripe product named after the quota item with "Overage" on the end, and its quantity is not units. It is billable blocks. Each record reports the difference between the block count after it and the block count before it, so over a period the line adds up to: ```text overage = max(0, consumed - included) billable blocks = ceil(overage / unitSize) ``` Put demo numbers through it. A plan includes 10,000 `api-calls` and prices overage per 1,000. The workspace has consumed 12,500. Overage is 2,500, which is 3 blocks. The usage screen says 12,500, the invoice says 3, and nothing is wrong. The pre-built usage screen, `openWorkspaceSettings('usage')`, already does this arithmetic. When the unit size is above 1 it prints a "Billable blocks" row, and its estimated charge multiplies that same ceiling by the overage rate. Compare the invoice to that row, not to the big number at the top. From your own code it looks like this. I have not run the snippet as written, so treat it as a shape rather than a tested script. ```ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); // unitSize comes from the quota on the plan version: 1 when overage is // priced per unit, 1000 when the rate reads "per 1,000". export async function expectedBlocks( workspaceId: string, quotaSlug: string, unitSize: number ) { const q = await bb.usage.getQuota(workspaceId, quotaSlug); return { consumed: q.consumed, // what the usage screen shows included: q.included, blocks: Math.ceil(q.overage / unitSize), // what Stripe is told }; } ``` Three situations never produce an invoice line, however high the counter goes. A trialing subscription is capped at its included amount and its overage is never reported. A quota with overage turned off is a hard limit, and the Stripe subscription carries no metered item for it at all. And a free plan has no Stripe subscription to bill. Our own plans lean on the second kind heavily: on the paid plans only workflow runs, web analytics events and storage bill over (storage at $0.10 per GB-month beyond the plan allowance), while emails and webhook deliveries are hard allowances that never reach an invoice, and our Free plan bills nothing at all. Credits never reach one either. A credit pack is a one-time payment, and spending credits debits a wallet rather than reporting usage to Stripe. If the number you are reconciling is a credit balance, you are on the other system, and [quotas are not credits](/blog/quotas-are-not-credits) is where the two part ways. Price can drift too, separately from quantity. The invoice charges the Stripe price's unit amount. If the plan version's overage rate and that Stripe price have come apart, the server logs an "Overage amount mismatch" warning and keeps billing at Stripe's figure, while the usage screen's estimate reads the plan. Same blocks, different total. > **Key takeaway:** Reconcile the invoice quantity against ceil((consumed - included) / unitSize) > for the same window. If that holds, nothing is broken. If it does not, the > next three checks are about timing. ### Check which period the invoice is billing Stripe bills metered usage [in arrears](/blog/metered-vs-seat-based-billing). Its own documentation puts it plainly: at the end of the billing period, the total usage is multiplied by the unit amount. So the overage on an invoice belongs to the period that just closed, and by the time that invoice reaches anyone, the usage screen has reset or is about to. You are holding last period's bill against this period's counter. To see what the next invoice will bill, preview the upcoming invoice in Stripe. Stripe's docs warn that the quantity there "might not be the most up-to-date", because its own processing lags a little. On an annual plan the gap is a year. Overage prices are created with the same interval as the plan's base price, because the subscriptions BuildBase creates, through Checkout on Stripe's classic billing mode, must keep every price on one interval. So a yearly subscription carries a yearly metered item. The counter, meanwhile, resets monthly whatever the interval. Twelve monthly counters' worth of overage goes onto one invoice at renewal. A customer who went over in the second month sees it on an invoice about ten months later, unless a plan change bills it sooner. That is the other way usage jumps invoices. Removing a metered item from a Stripe subscription discards its usage, so before a plan change swaps the items, the server reads what each metered item has accumulated and moves it onto the next invoice as an invoice item described `Usage before plan change: N unit(s)`. N there is blocks. So after a plan change, one quota's overage can arrive on two lines: the carried one, on the next invoice the subscription produces, and the new metered item's own line, counting up from zero. Why the carry exists at all is in the [proration guide](/guides/proration-on-plan-change-nextjs). ### Check whether it has reached Stripe yet Recording happens in two phases, and only the first one is in your request. The call increments the counter and returns. Reporting the overage to Stripe is a queued job. The response tells you which happened: `billedAsync: true` means a job was queued for this record, and `false` means either nothing was billable or the enqueue failed. The job gets 5 attempts with exponential backoff starting at 3 seconds. A report that never lands leaves its usage log marked unbilled, and a sweep at :03, :13, :23 and every 10 minutes after re-queues unbilled logs older than 2 minutes, up to 100 per org per pass. In the normal case Stripe is one queued job behind the counter. After a failure, a sweep or two behind. The Stripe idempotency key on that report is the usage log's id, not the job's. It used to be the job's, and the comment in the code records what that cost: the sweep re-queued a log whose "billed" flag had failed to save after Stripe had already accepted the usage, the re-queue was a new job with a new id, and the same overage was billed twice. [Key on the thing being billed](/blog/idempotency-in-billing), not on the attempt to bill it. Everything else in this post keeps landing on that rule. ### Usage near a boundary lands one invoice later Stripe refuses a usage record stamped before the subscription's current period. Its docs describe a grace window of a few minutes for clock drift, and say not to rely on it. The worker doesn't. When a report is stamped before the open period's start, which is exactly what a sweep produces when it re-queues a log created just before a renewal, the worker stamps it at the start of the open period instead. The usage is billed. One invoice late. So the closing invoice comes up short by those blocks and the next one runs long by the same amount. Two consecutive invoices reconcile even when neither does on its own, which is worth checking before anyone opens a ticket. The counter also keeps its own clock. Its monthly period starts when the checkout webhook is processed, not at Stripe's billing anchor, and a reset only takes effect once that period has ended. The reset sweep runs every 5 minutes. Net effect: the counter resets a little after Stripe renews. Units recorded in that gap count against the old counter, and if it was already past its included amount, they bill as overage into the new Stripe period. With a trial, the gap is not a little. Stripe anchors the billing cycle at the trial's end by default, while the counter anchored at checkout. Say the trial is 14 days: every counter month starts two weeks before the invoice month, and it stays that way, so each invoice's overage is drawn from two counter windows. Units used during the trial also stay on the counter after it converts, until the counter's own month runs out. Your own logs are a third clock. Sum them by calendar month and you are comparing against a window neither system uses. Use the invoice line's own period, which Stripe gives in Unix seconds: ```ts // periodStart and periodEnd: the invoice line's period, from Stripe const page = await bb.usage.getLogs(workspaceId, { quotaSlug: 'api-calls', from: new Date(periodStart * 1000).toISOString(), to: new Date(periodEnd * 1000).toISOString(), limit: 100, }); // page.docs, page.hasNextPage: page through and sum quantity ``` How far back that reaches is bounded by a log-retention limit on your BuildBase plan, so reconcile while the period is recent rather than at year end. ### A missed payment changes what counts as overage A `past_due` subscription can still record usage. [Entitlement treats it as the grace window](/blog/what-are-entitlements) while Stripe retries the card, and overage keeps being reported. What it does not get is a reset. Reset eligibility is `active` and `trialing` only, on purpose, so a failing card does not buy a fresh allowance. Follow that through a renewal. The counter carries last period's total into the new one, so every new unit is already past the included amount, and every new unit bills. Then the payment recovers, a reset is queued straight away, and the usage screen drops to a small number while the upcoming invoice holds a pile of overage. Neither number is wrong. It is the same rule, read at two moments. On a quota with overage off, the identical gap shows up as a counter stuck at the cap instead, which the [429 guide](/guides/quota-429-not-exhausted) walks through. One step further, a subscription suspended by dunning is not entitled to record at all. The call fails with `No active subscription found`. Your app did the work, nothing was counted, and nothing will be billed. ### Then compare your own logs with the counter Everything so far is the counter against the invoice. If the counter disagrees with what your app believes it did, the cause is on the recording side, and the direction tells you which. **Your logs are higher.** Records were refused. A quota rejection, a missing subscription, or a batch item reported as `success: false` inside a response that was otherwise a 200. Each is work your app did that was never counted. **The counter is higher.** A retry was counted, which the [per-call billing guide](/guides/charge-per-api-call-nextjs) names as the invoice dispute you will actually get. An idempotency key is matched on workspace, quota slug and key together, and a replay of a finished record is absorbed: the response comes back with `used: 0`, which is the cheapest way to watch deduplication working. It fails in two shapes. The first is a fresh key per attempt. Our own docs sample keys on `req.headers.get('x-request-id')`, which is only stable if your caller sets that header and resends it. If a proxy in front of you mints one per inbound request, every retry is a new key and a new unit. The second is an overlapping retry. [The key is checked with a read before the increment](/blog/idempotency-keys-metering-write-path) and stored with the usage log after it, so a retry that arrives while the first attempt is between those two points passes the check. Both count. Both bill. Retry after a backoff, never in parallel, and never from a client timeout shorter than the call takes to answer. The fix for the first shape is to mint the key where the operation is defined, not where the attempt happens: ```ts // The key is created with the export and stored on it, so every retry of // this job sends the same one. const usage = await bb.usage.record(workspaceId, { quotaSlug: 'exports', quantity: 1, idempotencyKey: `export:${exportId}`, }); if (usage.used === 0) { // A replay. This export was already counted, and nothing new was billed. } ``` Same caveat as before: I have not run it. Our own metering is built this way. When an org on BuildBase sends email, the send is counted into a Redis buffer, flushed every 30 seconds, and reported onto a workspace counter in our own BuildBase, the same kind your app writes through the SDK. The key is minted once, when the buffer is taken, and travels with the queued job. The comment above that code says why: a retry that re-read the buffer "would send new counts under an old key, or old counts twice". ### When the counter and the invoice move differently Three paths move the counter and the invoice by different amounts. A correction in the console. The admin path, `PATCH /api/workspaces/:id/quota/usage`, sets values absolutely. An increase goes through the billing path like any record. A decrease is written to the counter only, so lowering a counter after a bug leaves whatever was already reported to Stripe on the invoice; that needs a credit in Stripe. An increase the billing path refuses (no entitled subscription, or a trial or hard-capped quota at its limit) is written to the counter anyway, without billing. A correction path that reaches the invoice is one of the pieces [building metering yourself](/blog/cost-of-building-usage-metering-yourself) has to price in. A write-off. When the sweep finds an unbilled log whose workspace no longer has a Stripe subscription, a cancellation for instance, it marks the log billed without reporting it. Overage that failed to report before a cancellation is dropped rather than chased. Records that land at the same instant. Overage is computed from the counter as it was read before the increment, so simultaneous records each see the same starting value. The code comment says this can slightly under-bill, and across the included line with a unit size of 1, it does. With a unit size above 1, two simultaneous records that each open a new block each bill it, so the invoice can also run a block over. Sequential records add up exactly. This is the last place to look, and only when traffic for one workspace overlaps. ### Install ```bash npm i @buildbase/sdk ``` --- ## Multi-tenant workspaces in Express, Hono and Fastify: one middleware that checks membership > Multi-tenant workspaces in Express, Hono and Fastify: take the workspace from the path, then refuse any user who is not a member, in one middleware. - Source: https://www.buildbase.app/guides/multi-tenant-workspaces-express - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-28 ### In short A multi-tenant Express API takes the workspace ID from the route path, then checks in one middleware that the signed-in user is a member, answering 403 if not. Mounted on the router, every handler inherits the check. Hono does the same with createMiddleware, Fastify with a preHandler hook in a prefixed plugin. The [multi-tenant](/blog/what-is-multi-tenancy) Express tutorials that rank today show you how to read a tenant ID. A subdomain, an `X-Tenant-ID` header, a claim in the JWT. Then they hand that ID to a database query and move on. Reading the ID was never the hard part. It tells you which workspace the client **wants**, and nothing about which one it is allowed to have. Skip that second question and your API serves workspace B's invoices to anyone who types B's ID into a request. Our own setup guides have a version of this gap. The [Express](/guides/buildbase-on-express) and [Hono](/guides/buildbase-on-hono) pages do `const [workspace] = await bb.workspace.list()` and use the first one, and the [Fastify](/guides/buildbase-on-fastify) gateway's `account()` and `spend()` stand for one workspace the same way. That is fine for one workspace per user. Give someone two and "which workspace?" needs a real answer, which is this page. The answer fits in one middleware: take the ID from the path, ask BuildBase what this user may do there, refuse if the answer is nothing, and mount it where no handler can be written without it. > **Before you start:** Sign-in already working through the setup guide for your framework, so every > request carries a BuildBase session. An organization in **Platform** mode, > which is sold on a plan: new organizations start in Personal mode, one > workspace per user, and there is nothing to switch between. `@buildbase/sdk` > 0.0.73 or later, which has `workspace.permissions()`. ### Express: one middleware that fails closed Add it next to `forRequest` from the setup guide: ```js // middleware/workspace.js const buildbase = require('../config/buildbase'); /** * Resolves req.params.workspaceId to what this user may do there, or refuses. * Fails closed: any error ends the request before a handler runs. */ exports.requireWorkspace = async (req, res, next) => { const { workspaceId } = req.params; if (!workspaceId) return res.status(400).json({ message: 'No workspace.' }); try { const access = await buildbase .forRequest(req) .workspace.permissions(workspaceId); req.workspace = { id: workspaceId, ...access }; return next(); } catch (err) { if (err.status === 400 || err.status === 403 || err.status === 404) { return res.status(403).json({ message: 'No access to this workspace.' }); } return next(err); } }; ``` `permissions()` returns `{ role, isOwner, permissions }`, resolved by BuildBase's server for the signed-in user. A member gets their role (`admin`, `editor`, `viewer`, or one your organization defined) and the permission list that role carries. Not a member? The SDK throws an error with `status: 403`, and it throws the same for a workspace that does not exist. A string that is not a valid workspace ID at all gets 400. We turn all three into one 403. Why not 404 for the one that does not exist? Because then the status leaks which IDs are real. GitHub makes the opposite call and [answers 404](https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api) for private repositories it will not show you. Either is defensible. Mixing them is not. Never 401, though. A 401 says "you are not signed in", and a well-behaved client acts on it by signing the user out. Our own React SDK does exactly that: a 401 from BuildBase clears the stored session and calls `onSessionExpired`. BuildBase's API once answered membership failures with 401, and the guard's comment now reads "A 401 here signed people out for opening a workspace they had lost access to." Your API's clients will draw the same conclusion from yours. Anything else, a timeout or a 5xx, goes to `next(err)` and on to your error handler. The request still does not reach a handler. That is what fails closed means here: there is no path through this function that calls `next()` without a membership answer in hand. ### Mount it where a handler cannot miss it ```js // routes/workspace.js const express = require('express'); const { requireWorkspace } = require('../middleware/workspace'); const reports = require('../controllers/reports'); const router = express.Router({ mergeParams: true }); router.use(requireWorkspace); router.get('/reports', reports.list); router.post('/reports', reports.create); module.exports = router; ``` ```js // app.js app.use( '/workspaces/:workspaceId', isAuthenticated, require('./routes/workspace') ); ``` `mergeParams: true` is the line people lose an hour to. Its default is `false`, and Express documents what it does as "preserve the `req.params` values from the parent router." Without it, `:workspaceId` belongs to the `app.use` path, the router never sees it, `req.params.workspaceId` is `undefined`, and every request gets "No workspace." Why `router.use` and not `router.param('workspaceId', ...)`? Because param callbacks "are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers." On a `mergeParams` router, `workspaceId` is exactly such an inherited parameter, so the callback would never fire at all. `router.use` has no such exception. Now a handler reads the workspace it has already been cleared for: ```js // controllers/reports.js exports.create = async (req, res) => { if (!req.workspace.permissions.includes('app:reports:create')) { return res .status(403) .json({ message: 'Your role cannot create reports.' }); } // ...create the report in req.workspace.id res.status(201).json({ ok: true }); }; ``` No second round trip. `bb.workspace.can(workspaceId, 'app:reports:create')` exists and returns a boolean, but it is another request for an answer the middleware already fetched. To check it: call `GET /workspaces//reports` signed in, then the same path with a workspace you are not in. The first reaches the handler. The second answers 403 and the controller never logs a thing. > **Key takeaway:** Put the membership check in `router.use` on a router created with > `mergeParams: true`, and no handler under it can run for a workspace the user > is not in. Refuse with 403, never 401, and hand every other error to > `next(err)` so the request fails closed. ### Hono: one more method on the client, then `createMiddleware` Hono's setup guide keeps `forSession` private inside `buildbaseFor`. Add one method to the object it returns, so the middleware does not reach around it: ```ts // src/buildbase.ts (add to the object buildbaseFor returns) workspaceAccess: (sessionId: string, workspaceId: string) => forSession(sessionId).workspace.permissions(workspaceId), ``` ```ts // src/workspace.ts import { getSignedCookie } from 'hono/cookie'; import { createMiddleware } from 'hono/factory'; import { buildbaseFor } from './buildbase'; import { config } from './config'; // the setup guide's env() helper, moved to its own file type WorkspaceAccess = { id: string; role: string | null; isOwner: boolean; permissions: string[]; }; export const requireWorkspace = createMiddleware<{ Variables: { workspace: WorkspaceAccess }; }>(async (c, next) => { const sessionId = await getSignedCookie( c, config(c).COOKIE_SECRET!, 'bb_session' ); if (!sessionId) return c.json({ message: 'Sign in first.' }, 401); const workspaceId = c.req.param('workspaceId'); if (!workspaceId) return c.json({ message: 'No workspace.' }, 400); try { const access = await buildbaseFor(config(c)).workspaceAccess( sessionId, workspaceId ); c.set('workspace', { id: workspaceId, ...access }); } catch (err) { const status = (err as { status?: number }).status; if (status === 400 || status === 403 || status === 404) { return c.json({ message: 'No access to this workspace.' }, 403); } throw err; } await next(); }); ``` ```ts // src/index.ts const workspace = new Hono() .use(requireWorkspace) .get('/reports', (c) => c.json({ workspace: c.var.workspace.id })); app.route('/workspaces/:workspaceId', workspace); ``` Two differences from Express. The 401 for no session is fine here, because there really is no session; it is only a membership failure that must never be 401. And the `Variables` type on `createMiddleware` is what makes `c.var.workspace` typed in the handlers chained after `.use()`. Call `.use()` as a separate statement and the sub-app's type never learns about it. ### Fastify: encapsulation does the mounting A hook added inside a registered plugin covers that plugin's routes and nothing else. Fastify says "all hooks are encapsulated" except `onClose`. So register the workspace routes as one plugin with a prefix, and the hook can neither leak out to other routes nor be skipped by these. The gateway interface from the setup guide grows one method, and so does the fake your tests pass in through `opts.buildbase`, or every workspace route answers 500 in tests: ```ts // src/plugins/app/buildbase.ts (add to BuildBaseGateway and createGateway) workspaceAccess( sessionId: string, workspaceId: string ): Promise<{ role: string | null; isOwner: boolean; permissions: string[] }>; ``` ```ts // src/routes/workspaces.ts import { FastifyInstance } from 'fastify'; declare module 'fastify' { interface FastifyRequest { workspace: { id: string; role: string | null; isOwner: boolean; permissions: string[]; } | null; } } export default async function workspaceRoutes(fastify: FastifyInstance) { fastify.decorateRequest('workspace', null); fastify.addHook('preHandler', async (request, reply) => { const { workspaceId } = request.params as { workspaceId: string }; try { const access = await fastify.buildbase.workspaceAccess( request.session.buildbaseSessionId ?? '', workspaceId ); request.workspace = { id: workspaceId, ...access }; } catch (err) { const status = (err as { status?: number }).status; if (status === 400 || status === 403 || status === 404) { return reply .code(403) .send({ message: 'No access to this workspace.' }); } throw err; } }); fastify.get('/reports', async (request) => ({ workspace: request.workspace!.id, })); } ``` ```ts // src/app.ts fastify.register(workspaceRoutes, { prefix: '/workspaces/:workspaceId' }); ``` Why `preHandler` and not `onRequest`? Routing runs before `onRequest`, so the params exist in both. But `preHandler` runs after your session and auth hooks, so the check sees a session that has already been validated. Do not wrap `workspaceRoutes` in `fastify-plugin`. That is how you share a decorator with the whole app, and it is the opposite of what you want here: Fastify's docs say `prefix` "will not work" on a plugin wrapped with it, and the hook would escape to every route. ### Why the path, and not a header or the token All three frameworks read the ID from `/workspaces/:workspaceId`, and that is a choice. The path lands in every access log you already have, so "who touched workspace X last Tuesday" is a grep. It can be linked, bookmarked and pasted into a support ticket. A header shows up in none of those. It works, and reading `req.get('X-Workspace-Id')` instead is a one-line change to the middleware, but you give up the logs for nothing. Subdomains (`acme.yourapp.com`) are a browser-app decision, usually about custom domains, and a different problem from membership. Avoid the JWT claim. It is decided when the token is issued: remove someone from a workspace at 10:00 and a token issued at 09:55 still names it until it expires. Wherever the ID comes from, the check stays the same. None of these sources is proof. ### What it costs One HTTP round trip per request, to BuildBase's API. The server SDK does not cache, so two requests to the same workspace ask twice. You can put a short in-memory cache in front of `permissions()`, keyed on session and workspace. [We left it out, on purpose](/blog/why-permissions-refresh-hourly). The price is exact: a member you remove keeps access for the length of the TTL. Thirty seconds is fine for a reporting app and wrong for anything that moves money. Choose it knowing that, or not at all. ### When it goes wrong | What you see | Why, and the fix | | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Every request answers "No workspace." | The router was created without `mergeParams: true`, so `req.params.workspaceId` is `undefined` inside it. | | Users get signed out when they open a workspace they left. | Something answers membership failures with 401, and the client treats it as a sign-out. Membership is 403. 401 means the session itself is gone. | | One nested router skips the check. | It hangs off a `router.param` callback, which mounted routers do not inherit. Move the check to `router.use`. | | A Fastify route outside the prefix is guarded, or one inside is not. | The plugin is wrapped in `fastify-plugin`, which breaks encapsulation and the prefix with it. | | The right user, the right workspace, still 403. | The server does not count them as a member. An accepted invitation that never became a membership looks exactly like this: see [an invited member who cannot see the workspace](/guides/invited-member-cannot-see-workspace). | The worst failure raises no error at all: every query returns everyone's rows. The middleware decides who may enter a workspace. It does not filter your database, so [every query still needs `where workspace_id = req.workspace.id`](/guides/per-org-data-isolation-nextjs), or a [database per tenant](/blog/database-per-tenant-vs-shared-schema). Building on React Router instead? The same problem has a different trap there, where a parent loader's check does not guard its children: [multi-tenant workspaces in Remix](/guides/multi-tenant-workspaces-remix). Metering usage per workspace builds on this: the [usage metering middleware](/guides/usage-metering-middleware-express) reads the workspace, and who may record against it, from `req.workspace`. ### Install ```bash npm i @buildbase/sdk ``` --- ## Multi-tenant Remix: put the workspace in the URL, and check membership before any loader runs > Multi-tenant workspaces in Remix and React Router v7 or v8: the workspace lives in the URL, and one membership check runs before any loader can fetch. - Source: https://www.buildbase.app/guides/multi-tenant-workspaces-remix - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-28 ### In short A multi-tenant Remix or React Router app should keep the active workspace in the URL as /w/:workspaceId, not a cookie, so each tab stays in its own workspace. Check membership before any loader runs: one middleware on v8 or flagged v7, or one helper in every loader, because loaders run in parallel. Here is the check almost every multi-tenant Remix app starts with. A layout route at `/w/:workspaceId` loads the workspace, throws if the user is not a member, and every page for that workspace nests under it. It reads like a guard. For years it was not one. Remix, and React Router before middleware, ran the loaders of every matched route in parallel. The Remix team put it bluntly when they shipped middleware: people assumed "a redirect from a parent loader would prevent the child loader from running - but this was also not the case." Your `projects` loader has already queried the database and returned rows for a workspace the user was never in, while the layout is still on its way to throwing. Two decisions follow, and the second matters more. The workspace lives **in the URL**. And the membership check runs **before any loader**: in middleware if your React Router has it, in one helper that every loader and action calls if it does not. > **Before you start:** A React Router v7 or v8 app in framework mode (or Remix v2) with sign-in > working through the [React Router setup > guide](/guides/buildbase-on-react-router). A `requireBuildBase(request)` > helper that returns a session-bound client, as in [usage-based billing in > React Router](/guides/usage-based-billing-react-router). Your organization in > **Platform** mode: new organizations start in Personal mode, one workspace per > user with the switcher hidden, and there is nothing to switch between. ### The workspace goes in the URL, not the cookie A cookie holds one "current" workspace for the whole browser. A URL holds one per tab, and a link pasted into Slack opens the right workspace for whoever clicks it. Keeping `currentWorkspaceId` in the cookie session is tempting anyway: every loader can read it, and URLs stay short. Then someone opens a second tab and switches workspace there, which rewrites the cookie. Back in the first tab nothing moves. At the next revalidation, the page they were reading [quietly shows the other tenant's data](/guides/stale-data-after-workspace-switch) under the same URL. Worse, a form posted from that first tab lands in whichever workspace the cookie names now. (A subdomain per customer, routed by host header, is a different problem: custom domains, not one user in several teams. This guide does not cover it.) The cookie keeps one job: remembering which workspace to open **by default**. The `/w` redirect further down uses it that way and nowhere else. ### One function asks the server whether this user is a member Put the membership check in one function, and make it the only way a route gets a workspace: ```ts // app/utils/workspace.server.ts import { buildbaseFor } from '#app/utils/buildbase.server.ts'; import { data } from 'react-router'; type BuildBaseClient = ReturnType; export type Workspace = { id: string; role: string | null; permissions: string[]; }; export async function resolveWorkspace( bb: BuildBaseClient, workspaceId: string ): Promise { try { const me = await bb.workspace.permissions(workspaceId); return { id: workspaceId, role: me.role, permissions: me.permissions }; } catch (err) { const status = (err as { status?: number }).status; if (status === 400 || status === 403 || status === 404) { throw data('Workspace not found', { status: 404 }); } throw err; } } ``` `bb.workspace.permissions()` asks the server what the session's user may do in that workspace, and gets back `{ role, isOwner, permissions }`. The server resolves it from the workspace's own members, so a workspace ID typed into the address bar proves nothing on its own. Two answers come back as errors. A string that is not a valid ID gets a 400 (`Invalid workspace ID.`). A workspace the user does not belong to gets a 403 (`You are not a member of this workspace.`), and so does one that does not exist at all. That second part is deliberate. The same answer for both means nobody can probe for which workspace IDs are real. The `status` sits on the thrown error but not in the SDK's type definitions, hence the cast. Note what the function **does not** do: redirect to `/login`, or answer 401. We learned that one on our own server. Its membership guard used to answer 401, and our React SDK treats every 401 from it as a dead session. As the comment in that guard now says, "A 401 here signed people out for opening a workspace they had lost access to." A user removed from one workspace is still signed in, and still a member of the others. Send them a 404 page with a link home. ### With middleware (v8, or v7.9+ with the flag): one check on the layout Middleware is the framework's own answer to the parallel-loader problem. It "runs sequentially on the server before and after document and data requests," and on the leaf route `next` is what runs the loaders and actions. Throw before `next` and no loader below runs. It is always on in React Router v8. On v7.9 or later, turn it on first: ```ts // react-router.config.ts (v7.9+ only; remove the flag on v8, whose build // fails while it is still set) import type { Config } from '@react-router/dev/config'; export default { future: { v8_middleware: true }, } satisfies Config; ``` Then the layout route checks once and hands the result down: ```tsx // app/routes/w.$workspaceId.tsx import { requireBuildBase } from '#app/utils/buildbase.server.ts'; import { resolveWorkspace, type Workspace, } from '#app/utils/workspace.server.ts'; import { createContext, Outlet } from 'react-router'; import type { Route } from './+types/w.$workspaceId'; export const workspaceContext = createContext(); export const middleware: Route.MiddlewareFunction[] = [ async ({ request, params, context }) => { const bb = await requireBuildBase(request); context.set( workspaceContext, await resolveWorkspace(bb, params.workspaceId) ); }, ]; export default function WorkspaceLayout() { return ; } ``` A child route reads the workspace from context instead of from `params`: ```ts // app/routes/w.$workspaceId.projects.tsx import { prisma } from '#app/utils/db.server.ts'; import type { Route } from './+types/w.$workspaceId.projects'; import { workspaceContext } from './w.$workspaceId'; export async function loader({ context }: Route.LoaderArgs) { const workspace = context.get(workspaceContext); const projects = await prisma.project.findMany({ where: { workspaceId: workspace.id }, }); return { projects, canEdit: workspace.permissions.includes('app:projects:create'), }; } ``` That `context.get` is the whole point. A child that reads the workspace this way cannot run without the middleware having set it, and the middleware cannot set it without the server having said yes. A child that reads `params.workspaceId` directly works too, right up until someone mounts it somewhere else. Open `/w//projects` and you should get the 404 page, with no query in your database log. ### Without middleware: the same check, in every loader and action On Remix v2, or React Router v7 before 7.9 or without the flag, there is no stable place that runs first. So the check goes where the data is: ```ts // app/utils/workspace.server.ts (continued) import { requireBuildBase } from '#app/utils/buildbase.server.ts'; export async function requireWorkspace( request: Request, params: { workspaceId?: string } ) { if (!params.workspaceId) { throw data('Workspace not found', { status: 404 }); } const bb = await requireBuildBase(request); return resolveWorkspace(bb, params.workspaceId); } ``` ```ts // app/routes/w.$workspaceId.projects.tsx export async function loader({ request, params }: Route.LoaderArgs) { const workspace = await requireWorkspace(request, params); const projects = await prisma.project.findMany({ where: { workspaceId: workspace.id }, }); return { projects }; } ``` Every loader. Every action, including the ones that only delete something, because an action is a POST to the same URL and nothing stops anyone sending it. The layout loader can call it too, for the name in the header, but it guards nothing below it. That is more repetition than the middleware version, and it is the honest case for upgrading. A helper you have to remember is a helper someone forgets in the fortieth route. In review, grep for `loader` and `action` exports under `routes/w.$workspaceId.*` and check every one calls it. Either way, every request now asks the server once, and data requests after navigation count. That round trip is the price of the server deciding. Do not cache the answer across requests: a membership revoked a minute ago has to stop working now. > **Key takeaway:** The URL says which workspace a tab wants. Only the server can say whether this > user may have it, and that answer has to arrive before any loader runs, which > a parent loader cannot promise. ### Where `/w` sends people Someone who types your domain has no workspace in their URL. An index route picks one: ```ts // app/routes/w._index.tsx import { requireBuildBase } from '#app/utils/buildbase.server.ts'; import { redirect } from 'react-router'; import type { Route } from './+types/w._index'; export async function loader({ request }: Route.LoaderArgs) { const bb = await requireBuildBase(request); const workspaces = await bb.workspace.list(); const lastUsed = await getLastWorkspaceId(request); // your cookie, if any const target = workspaces.find((w) => w._id === lastUsed) ?? workspaces[0]; if (!target) throw redirect('/welcome'); throw redirect(`/w/${target._id}`); } ``` `workspace.list()` returns every workspace the user belongs to, in one call. Use `_id` in the URL. The workspace object also has a field called `workspaceId`, which is a different value, and the membership check will answer 400 for it. Here the cookie earns its keep. It remembers the last workspace so `/w` can reopen it, and it is only ever a suggestion: the redirect still lands on a URL that goes through the membership check, and a stale cookie pointing at a workspace the user left just falls through to the first one. With **Auto-Create First Workspace** on (it is by default, under the workspace settings' Advanced Overrides), `list()` creates a workspace for a user who has none, so `/welcome` fires only when you have [turned that off](/guides/auto-created-first-workspace-nextjs), or when a workspace cap or your plan's limit refuses the auto-create: `list()` then answers with an empty list rather than an error. The switcher is a list of links. Each one goes to `/w/${w._id}`, and each tab can sit in a different workspace without either one noticing. ### Let members see, and only some of them act Check the permission in the action, not the button. You already have it: the membership check returns more than yes or no. `role` is `admin`, `editor` or `viewer` by default (stored lowercase, so compare against those), or a custom role, and `permissions` is the resolved list, platform keys and your organization's own. ```ts // app/routes/w.$workspaceId.projects.tsx (v8 version) import { data } from 'react-router'; export async function action({ context, request }: Route.ActionArgs) { const workspace = context.get(workspaceContext); if (!workspace.permissions.includes('app:projects:create')) { throw data('Your role cannot create projects.', { status: 403 }); } // ...create the project in workspace.id } ``` A viewer can open every page in the workspace and still gets a 403 from this action. That is working as intended. Hiding the button is a courtesy; the action is the rule. None of this costs a request, since the permissions arrived with the membership check. If you need the answer somewhere the middleware did not run, `bb.workspace.can(workspaceId, 'app:projects:create')` returns it as a boolean, at the price of another round trip. ### Five symptoms, and the cause behind each **Opening a workspace you were removed from signs you out.** Something maps the membership failure to 401, or redirects to `/login`. Answer 404 (or 403). The session is fine. **A child route returns data the user should not see, then the error page appears.** The check lives only in the parent loader. Move it into `middleware`, or on older versions call `requireWorkspace` in the child loader itself. **Two tabs keep switching each other's workspace.** The active workspace lives in a cookie. Put it in the URL and demote the cookie to the default for `/w`. **Every workspace page is a 404, even your own.** The URL carries the workspace's `workspaceId` field rather than its `_id`. The server answers 400 `Invalid workspace ID.`, and `resolveWorkspace` turns that into the 404. **A new teammate cannot see the workspace at all.** Membership, not routing. Start with [an invited member who cannot see the workspace](/guides/invited-member-cannot-see-workspace). Serving the same workspaces from an Express, Hono or Fastify API as well? There the check is one middleware, mounted where no handler can miss it: [multi-tenant workspaces in Express](/guides/multi-tenant-workspaces-express). Why workspaces belong in your data model in the first place, rather than a `teamId` bolted onto users, is in [multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon). ### Install ```bash npm i @buildbase/sdk ``` --- ## Usage-based billing in React Router (Remix): meter in the action, never the loader > Usage-based billing in React Router (Remix): record usage in the action, not the loader, and key each form render so a retried submit bills once. - Source: https://www.buildbase.app/guides/usage-based-billing-react-router - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-28 - Updated: 2026-10-22 ### In short In a React Router (Remix) app, record usage in the action that does the work, never in a loader: loaders re-run after every successful submission and on link prefetch. Generate the idempotency key in the loader and send it as a hidden field, so a retry bills once and the next report gets a fresh key. A React Router loader runs far more often than the page it belongs to is opened. It runs again after every successful action on the page. It runs when someone hovers a `` that points at it. Put a usage meter in there and you are billing customers for looking. The meter belongs in the action that does the work. The half that is easy to miss is the idempotency key, and it belongs in the loader. That sounds backwards until you see what it buys: a loader key survives a failed submission and rotates on a successful one. The example is a workspace that pays per generated report: a `reports` quota, one unit per report, a button that spends it and a counter that shows what is left. > **Before you start:** A React Router v7 or v8 app in framework mode (or Remix v2 with > `future.v3_singleFetch` on) with sign-in already working through the [React > Router setup guide](/guides/buildbase-on-react-router), which gives you > `buildbaseFor()` and a `buildbaseSessionId` in your cookie session. In the > console, a plan with a `reports` quota on it and a workspace subscribed to > that plan. Workspace IDs in the URL, as in [multi-tenant workspaces in > Remix](/guides/multi-tenant-workspaces-remix). ### 1. Get a session-bound client from the request The setup guide binds a client to one session with `withSession()`. Add a helper that pulls the session out of the cookie, so every loader and action starts from one line: ```ts // app/utils/buildbase.server.ts (next to buildbaseFor from the setup guide) import { authSessionStorage } from '#app/utils/session.server.ts'; import { redirect } from 'react-router'; export async function requireBuildBase(request: Request) { const authSession = await authSessionStorage.getSession( request.headers.get('cookie') ); const sessionId = authSession.get('buildbaseSessionId'); if (!sessionId) throw redirect('/login'); return buildbaseFor(sessionId); } ``` Nothing to see yet. Signed out, any route that calls it sends you to `/login`. ### 2. The loader reads the quota, and hands out a key ```ts // app/routes/w.$workspaceId.reports.tsx import { randomUUID } from 'node:crypto'; import { requireBuildBase } from '#app/utils/buildbase.server.ts'; import type { Route } from './+types/w.$workspaceId.reports'; export async function loader({ request, params }: Route.LoaderArgs) { const bb = await requireBuildBase(request); const quota = await bb.usage.getQuota(params.workspaceId, 'reports'); return { quota, idempotencyKey: randomUUID() }; } ``` `getQuota` returns `consumed`, `included`, `available`, `overage` and `hasOverage` for that one quota. It reads. It never writes, which is the whole reason it is allowed to live here: this loader will run on hover, on every revalidation, and on every navigation back to the page, and none of those should cost anyone anything. The key is the part that looks odd. Why would a read hand out a write's idempotency key? Hold that thought until step 5. Load `/w//reports` and you should see the loader data with a fresh UUID in it on every reload. ### 3. The action records the usage, then does the work ```ts // app/routes/w.$workspaceId.reports.tsx (continued) import { data } from 'react-router'; export async function action({ request, params }: Route.ActionArgs) { const bb = await requireBuildBase(request); const form = await request.formData(); const key = form.get('idempotencyKey'); if (typeof key !== 'string' || !key || key.length > 64) { return data({ error: 'Reload the page and try again.' }, { status: 400 }); } try { const usage = await bb.usage.record(params.workspaceId, { quotaSlug: 'reports', quantity: 1, idempotencyKey: `report:${key}`, }); const report = await generateReport(params.workspaceId); return { report, usage }; } catch (err) { const { status } = err as { status?: number }; // On the usage routes only the quota refusal answers 402. if (status === 402) { return data( { error: 'This workspace has used every report on its plan.' }, { status: 402 } ); } if (status === 403) { return data( { error: 'Your role cannot generate reports.' }, { status: 403 } ); } throw err; } } ``` Three things in there are not obvious. **The record comes first.** Our [per-API-call guide](/guides/charge-per-api-call-nextjs) records after the work succeeds, and on a plan that allows overage that is the right order, because `record` never refuses for being over quota: past the included amount it counts the units as overage. On a plan with a hard cap, or during a trial, `record` is [the gate](/guides/quota-enforcement-server-side-nextjs). Call it after the work and the refusal arrives once the report is already built and handed over. Recording first has its own cost. A report that then fails has still been counted, and `bb.usage` has no reversal. That trade-off, and how to pick per route, is the subject of [usage metering middleware in Express](/guides/usage-metering-middleware-express). **Over quota is a 402, not a 429.** The server answers an over-quota record with HTTP 402, `code: 'QUOTA_EXHAUSTED'`, the `quotaSlug` and `resetsAt`, and a message that starts `Quota limit reached for 'reports'`. A 400 means the request itself was wrong. What the SDK throws is a plain `Error` with the status attached as `status`, a field its type definitions leave out - hence the cast. On the usage routes only the quota refusal answers 402, so the status is enough to branch on. The error does not carry the server's `code` in `@buildbase/sdk` 0.0.90; it will from the next SDK release, and until then `code` is undefined. Passing 402 on is our choice, for our own response. A 429 from the usage API only ever comes from its rate limiter, which is a different problem with a [different fix](/guides/quota-429-not-exhausted). **Some members get a 403.** Recording usage needs the `workspace:usage:record` permission, and the built-in `viewer` role does not have it. It lacks usage view as well, so `getQuota` in the loader throws for a viewer too. Decide whether viewers should see this page at all before you ship it. ### 4. The form sends the key, and locks while it is in flight ```tsx // app/routes/w.$workspaceId.reports.tsx (continued) import { useFetcher } from 'react-router'; export default function Reports({ loaderData }: Route.ComponentProps) { const { quota, idempotencyKey } = loaderData; const fetcher = useFetcher(); const busy = fetcher.state !== 'idle'; return (

{quota.consumed} of {quota.included} reports used this period {quota.hasOverage && `, ${quota.overage} billed as overage`}

{fetcher.data && 'error' in fetcher.data && (

{fetcher.data.error}

)}
); } ``` Click once. The button locks, the report comes back, and the count goes up by one without you writing any code to refresh it: a successful action revalidates every loader on the page. That revalidation also runs step 2's loader again, which is where the new key comes from. The `disabled` is not decoration. Step 6 says why. ### 5. Why the key comes from the loader A loader key holds while a submission fails and rotates when one succeeds, which is the rule billing needs. The other two places a key could come from both bill wrong. **Made in the action.** Every attempt gets a new key, so nothing is ever deduplicated. A retry after a network blip bills twice. **Made in the component**, with `useState(() => crypto.randomUUID())` or a ref. Now the key never changes. The first report is billed. Every report after it replays the same key, and the server answers a replay with the current status and `used: 0`. The customer generates reports all month and is billed for one. Nothing errors. This is the version to be afraid of, because it looks fine until someone reads an invoice. **Made in the loader.** The key lives as long as one render of the page's data. React Router revalidates loaders after a successful submission, so a success rotates it and the next report is billed. It does not revalidate after a 4xx or 5xx by default, so a failed attempt keeps its key, and trying again sends the same one. A retry of a report that was already recorded comes back as a replay instead of a second charge. That is the whole trick. The framework already draws the line between "that worked, the next one is new" and "that failed, this is the same attempt", and the loader is where that line is visible. It is not perfect. The loader also runs on a reload, a navigation back and any other revalidation on the page, and each of those hands out a new key. So a customer whose connection dropped after the server recorded the report, and who then reloads and clicks again, sends a new key and is billed again. That is a new attempt as far as anything can tell, and we would rather name the gap than pretend the key closes it. The key is matched on workspace, quota and key, and remembered for as long as the usage log is kept: 730 days. Prefix it (`report:`) so a key from another form can never collide with this one. ### 6. Why the button still has to lock The key does not fully cover two submissions that arrive together, and a double-click produces exactly that. React Router's own concurrency docs say it plainly: cancelling a request in the browser "simply releases browser resources for that request; it can't 'catch up' and stop it from getting to the server." Click twice fast and both submissions reach your action, carrying the same key. Why doesn't the key catch the second one? The server checks for an existing key and then increments the counter as separate steps, so two concurrent requests with the same key can both pass the check. A retry that arrives after the first one finished is handled. Two at once are not, and we would rather say so than let the key look like a guarantee it is not. Locking the button while `fetcher.state !== 'idle'` removes the common case (the double-click) on the client. The key covers the retries that get past it. Neither is enough alone. ### What breaks, and how you can tell **Usage climbs when nobody generates anything.** A meter is in a loader, or in something a loader calls. Search every `loader` for `usage.record`. Prefetch and revalidation make this worse the more links point at the page. **Customers are billed for one report a month.** The key is held in component state or a ref and never changes. Log `usage.used` from the action: a replay returns `0`, a real record returns the quantity you sent. **One click, two charges.** Two submissions ran at the same time with the same key. Usually the button is not locked, or two fetchers on the page post to the same action. **The counter does not move after "This workspace has used every report".** That is the default working as intended. A 4xx from the action skips revalidation, so the loader does not re-run on refusal. The message comes from `fetcher.data`, not the loader. **`Too many usage recording requests. Please slow down.`** That is the 429 from the usage API's rate limiter: 60 requests a minute, counted per IP. Every request comes from your app server, so all your users share one budget. It has nothing to do with the quota. Read [the 429 that is not your quota](/guides/quota-429-not-exhausted) before raising any limit. **A viewer sees an error page instead of the counter.** `getQuota` needs usage view, which `viewer` lacks. Catch the 403 in the loader, or keep viewers off the route. ### Install ```bash npm i @buildbase/sdk ``` --- ## Usage metering middleware in Express: record before the handler or after the response (Hono and Fastify too) > Usage metering middleware for Express, Hono and Fastify: when to record before the handler, when to batch after the response, and the rate limit that decides it. - Source: https://www.buildbase.app/guides/usage-metering-middleware-express - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-28 - Updated: 2026-10-22 ### In short Metering middleware in Express can record before the handler or after the response. Recording first enforces the quota but counts requests that fail, one call each against a 60-a-minute limit. Recording after a 2xx and flushing with recordBatch bills only successes at volume, but cannot stop a request at the cap. Write the obvious metering middleware for an Express API, one `bb.usage.record()` per request, and you have set the throughput of every metered route you own to 60 requests a minute. That is not your quota. It is the rate limit on BuildBase's usage endpoints, counted per IP, and every usage call comes from your server's one address. All your users share it. It breaks first. So the decision is not where the middleware goes. It is **which of two jobs the call does on this route**: - **Mode one: record before the handler.** The record call is also the quota check, so it can refuse the request. At one call per request, it suits expensive routes that stay well under 60 a minute, like report generation. - **Mode two: record after the response, in batches.** Only successful responses are billed, and 100 of them go in one call. Nothing is refused per request, because by the time the batch runs, the responses are gone. You cannot have both on one call. Most APIs want both, on different routes. > **Before you start:** An Express, Hono or Fastify app with sign-in working through its setup guide > ([Express](/guides/buildbase-on-express), [Hono](/guides/buildbase-on-hono), > [Fastify](/guides/buildbase-on-fastify)), and the workspace resolved per > request as in [multi-tenant workspaces in > Express](/guides/multi-tenant-workspaces-express), which puts it on > `req.workspace`. In the console, a plan with the quotas you meter, here > `reports` and `api-calls`. ### What the middleware knows, and when Before the handler, middleware cannot know whether the work will succeed. After the response, it knows the status code and can no longer do anything about the request. Each mode gives up one half. Our [per-API-call guide](/guides/charge-per-api-call-nextjs) says metering in middleware is "wrong for anything expensive" because the middleware "does not know whether the work succeeded". For mode one that is exactly right. A request that fails after the record has still been counted, and `bb.usage` has no way to take it back. `quantity` has a minimum of 1, so there is no negative record either. ### Mode one: the record is the gate ```js // middleware/meter.js const crypto = require('node:crypto'); const buildbase = require('../config/buildbase'); /** Refuses the request when the quota is spent. One usage call per request. */ exports.meterFirst = ({ quota, quantity = 1 }) => async (req, res, next) => { const key = req.get('Idempotency-Key') ?? crypto.randomUUID(); if (key.length > 128) { return res.status(400).json({ message: 'Idempotency-Key is too long.' }); } try { await buildbase.forRequest(req).usage.record(req.workspace.id, { quotaSlug: quota, quantity, idempotencyKey: `${quota}:${key}`, source: 'api', }); return next(); } catch (err) { // On the usage routes only the quota refusal answers 402. if (err.status === 402) { return res .status(402) .json({ message: `This workspace has used its ${quota} allowance.` }); } if (err.status === 429) { // BuildBase's rate limit, not the customer's quota. res.set('Retry-After', '60'); return res .status(503) .json({ message: 'Usage metering is busy. Try again shortly.' }); } return next(err); } }; ``` ```js // routes/api.js router.post('/reports', meterFirst({ quota: 'reports' }), reports.create); ``` On a plan that is trialing, or a quota with overage switched off, `record` is an atomic check-and-increment, so two requests racing for the last unit cannot both get it. [Server-side quota enforcement](/guides/quota-enforcement-server-side-nextjs) walks through that, and why a separate "is there any left?" read is the wrong check. With overage on, `record` never refuses. It bills the overage and the request goes through. Three choices in there are ours: **402 for a spent quota, not 429.** A 429 tells a well-behaved client to back off and retry. Retrying a spent allowance fails until the period resets, so we answer with the status that says "this needs paying for". **503 when BuildBase rate-limits us.** It fails closed. Doing the work unmetered would give away exactly the expensive requests this mode exists for. And the status is ours to pick, because the upstream 429 is about our server's call volume, not the customer. **The client's `Idempotency-Key`, when it sends one.** A retried request with the same key is counted once: the server matches the key on workspace, quota and key, and a replay returns `used: 0`. Without a header we mint a UUID, which makes the record safe to retry inside this request but treats a client retry as a new request. A server-rendered form can hand out its key when the page renders instead, as [usage-based billing in React Router](/guides/usage-based-billing-react-router) does from the loader. The cap of 128 characters keeps the prefixed key under the 255 the API accepts. To check it, set the `reports` quota to 2 with overage off and send three requests. The third answers 402. ### Mode two: record after the response, in batches The middleware only notes what happened. A buffer sends it later. ```js // middleware/meter.js (continued) const usageBuffer = require('../lib/usage-buffer'); /** Bills 2xx responses only. Never refuses a request. */ exports.meterAfter = ({ quota, quantity = 1 }) => (req, res, next) => { const clientKey = req.get('Idempotency-Key'); // A long client key is not truncated: two truncated keys could collide. const key = clientKey && clientKey.length <= 128 ? clientKey : crypto.randomUUID(); const workspaceId = req.workspace.id; // Only a session that may record usage is worth keeping for the flush. const sessionId = req.workspace.permissions.includes( 'workspace:usage:record' ) ? req.session.buildbaseSessionId : null; res.on('finish', () => { if (res.statusCode < 200 || res.statusCode >= 300) return; usageBuffer.add(workspaceId, sessionId, { quotaSlug: quota, quantity, idempotencyKey: `${quota}:${key}`, source: 'api', }); }); next(); }; ``` Why only 2xx? A 4xx is the client's mistake and a 5xx is ours. Neither belongs on an invoice. Node's docs are precise about what `finish` means: the response "has been sent", which "does not imply that the client has received anything yet". For billing, sent is the right line. ```js // lib/usage-buffer.js // The one BuildBase call, set once at startup: the Express app passes the // SDK, a Fastify app its gateway. Nothing else in this file knows which. /** @typedef {(sessionId: string, workspaceId: string, items: Array<{ quotaSlug: string, quantity: number, idempotencyKey: string, source?: string }>) => Promise} Sender */ /** @type {Sender | null} */ let send = null; /** @param {Sender} fn */ exports.setSender = (fn) => { send = fn; }; const FLUSH_MS = 60_000; const BATCH_LIMIT = 100; // the most recordBatch takes in one call /** workspaceId -> items waiting to be sent */ const pending = new Map(); /** workspaceId -> the latest session from a member who may record */ const sessions = new Map(); /** Workspaces with a batch in flight, so two flushes never overlap. */ const flushing = new Set(); exports.add = (workspaceId, sessionId, item) => { if (sessionId) sessions.set(workspaceId, sessionId); const items = pending.get(workspaceId) ?? []; items.push(item); pending.set(workspaceId, items); if (items.length >= BATCH_LIMIT) flush(workspaceId); }; async function flush(workspaceId) { const sessionId = sessions.get(workspaceId); const queued = pending.get(workspaceId); if (!send || !sessionId || !queued?.length) return; // nothing to do yet if (flushing.has(workspaceId)) return; // the next tick picks the rest up flushing.add(workspaceId); const items = queued.slice(0, BATCH_LIMIT); pending.set(workspaceId, queued.slice(BATCH_LIMIT)); try { await send(sessionId, workspaceId, items); } catch (err) { if ( err.status === undefined && err.message === 'Failed to record batch usage' ) { // The server refused some items (usually a hard cap) and recorded the // rest. // A resend would be refused again, so drop the batch and say so. console.warn('usage partly refused', workspaceId, items.length); } else { // A 429, a 5xx or a network error: it may or may not have landed. // Put the items back; their keys make the resend safe either way. pending.set(workspaceId, [...items, ...(pending.get(workspaceId) ?? [])]); console.error('usage flush failed', workspaceId, err.message); } } finally { flushing.delete(workspaceId); } } exports.flushAll = () => Promise.all([...pending.keys()].map(flush)); /** For shutdown: keep flushing until nothing is left, or the deadline passes. */ exports.drain = async (deadlineMs = 10_000) => { const stop = Date.now() + deadlineMs; while (Date.now() < stop) { const left = [...pending.entries()].some( ([id, items]) => items.length && sessions.has(id) ); if (!left && flushing.size === 0) return; await exports.flushAll(); await new Promise((r) => setTimeout(r, 100)); } }; setInterval(exports.flushAll, FLUSH_MS).unref(); ``` In the Express app, the sender is the SDK. `forSession` is one line added to `config/buildbase.js` from the setup guide, next to `forRequest`: ```js // config/buildbase.js (next to forRequest) exports.forSession = (sessionId) => buildbase().withSession(sessionId); // app.js, once at startup const buildbase = require('./config/buildbase'); const usageBuffer = require('./lib/usage-buffer'); usageBuffer.setSender((sessionId, workspaceId, items) => buildbase.forSession(sessionId).usage.recordBatch(workspaceId, { items }) ); ``` ```js // routes/api.js router.get('/search', meterAfter({ quota: 'api-calls' }), search.run); ``` Send a few searches and nothing reaches BuildBase for up to a minute. Then one `recordBatch` lands with all of them, and `api-calls` in the console moves by the number of 2xx responses, not the number of requests. Which session sends the batch? The requests are over, so there is no current user, and the server SDK takes no API key: every call it makes runs as some user's session. The buffer keeps, per workspace, the most recent session from a member whose permissions include `workspace:usage:record`, which the [workspace middleware](/guides/multi-tenant-workspaces-express) already resolved. A viewer's session would only earn a 403, so it is never kept. This is the weakest part of the design, and we would rather say so. A kept session can be signed out, or its member demoted, before the flush. That shows up as a rejected batch while the items wait for the next request from a member who may record. Usage from a workspace whose only active users are viewers waits until one comes along. An API token can be exchanged for a session, but that session's user still has to be a member of the workspace who may record, so it does not remove the problem for a multi-tenant API. #### The arithmetic of the flush interval A batch carries one workspace and counts once against the 60-a-minute limit. Flush every N seconds, with W workspaces active, and you make W × 60 / N calls a minute. Keep that at or under 60 and the rule falls out: **The flush interval, in seconds, has to be at least the number of workspaces active during it.** At the 60-second interval above, that holds for up to 60 busy workspaces at a time. And the budget is shared: every mode-one `record` spends from the same 60, and so does every other process behind the same outgoing IP. Two API servers behind one NAT halve it. Past that, lengthen the interval and accept that usage shows up later. A workspace that fills 100 items early flushes early and spends an extra call, so the busiest customers cost the most of the budget. #### What the batch gives up **The cap.** Every item goes through the same check as a single `record`, so on a hard-capped quota the items past the limit are refused, after the customer already has the response. That is overshoot, bounded by one flush interval of traffic. If a route has to stop dead at the cap, it belongs in mode one. **Which items were refused.** Over HTTP, the batch answers 200 with per-item `success: false` entries in `results` ([one request is not one unit](/guides/quota-429-not-exhausted) walks through them). Through `@buildbase/sdk` 0.0.73 you never see them: a batch with any refused item throws `Failed to record batch usage`, with no `status` and no `results`. That is why the buffer tells that error apart from the rest. The accepted items are already recorded and the refused ones will be refused again, so re-queueing the batch would resend the same 100 items at every flush while newer usage waits behind them. **Anything in memory at a crash.** The buffer lives in the process. A deploy that kills it without draining loses up to a minute of usage, so wire `drain()` to shutdown. It waits for a batch already in flight and keeps flushing past the first 100 items, up to a deadline: ```js process.on('SIGTERM', async () => { await usageBuffer.drain(10_000); process.exit(0); }); ``` A crash still loses what was buffered. Notice which way that fails: toward billing too little, never twice. A resend after a failed flush reuses every item's key, so an item the server did count the first time comes back as a replay rather than a second charge. (The server checks and increments in separate steps, so two flushes of the same item at the same instant could both count. The `flushing` set keeps one batch per workspace in flight, so one process never does that.) ### On Hono, the real status arrives after `await next()` Code after `await next()` runs on the way back out, with the response already built. Hono's docs say `next()` never throws: an error goes to `app.onError()`, or becomes a 500, before it comes back up, so `c.res.status` is the real status either way. The Hono setup guide keeps `forSession` private inside its gateway. Expose the usage calls with one more entry on the object `buildbaseFor()` returns: ```ts // src/buildbase.ts, inside buildbaseFor()'s return usage: (sessionId: string) => forSession(sessionId).usage, ``` ```ts // src/meter.ts import { getSignedCookie } from 'hono/cookie'; import { createMiddleware } from 'hono/factory'; import { buildbaseFor } from './buildbase'; import { config } from './config'; // the setup guide's env() helper, moved to its own file export const meterAfter = (quotaSlug: string) => // Typed, so c.var.workspace is checked here. Mount it after requireWorkspace. createMiddleware<{ Variables: { workspace: { id: string } } }>( async (c, next) => { await next(); if (c.res.status < 200 || c.res.status >= 300) return; const workspace = c.get('workspace'); if (!workspace) return; // mounted without requireWorkspace in front const sessionId = await getSignedCookie( c, config(c).COOKIE_SECRET!, 'bb_session' ); if (!sessionId) return; const recorded = buildbaseFor(config(c)) .usage(sessionId) .record(workspace.id, { quotaSlug, quantity: 1, idempotencyKey: `${quotaSlug}:${crypto.randomUUID()}`, }) .catch((err) => console.error('usage not recorded', err.message)); try { c.executionCtx.waitUntil(recorded); // Workers: keep the isolate alive for it } catch { // Node and Bun have no ExecutionContext; the promise runs on its own. } } ); ``` The `try` is not decoration. On Node and Bun, reading `c.executionCtx` throws `This context has no ExecutionContext`, and with the response already gone, the only sign would be an error in your logs on every metered request. That is still one call per request, so the 60-a-minute arithmetic applies. On Node and Bun, a Hono app can use the Express buffer module unchanged, with its sender set, because it is plain module state and a timer. Workers should not: Cloudflare says not to rely on global state across requests, since an isolate can be evicted at any time, and there is no timer that outlives a request to flush it. Batch there through something that persists, such as a Cloudflare Queue whose consumer calls `recordBatch`. ### On Fastify, `onResponse` is mode two The `onResponse` hook runs when "a response has been sent, so you will not be able to send more data to the client", which is exactly mode two. Mode one goes in a `preHandler` hook, the same shape as the Express `meterFirst`, answering with `reply.code(402)`. The Fastify setup guide's `BuildBaseGateway` has no usage method, so add one, and add it to the fake your tests pass in: ```ts // src/plugins/app/buildbase.ts export interface BuildBaseGateway { // ...the six methods from the setup guide recordUsageBatch( sessionId: string, workspaceId: string, items: Array<{ quotaSlug: string; quantity: number; idempotencyKey: string; }> ): Promise; } ``` The real implementation awaits `client.withSession(sessionId).usage.recordBatch(workspaceId, { items })` and returns nothing. The test fake pushes the items into an array, which gives you a test that a 404 is never billed. ```ts // src/plugins/app/meter.ts import { randomUUID } from 'node:crypto'; import fp from 'fastify-plugin'; import * as usageBuffer from '../../lib/usage-buffer'; export default fp(async (fastify) => { usageBuffer.setSender((sessionId, workspaceId, items) => fastify.buildbase.recordUsageBatch(sessionId, workspaceId, items) ); fastify.addHook('onResponse', async (request, reply) => { const quotaSlug = request.routeOptions.config.meter; if (!quotaSlug) return; if (reply.statusCode < 200 || reply.statusCode >= 300) return; const workspace = request.workspace; if (!workspace) return; // not a workspace route const mayRecord = workspace.permissions.includes('workspace:usage:record'); usageBuffer.add( workspace.id, mayRecord ? request.session.buildbaseSessionId : null, { quotaSlug, quantity: 1, idempotencyKey: `${quotaSlug}:${randomUUID()}` } ); }); }); ``` A route opts in with `config: { meter: 'api-calls' }` (declare `meter` on Fastify's `FastifyContextConfig` so the read type-checks). The buffer is the same module as the Express one, with the gateway as its sender, so the tests' fake gateway sees every batch. It is plain JavaScript: in a TypeScript or ESM Fastify project, port it to `lib/usage-buffer.ts`, which is a line-for-line change plus types. Do not use `request.id` as the key. Fastify's default is "value of 'request-id' header if provided or monotonically increasing integers" (and v5 ignores that header unless `requestIdHeader` is set), so two processes, or one process after a restart, hand out the same IDs. A reused key is a replay, and a replay is recorded as `used: 0`: real usage, silently not billed. ### What breaks, and how you can tell | You see | Cause, and the fix | | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Too many usage recording requests. Please slow down.` in your logs, or your own 503s from mode one | The metered routes together make over 60 usage calls a minute. Move the busiest route to mode two, or lengthen the flush interval. [The 429 that is not your quota](/guides/quota-429-not-exhausted) explains the limiter. | | Console usage lags traffic by a minute | Mode two working. The flush interval is the lag. | | Usage drops after every deploy | The buffer died with the process. Check that `SIGTERM` reaches Node (a shell wrapper in the container's start command swallows it) and that `drain()` runs. | | Usage stops moving for one workspace, and "usage partly refused" is in the log | Its quota is hard-capped and full, or the workspace has no active subscription, or the quota slug is not on its plan. The batch was refused in part; the accepted items were recorded and the rest dropped. Raise the cap or turn overage on. | | A flush fails with 403 over and over | The kept member was signed out or demoted since. The next request from a member who may record replaces the session. A workspace that only ever sees viewers never lands its usage, so keep metered routes off roles that cannot be billed. | | Customers billed for requests that failed | The route is on mode one, which records before the work. That is the trade. If failures are common there, move it to mode two. | | Metered usage far below traffic, and nothing errors | Keys are repeating. Look for `request.id`, a counter or a hard-coded key. | ### Install ```bash npm i @buildbase/sdk ``` --- ## BuildBase on Astro: one middleware for sign-in, roles and API tokens > Astro middleware authentication with roles: one onRequest gate where admins and editors write, viewers read, strangers bounce and machines use a token. - Source: https://www.buildbase.app/guides/buildbase-on-astro - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-10-19 ### In short Put Astro authentication in one src/middleware.ts. It reads the BuildBase session, looks up the person's role in one workspace, and hands both to a pure decide() function you can unit-test. Admins and editors write, viewers only read, everyone else is sent away, and /api still accepts a token for machines. Signing in is the easy half of Astro authentication. The tutorials we read got you to "we know who this is" and stopped there, one of them at a boolean: `locals.isAdmin`. Whether your admin leaks depends on the next question: **may this request do this?** Here is what happens when nobody asks it. Cloudflare's SaaS Admin Template, an Astro dashboard for customers and subscriptions, ships with `/admin` open to anyone who has the URL. Its API is guarded by a single `API_TOKEN`, and the admin's own Create dialogs work by handing that token to the browser: ```astro ``` A `client:only` component's props are serialized into the page. So the one secret protecting the API is in the HTML of every admin page. We fixed that template with one middleware and one pure function. The [example](https://github.com/buildbase-app/examples/tree/main/astro-saas-admin) runs on Cloudflare Workers with D1. Admins and editors write. Viewers only read, strangers are sent away, and scripts keep using the token - on `/api` only. > **Before you start:** An Astro app with server output (the example uses the Cloudflare adapter), a > BuildBase organization, and an auth client created in the console under **User > Management → Authentication**, with its client ID and secret. Register > `http://localhost:4321/auth/callback` on the client. > **Tip:** **Start from the working example.** > [`astro-saas-admin`](https://github.com/buildbase-app/examples/tree/main/astro-saas-admin) > in the examples repo runs everything on this page in the SaaS Admin Template. > [Watch it > working](https://github.com/buildbase-app/examples/tree/main/astro-saas-admin#see-it-working), > or copy it with `npx degit buildbase-app/examples/astro-saas-admin my-app`. ### 1. Write the rule first, as a pure function ```ts // src/lib/buildbase.ts export type Role = 'admin' | 'editor' | 'viewer'; export const canWrite = (role: Role | null) => role === 'admin' || role === 'editor'; export function decide({ pathname, method, apiToken, member, }: { pathname: string; method: string; apiToken: boolean; // the request carried a valid API_TOKEN member: { role: Role | null } | null; // null: not signed in }) { const isApi = pathname.startsWith('/api/'); const isAdmin = pathname === '/admin' || pathname.startsWith('/admin/'); if (!isApi && !isAdmin) return { allow: true }; if (isApi && apiToken) return { allow: true }; // machines, as before if (!member) return { allow: false, status: 401, reason: 'sign-in' }; if (!member.role) return { allow: false, status: 403, reason: 'not-a-member' }; if (isApi && method !== 'GET' && !canWrite(member.role)) { return { allow: false, status: 403, reason: 'read-only' }; } return { allow: true }; } ``` Why pure? Because this is the part you most want tests on, and a function with no I/O runs under `node --test` with no server and no mocks. The example has seven: the landing page stays open, signed-out visitors go to sign-in, strangers are refused, admins and editors can write, viewers read but cannot write, the token works on `/api` and only there, and `/administrator` is not mistaken for `/admin`. The roles are BuildBase's [workspace roles](/guides/multi-tenant-workspaces-in-an-afternoon): admin, editor and viewer. The admin belongs to one BuildBase workspace, named by `ADMIN_WORKSPACE_ID`, and your place in that workspace is your place in the admin. ### 2. The middleware gathers the inputs and applies the rule ```ts // src/middleware.ts import { defineMiddleware } from 'astro:middleware'; export const onRequest = defineMiddleware(async (context, next) => { const env = context.locals.runtime.env; const { pathname } = context.url; const sessionId = context.cookies.get('bb_session')?.value; context.locals.member = sessionId ? await buildbase(env).member(sessionId) : null; if (sessionId && !context.locals.member) context.cookies.delete('bb_session', { path: '/' }); const apiToken = pathname.startsWith('/api/') && (await validateApiToken(context.request, env.API_TOKEN)); const verdict = decide({ pathname, method: context.request.method, apiToken, member: context.locals.member, }); if (verdict.allow) return next(); if (pathname.startsWith('/api/')) { return Response.json( { message: verdict.reason }, { status: verdict.status } ); } return verdict.reason === 'sign-in' ? context.redirect(`/auth/sign-in?next=${encodeURIComponent(pathname)}`) : context.redirect('/access'); }); ``` `member()` makes the BuildBase calls: the profile and the workspace list together, as the [Hono guide](/guides/buildbase-on-hono) does on Workers, then the members of the admin workspace, from which it reads the role. A session BuildBase no longer knows comes back as `null`, and the cookie is cleared. Pages read `Astro.locals.member` for the header's role badge, and hide the Create buttons from viewers: ```astro --- const writable = canWrite(Astro.locals.member?.role ?? null); --- {writable && } ``` No `apiToken` prop any more. The dialogs call `/api/customers` with the session cookie, and the middleware checks it like any other request. Hiding the button is courtesy; the 403 from `decide()` is the rule. ### 3. Sign-in: three small endpoints `/auth/sign-in` stores a random `state` (and where to go next, same-site paths only) in a short-lived cookie, then redirects to the URL from `AuthApi.requestAuth()`. `/auth/callback` checks the `state`, exchanges the code for a BuildBase session with the client secret, and sets `bb_session` as an httpOnly, `SameSite=Lax` cookie. `/auth/sign-out` is a POST, and it ends the BuildBase session too. The cookie holds nothing but the session ID. The middleware checks that ID with BuildBase on every request, so a made-up value is refused like any session BuildBase does not know. Open `/admin` signed out and you go through the hosted page (whichever sign-in methods your org has on) and come back to `/admin`, with your role in the header. ### 4. The first run: pick the workspace With `ADMIN_WORKSPACE_ID` unset, a signed-in visitor lands on `/access`, which lists their BuildBase workspaces and IDs. By default BuildBase creates one for each person on first sign-in, and they are its admin. Put that ID in `ADMIN_WORKSPACE_ID`, restart, and invite teammates into that workspace as editors or viewers. If one of them [cannot see the workspace](/guides/invited-member-cannot-see-workspace) after accepting, the invite is stuck in one of a few states. Because the middleware reads the role on every request, [a role change or a removal takes effect on the teammate's next click](/blog/why-permissions-refresh-hourly). > **Key takeaway:** In Astro, authorization is one middleware and one pure function. The > middleware gathers who and what; `decide()` says yes or no, and it is the part > with the tests. ### CSRF: what Astro covers, and what it does not `security.checkOrigin` is on by default since Astro 4.9. It refuses cross-origin POST, PUT, PATCH and DELETE requests sent with a form content type or none at all, so a cross-site sign-out, or a hidden form posting to your admin, gets a 403. We checked: a sign-out posted with a foreign `Origin` header was refused. It does not look at JSON requests. Those are covered differently: another site cannot send `Content-Type: application/json` cross-origin without a CORS preflight, which your API does not answer, and the `SameSite=Lax` session cookie is not sent on cross-site subrequests anyway. ### Where the upstream template is simpler Upstream needs no outside service and makes no network calls to decide access. This version asks BuildBase up to three times on each request that carries a session cookie, in two round trips, and needs `ADMIN_WORKSPACE_ID` set up once. For a busy admin, cache `member()` for a minute (in KV, say) and accept that a removed teammate keeps access for that minute. And if you only want sign-in with a fixed list of admins, [Clerk](/compare/clerk-vs-buildbase)'s Astro integration protects routes from its own middleware with less code than this. ### What breaks, and how you can tell **Everyone lands on `/access` with "not a member".** `ADMIN_WORKSPACE_ID` names a workspace they are not in. Check the ID the `/access` page listed when the variable was unset. **Viewers get 403 on a button that should work.** It is a write. `decide()` allows viewers `GET` only, by design; make them editors. **Scripts get 401 on `/api`.** They are not sending the token, or not on `/api`. The token is accepted as `Authorization: Bearer`, `Authorization: Token` or `x-api-token`, and never on `/admin` pages. **Scripts get 403 on a POST, before the token is checked.** Astro's origin check treats a request with no `Origin` header as cross-site when it is sent as a form or with no content type. Send `Content-Type: application/json`. **The hosted page refuses to send you back.** The callback URL must match one registered on the auth client exactly, path included; the port must match too, except on localhost, where it is ignored. A wildcard can stand in for one leftmost subdomain on a domain you own, but not for a public suffix like `*.workers.dev`. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/astro-saas-admin my-app`. ```bash npm i @buildbase/sdk ``` --- ## BuildBase on Express: add authentication to an existing app and keep req.user > Add authentication to an existing Express app: hosted sign-in, a callback route, and express-session, with req.user and every protected route left untouched. - Source: https://www.buildbase.app/guides/buildbase-on-express - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-10-19 ### In short To add authentication to an existing Express app with BuildBase, have POST /login redirect to hosted sign-in, then swap the returned code for a session on a callback route using the client secret. Keep the session ID in express-session and call req.logIn(), so req.user and every protected route keep working unchanged. Passport was never the problem in your Express app. The problem is everything built around it: the local strategy, bcrypt, reset tokens, verification emails, the passkey ceremony, the TOTP setup page. [That is where the lines are](/blog/cost-of-building-auth-yourself), and where the security bugs hide. So keep Passport and delete the rest. On [hackathon-starter](https://github.com/buildbase-app/examples/tree/main/hackathon-starter), the 35k-star Express template, `controllers/user.js` and `controllers/webauthn.js` were 1,384 lines between them. They are now one `user.js` of about 240 lines. Every route that reads `req.user` is unchanged, and all 133 of upstream's remaining tests pass. > **Before you start:** An Express app using `express-session` (with or without Passport), a BuildBase > organization, and an auth client created in the console under **User > Management → Authentication**, with its client ID and secret. Register > `http://localhost:8080/auth/buildbase/callback` (hackathon-starter's port) on > the client as a redirect URL. > **Tip:** **Start from the working example.** > [`hackathon-starter`](https://github.com/buildbase-app/examples/tree/main/hackathon-starter) > in the examples repo runs everything on this page in Hackathon Starter. [Watch > it > working](https://github.com/buildbase-app/examples/tree/main/hackathon-starter#see-it-working), > or copy it with `npx degit buildbase-app/examples/hackathon-starter my-app`. ### 1. Install the SDK and add three variables ```bash npm i @buildbase/sdk ``` ```bash # .env BUILDBASE_ORG_ID=demo-org-id BUILDBASE_CLIENT_ID=demo-client-id BUILDBASE_CLIENT_SECRET=demo-client-secret BASE_URL=http://localhost:8080 # BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` ### 2. One module for everything BuildBase ```js // config/buildbase.js const crypto = require('node:crypto'); const { AuthApi, BuildBase } = require('@buildbase/sdk'); const SERVER_URL = process.env.BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app'; const authApi = new AuthApi({ serverUrl: SERVER_URL, version: 'v1' }); const callbackUrl = () => `${process.env.BASE_URL}/auth/buildbase/callback`; // Made on first use: BuildBase() refuses to start without an org ID. let client; const buildbase = () => { client ??= BuildBase({ serverUrl: SERVER_URL, orgId: process.env.BUILDBASE_ORG_ID, }); return client; }; /** The signed-in user's BuildBase session, bound for this request. */ exports.forRequest = (req) => buildbase().withSession(req.session?.buildbaseSessionId); /** Remember a random state, then send the visitor to the hosted page. */ exports.startSignIn = async (req, res) => { const state = crypto.randomBytes(16).toString('hex'); req.session.buildbaseState = state; const { redirectUrl } = await authApi.requestAuth({ orgId: process.env.BUILDBASE_ORG_ID, clientId: process.env.BUILDBASE_CLIENT_ID, redirect: { success: callbackUrl(), error: callbackUrl() }, state, }); res.redirect(redirectUrl); }; /** Swap the one-time code for a session ID. Needs the client secret. */ exports.exchangeCode = async (code) => { const res = await fetch(`${SERVER_URL}/api/v1/auth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, orgId: process.env.BUILDBASE_ORG_ID, clientId: process.env.BUILDBASE_CLIENT_ID, clientSecret: process.env.BUILDBASE_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`BuildBase token exchange failed (${res.status})`); return (await res.json()).data.sessionId; }; /** Ends the BuildBase session itself, not just this app's. */ exports.revokeSession = async (sessionId) => { if (sessionId) await authApi.logout(sessionId).catch(() => {}); }; ``` Then point your login form at it. `POST /login` becomes one line, `buildbase.startSignIn(req, res)`, and the login page becomes a single button. Click it and you land on BuildBase's hosted page, offering whichever sign-in methods your org has switched on. ### 3. The callback: state, code, user, `req.logIn()` ```js // controllers/user.js exports.getBuildbaseCallback = async (req, res, next) => { const { code, state } = req.query; const expectedState = req.session.buildbaseState; req.session.buildbaseState = undefined; if (typeof code !== 'string' || !state || state !== expectedState) { return res.redirect('/login'); } try { req.session.buildbaseSessionId = await buildbase.exchangeCode(code); const profile = await buildbase.forRequest(req).users.getProfile(); const rawId = profile.id || profile._id; // Never String() a missing ID: every such user would share one account. if (!rawId || !profile.email) throw new Error('BuildBase returned a profile without an ID or email.'); const buildbaseId = String(rawId); let user = await User.findOne({ buildbase: { $eq: buildbaseId } }); if (!user) { // An account made before BuildBase, with the same email, is adopted. user = (await User.findOne({ email: { $eq: profile.email } })) || new User({ email: profile.email }); user.buildbase = buildbaseId; } await user.save(); // passport.session() still carries the user between requests. req.logIn(user, (err) => err ? next(err) : res.redirect(req.session.returnTo || '/') ); } catch (err) { next(err); } }; ``` ```js // app.js app.get( '/auth/buildbase/callback', loginLimiter, userController.getBuildbaseCallback ); ``` The user model gains one field: `buildbase: { type: String, unique: true, sparse: true }`. And the `$eq` in both queries is not decoration. It stops a crafted query string from becoming a Mongo operator. That `req.logIn(user)` is the whole trick. It is the same call your local strategy ended with, so `passport.session()` keeps putting the user on `req.user`, and `isAuthenticated` middleware, templates and every route that reads `req.user` never find out the sign-in moved. Require the `state`, do not just compare it when present. A check written as `state && state !== expected` waves through any callback that omits it. We shipped exactly that in this example and fixed it while writing this page. To check it: open a protected page signed out, sign in on the hosted page, and you should land back on that page with your name in the header. ### 4. Call BuildBase from any route, as the user ```js // controllers/buildbase.js const crypto = require('node:crypto'); exports.postCredit = async (req, res, next) => { try { const bb = buildbase.forRequest(req); const [workspace] = await bb.workspace.list(); const result = await bb.credits.consume(workspace._id, { amount: 1, description: 'API example', // Minted when the form was rendered. Check the type: a crafted body can send an object. idempotencyKey: typeof req.body.key === 'string' ? req.body.key : crypto.randomUUID(), }); req.flash('success', { msg: `Spent 1 credit. ${result.balanceAfter} left.`, }); res.redirect('/api/buildbase'); } catch (err) { if (err.code === 'INSUFFICIENT_CREDITS') { req.flash('errors', { msg: 'Out of credits.' }); return res.redirect('/api/buildbase'); } next(err); } }; ``` `forRequest(req)` is the Express answer to "how does the SDK know who is calling?". There is no async request context to lean on, so each route binds the session it already has, the same way [a React Router loader does](/guides/buildbase-on-react-router) and [a Fastify plugin does](/guides/buildbase-on-fastify). The idempotency key rides in the form, so a double-submitted POST spends one credit, not two. Workspaces, plans and credits all follow that one pattern. The [credits wallet guide](/guides/credits-wallet-nextjs) and [charging per credit](/guides/charge-per-credit-nextjs) are written for Next.js, but from the SDK call down they are the same code in Express. ### 5. Logout ends both sessions ```js exports.logout = async (req, res) => { await buildbase.revokeSession(req.session?.buildbaseSessionId); req.logout(() => req.session.destroy(() => res.redirect('/'))); }; ``` Skip the revoke and you are signed out of your app, but the BuildBase session stays alive: anything else holding it keeps working until it expires. ### And what Passport is still for Passport stays, but its job shrinks. Hackathon-starter's API examples call GitHub, Google, Facebook and others on the user's behalf, and that needs the provider's OAuth token. So the provider strategies stay, for **linking**: a signed-in user connects GitHub from their account page. Signing in with GitHub happens on the hosted page instead, and a strategy callback that finds no signed-in user now answers "sign in first, then link it". > **Key takeaway:** In Express, BuildBase proves who someone is, then `req.logIn()` hands them to > Passport exactly as your old login did. Nothing downstream of `req.user` > changes. ### Where Auth0 is less work If you are starting fresh, [Auth0](/compare/auth0-vs-buildbase)'s `express-openid-connect` middleware is shorter: its `auth()` mounts `/login`, `/logout` and `/callback` for you. Here you write those three yourself, about 80 lines of code across `config/buildbase.js` and the callback. The trade is control. Because the callback is yours, it is also where your existing users get adopted by email, and where BuildBase's session sits next to your own for the workspace and credit calls that follow. ### What breaks, and how you can tell **Every sign-in lands back on `/login`.** The state is not surviving the round trip. express-session's cookie must be `SameSite=Lax` or unset, not `Strict`. The hosted page sends the visitor back with a top-level navigation from another site, and browsers drop a strict cookie on that. Behind a proxy with a `secure` cookie, also check `app.set('trust proxy', 1)`. **`forRequest(req)` calls fail with 401 after a restart.** Your session store is in memory, so the BuildBase session ID went with it. Use a persistent store (the example uses MongoDB) or expect everyone to sign in again. **Credit spends start failing with 429 under load.** Credit consumption is limited to 30 requests a minute per IP, and the IP it sees is your server's, not your user's. A busy app has to spend in batches rather than per click. **The hosted page refuses to send you back.** The callback URL must match a registered one exactly, path included; the port must match too, except on localhost, where it is ignored. A wildcard can stand in for one leftmost subdomain on a domain you own (`https://*.app.example.com/...`), but not for a public suffix, so `*.vercel.app` is refused: register each preview domain you use. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/hackathon-starter my-app`. ```bash npm i @buildbase/sdk ``` --- ## BuildBase on Fastify: authentication as a decorator plugin, tests included > Fastify authentication as a decorator plugin: hosted sign-in, @fastify/session, unchanged role checks, a fake for tests, and credits metered per request. - Source: https://www.buildbase.app/guides/buildbase-on-fastify - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-10-19 ### In short To add authentication to a Fastify app with BuildBase, register a plugin that decorates fastify.buildbase, sign in through the hosted page, and store the user in @fastify/session in the shape your role checks already read. Tests pass a fake through the plugin options, and paid routes spend credits and answer 402. The Fastify authentication guides we read (the plugin READMEs, Auth0's quickstart, the tutorials that rank) all stop at the same line: the user is logged in. None of them shows the part that decides whether the integration survives a year: can `npm test` still run with the network off? In Fastify the answer is built into the framework. Authentication is a decorator, decorators come from plugins, and plugins take options. So put every call to your identity provider behind `fastify.buildbase`, and let the test helper hand the app a fake. We did that to [the official Fastify demo](https://github.com/buildbase-app/examples/tree/main/fastify-demo), the Fastify team's own reference app. Its role checks did not change. Its 57 tests run on MySQL, against the fake. Then we made one route cost money. Once you know who is calling, the next question is what they pay. > **Before you start:** A Fastify app with `@fastify/session`, a BuildBase organization, and an auth > client created in the console under **User Management → Authentication**, with > its client ID and secret. Register > `http://localhost:3000/api/auth/buildbase/callback` on the client as a > redirect URL. > **Tip:** **Start from the working example.** > [`fastify-demo`](https://github.com/buildbase-app/examples/tree/main/fastify-demo) > in the examples repo runs everything on this page in the official Fastify > demo. [Watch it > working](https://github.com/buildbase-app/examples/tree/main/fastify-demo#see-it-working), > or copy it with `npx degit buildbase-app/examples/fastify-demo my-app`. ### 1. A plugin that owns every BuildBase call ```ts // src/plugins/app/buildbase.ts import { ApiVersion, AuthApi, BuildBase } from '@buildbase/sdk'; import { FastifyInstance, FastifyPluginOptions } from 'fastify'; import fp from 'fastify-plugin'; export interface BuildBaseGateway { signInUrl(state: string): Promise; exchangeCode(code: string): Promise; profile( sessionId: string ): Promise<{ id: string; email: string; name?: string }>; account(sessionId: string): Promise<{ profile: object; workspace: object | null; credits: number | null; }>; spend( sessionId: string, amount: number, description: string, idempotencyKey: string ): Promise<{ balanceAfter: number }>; revoke(sessionId: string): Promise; } declare module 'fastify' { interface FastifyInstance { buildbase: BuildBaseGateway; } } export default fp( async (fastify: FastifyInstance, opts: FastifyPluginOptions) => { // Tests pass a fake here; everything else gets the real thing. fastify.decorate('buildbase', opts.buildbase ?? createGateway(fastify)); }, { name: 'buildbase' } ); ``` `createGateway` is the real implementation: `AuthApi.requestAuth()` for the hosted URL, a `fetch` to `/api/v1/auth/token` with the client secret for the code exchange, and `BuildBase({ serverUrl, orgId }).withSession(sessionId)` for everything after. Fastify core has no async request context (`@fastify/request-context` adds one), so each call binds the session it is given, the same way [Express binds it per request](/guides/buildbase-on-express) and [a NestJS guard does](/guides/buildbase-on-nestjs). The client is made on first use, which lets the API boot and serve its docs before the BuildBase variables are filled in. The [example's plugin](https://github.com/buildbase-app/examples/blob/main/fastify-demo/src/plugins/app/buildbase.ts) is about 140 lines, most of them `createGateway`. Why an interface instead of calling the SDK in routes? Because the interface is the seam. Routes depend on six methods, not on a network. ### 2. Sign-in: two routes and a session shape you already have ```ts // src/routes/api/auth/index.ts fastify.get('/buildbase/sign-in', async (request, reply) => { const state = randomBytes(16).toString('hex'); request.session.buildbaseState = state; await request.session.save(); return reply.redirect(await fastify.buildbase.signInUrl(state)); }); fastify.get('/buildbase/callback', async (request, reply) => { const { code, state } = request.query; const expected = request.session.buildbaseState; request.session.buildbaseState = undefined; if (!code || !sameState(state, expected)) { return reply.unauthorized('Sign-in could not be verified.'); } const sessionId = await fastify.buildbase.exchangeCode(code); const profile = await fastify.buildbase.profile(sessionId); await fastify.knex.transaction(async (trx) => { const user = await usersRepository.upsertFromBuildBase(profile, trx); const roles = await usersRepository.findUserRolesByEmail(user.email, trx); request.session.user = { id: user.id, email: user.email, username: user.username, roles: roles.map((role) => role.name), }; }); request.session.buildbaseSessionId = sessionId; await request.session.save(); return reply.redirect('/api'); }); ``` `sameState` compares with `timingSafeEqual` and fails when either side is missing. The state is cleared before the check, so a callback URL works once. Look at what `request.session.user` holds: `{ id, email, username, roles }`. The demo's old password login put exactly that there. So its `isModerator` and `isAdmin` checks, and every route behind them, work unchanged. `upsertFromBuildBase` finds the user by `buildbase_id`, adopts an existing user with the same email, or creates one with the `basic` role. One migration adds the column and drops the password: ```sql ALTER TABLE users ADD COLUMN buildbase_id VARCHAR(64) NULL UNIQUE AFTER username, DROP COLUMN password; ``` Open `/api/auth/buildbase/sign-in` in a browser, sign in on the hosted page (whichever sign-in methods your org has on), and you land on `/api` greeted by name. The route-level auth hook lets `/api/auth/buildbase/*` through and still refuses everything else without a session. ### 3. The payoff: tests with a fake BuildBase ```ts // test/helper.ts export function fakeBuildBase() { const credits = new Map(); const spent = new Set(); const balance = (email: string) => credits.get(email) ?? 100; const emailOf = (sessionId: string) => sessionId.replace(/^session:/, ''); return { credits, signInUrl: async (state: string) => `https://auth.buildbase.test/sign-in?state=${state}`, exchangeCode: async (code: string) => `session:${code}`, // the code is the email profile: async (sessionId: string) => { const email = emailOf(sessionId); return { id: `bb_${email}`, email, name: email.split('@')[0] }; }, spend: async ( sessionId: string, amount: number, _d: string, key: string ) => { const email = emailOf(sessionId); if (spent.has(key)) return { balanceAfter: balance(email) }; if (balance(email) < amount) { throw Object.assign(new Error('Insufficient credits'), { code: 'INSUFFICIENT_CREDITS', }); } spent.add(key); credits.set(email, balance(email) - amount); return { balanceAfter: balance(email) }; }, revoke: async () => {}, }; } export function config() { return { skipOverride: true, buildbase: fakeBuildBase() }; } ``` The helper's `login(email)` then drives the **real** routes: it calls `/api/auth/buildbase/sign-in`, reads the `state` from the redirect, and calls the callback with the email as the code. So the state check, the upsert, the role lookup and the session all run in every test that signs in. Only the network is gone. The example's fake also backs the account screen. Its tests go further than the happy path: a forged `state`, a callback with no sign-in in progress, a seeded user adopted by email, a first-time user getting `basic`, and logout revoking the BuildBase session. > **Key takeaway:** In Fastify, BuildBase is a decorator. Routes call `fastify.buildbase`, tests > swap in a fake through the plugin options, and nothing that reads > `request.session.user` knows sign-in moved. ### 4. A route that costs a credit ```ts // src/routes/api/tasks/index.ts async function (request, reply) { const key = request.headers['idempotency-key']; try { await fastify.buildbase.spend( request.session.buildbaseSessionId ?? '', 1, 'Task created', typeof key === 'string' ? key : randomUUID(), ); } catch (err) { if ((err as { code?: string }).code === 'INSUFFICIENT_CREDITS') { reply.code(402); return { message: 'Out of credits.' }; } throw err; } // ...then create the task, as before } ``` The credit is spent before the insert, so an empty workspace gets a 402 and no task is written. The same `Idempotency-Key` twice is charged once. In the recorded demo, a new user's workspace starts with 5 credits from a Workspace Created workflow: five `POST /api/tasks` answer 201 and the sixth answers 402. Add the 402 to the route's response schema so Swagger shows it. For the pricing decisions behind this, see [charging per API call](/guides/charge-per-api-call-nextjs) and [a credits wallet](/guides/credits-wallet-nextjs), written for Next.js but identical from the SDK call down. ### Where the alternatives are less work **[Auth0](/compare/auth0-vs-buildbase)'s Fastify SDK** registers `/auth/login`, `/auth/logout` and `/auth/callback` for you and keeps the session in an encrypted cookie. Here you write those routes, about 110 lines with the schemas. The demo's sessions also stay in memory, as upstream's did, so production needs a session store. **@fastify/auth** composes several checks with and/or logic, such as "a session or an API key". This example has one session check. If you need both, keep @fastify/auth for the composition and let BuildBase be one of the strategies it calls. ### What breaks, and how you can tell **Sign-in answers 503.** The BuildBase variables are not set. The route answers with the variables it needs; the rest of the API still runs. **Signing in trips the rate limiter.** The demo's global rate limit counts every request, and a sign-in is two, plus Swagger's own assets if you use the docs. Upstream's `.env.example` set 4 a minute for its tests; ours sets 8. Raise it for anything but the test suite. **The callback answers 500, not 401.** The code exchange or the profile read failed (a reused code, or a network error), and the demo's error handler, upstream's, hides the message of a 5xx. Check the server log. **Everyone is signed out after a deploy.** Sessions are in memory. Give `@fastify/session` a store. **The hosted page refuses to send you back.** The callback URL must match one registered on the auth client exactly, path included; the port must match too, except on localhost, where it is ignored. A wildcard can stand in for one leftmost subdomain on a domain you own, but not for a public suffix like `*.vercel.app`. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/fastify-demo my-app`. ```bash npm i @buildbase/sdk ``` --- ## BuildBase on Hono: authentication and billing on Workers, Bun, Deno and Node > Hono authentication with no user table: hosted sign-in, a signed-cookie session you can still revoke, and metered credits, in one app on Node, Bun, Deno and Workers. - Source: https://www.buildbase.app/guides/buildbase-on-hono - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-10-19 ### In short BuildBase adds authentication to a Hono app with a hosted sign-in page and a signed session cookie, so the app keeps no user table and a signed-out session stays signed out. The server SDK uses only fetch and Web APIs, so the same app runs on Node.js, Bun, Deno and Cloudflare Workers, and meters usage with credits. Search "hono authentication" and the top results are as likely to be about Eclipse Hono, an IoT messaging project. This page is about the other one: the small web framework that runs on Cloudflare Workers, Bun, Deno and Node.js without changing a line. That last part is the whole point of Hono, and it is the part auth usually breaks. You add a library, the library wants a database, and now your "runs anywhere" app needs a Postgres it can reach from the edge. Or you go stateless: Better Auth and Auth0's Hono SDK can both keep the session in a cookie. The catch there is revocation. Better Auth's own docs say that in stateless mode "you can't invalidate session easily". BuildBase takes a third path. **The cookie holds only a BuildBase session ID, and BuildBase checks it on every request.** There is no user table in your app, and a session revoked anywhere is signed out everywhere. The [example](https://github.com/buildbase-app/examples/tree/main/hono) is about 400 lines, and we signed into it separately on all four runtimes against a BuildBase org on a local stack. > **Before you start:** A Hono app, a BuildBase organization, and an auth client created in the > console under **User Management → Authentication**, with its client ID and > secret. Register `http://localhost:3000/auth/callback` on the client. On > localhost the port is ignored, so the same entry covers `wrangler dev` on > 8787; in production, register each deployment's `/auth/callback`. > **Tip:** **Start from the working example.** > [`hono`](https://github.com/buildbase-app/examples/tree/main/hono) in the > examples repo runs everything on this page on all four runtimes. [Watch it > working](https://github.com/buildbase-app/examples/tree/main/hono#see-it-working), > or copy it with `npx degit buildbase-app/examples/hono my-app`. ### 1. Four variables, read the same way on every runtime ```bash npm i hono @buildbase/sdk ``` ```bash # .env (Node, Bun, Deno) and .dev.vars (Workers) BUILDBASE_ORG_ID=demo-org-id BUILDBASE_CLIENT_ID=demo-client-id BUILDBASE_CLIENT_SECRET=demo-client-secret COOKIE_SECRET=a-long-random-string # openssl rand -hex 32 ``` Every runtime keeps its environment somewhere different: `process.env`, `Bun.env`, `Deno.env`, or the Worker's `env` argument, which only exists inside a request. `env()` from `hono/adapter` reads whichever applies, so the app never has to know: ```ts import { env } from 'hono/adapter'; const config = (c: Context) => env(c); const secure = (c: Context) => new URL(c.req.url).protocol === 'https:'; ``` Same reason the SDK client below is created on first use: at import time, a Worker has no config to give it. ### 2. The BuildBase calls, behind one function ```ts // src/buildbase.ts import { ApiVersion, AuthApi, BuildBase } from '@buildbase/sdk'; const clients = new Map>(); export function buildbaseFor(env: Env) { const serverUrl = env.BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app'; const orgId = env.BUILDBASE_ORG_ID ?? ''; const authApi = new AuthApi({ serverUrl, version: ApiVersion.V1 }); const forSession = (sessionId: string) => { let client = clients.get(orgId); if (!client) clients.set(orgId, (client = BuildBase({ serverUrl, orgId }))); return client.withSession(sessionId); }; return { signInUrl: async (state: string, callbackUrl: string) => ( await authApi.requestAuth({ orgId, clientId: env.BUILDBASE_CLIENT_ID ?? '', redirect: { success: callbackUrl, error: callbackUrl }, state, }) ).redirectUrl, exchangeCode: async (code: string) => { const res = await fetch(`${serverUrl}/api/v1/auth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, orgId, clientId: env.BUILDBASE_CLIENT_ID, clientSecret: env.BUILDBASE_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`BuildBase token exchange failed (${res.status})`); return ((await res.json()) as { data: { sessionId: string } }).data .sessionId; }, account: async (sessionId: string) => { const bb = forSession(sessionId); const [profile, [workspace]] = await Promise.all([ bb.users.getProfile(), bb.workspace.list(), ]); const balance = workspace ? await bb.credits.getBalance(workspace._id) : null; return { profile, workspace, credits: balance?.available ?? null }; }, spend: async (sessionId: string, idempotencyKey: string) => { const bb = forSession(sessionId); const [workspace] = await bb.workspace.list(); return bb.credits.consume(workspace._id, { amount: 1, idempotencyKey }); }, revoke: (sessionId: string) => authApi.logout(sessionId).catch(() => {}), }; } ``` Nothing here imports from Node. The SDK's root export sticks to `fetch` and other Web APIs, which is what lets one file run on all four runtimes. Every snippet on this page is trimmed from the example, and the example is the tested version. Its `buildbase.ts` is a little longer: it keys the client cache on the server URL too, and returns plain objects rather than SDK types. ### 3. Sign-in: a state cookie, a redirect, a signed session cookie ```tsx // src/app.tsx import { Hono } from 'hono'; import { deleteCookie, getSignedCookie, setSignedCookie } from 'hono/cookie'; app.get('/auth/sign-in', async (c) => { const cfg = config(c); const state = crypto.randomUUID(); await setSignedCookie(c, 'bb_state', state, cfg.COOKIE_SECRET!, { httpOnly: true, secure: secure(c), sameSite: 'Lax', path: '/auth', maxAge: 600, }); const callback = `${cfg.APP_URL || new URL(c.req.url).origin}/auth/callback`; return c.redirect(await buildbaseFor(cfg).signInUrl(state, callback)); }); app.get('/auth/callback', async (c) => { const cfg = config(c); const { code, state } = c.req.query(); const expected = await getSignedCookie(c, cfg.COOKIE_SECRET!, 'bb_state'); deleteCookie(c, 'bb_state', { path: '/auth' }); if (!code || !state || state !== expected) return c.redirect('/?error=sign-in-not-verified'); const sessionId = await buildbaseFor(cfg).exchangeCode(code); await setSignedCookie(c, 'bb_session', sessionId, cfg.COOKIE_SECRET!, { httpOnly: true, secure: secure(c), sameSite: 'Lax', path: '/', maxAge: 60 * 60 * 24 * 7, }); return c.redirect('/'); }); ``` Why sign the cookie when BuildBase checks the ID anyway? So that a forged or edited value is thrown away by `getSignedCookie` before the app spends a network call on it. Click **Sign in with BuildBase**, and the hosted page offers whichever sign-in methods your org has on; you come back to `/` signed in. ### 4. Every page asks BuildBase, which is what makes revocation work ```tsx const account = await buildbaseFor(config(c)) .account(sessionId) .catch((err) => { if (err.status !== 401) throw err; deleteCookie(c, 'bb_session', { path: '/' }); // revoked elsewhere return null; }); ``` That `catch` is the difference from a purely stateless session. Sign out on another device, or revoke the session from BuildBase, and the next request here gets a 401, clears the cookie and renders the signed-out page. The example has a test for exactly that. You pay for it in round trips to BuildBase on each page that needs the account: the profile and the workspace list together, then the balance, so two in a row. On Workers that call goes from the edge to BuildBase's API. Without BuildBase it would go to a database you run. ### 5. A metered endpoint that answers 402 ```tsx import { csrf } from 'hono/csrf'; app.use(csrf()); app.post('/api/spend', async (c) => { const sessionId = await getSignedCookie( c, config(c).COOKIE_SECRET!, 'bb_session' ); if (!sessionId) return c.json({ message: 'Sign in first.' }, 401); try { const key = c.req.header('Idempotency-Key') || crypto.randomUUID(); return c.json(await buildbaseFor(config(c)).spend(sessionId, key)); } catch (err) { if ((err as { code?: string }).code === 'INSUFFICIENT_CREDITS') { return c.json({ message: 'Out of credits.' }, 402); } throw err; } }); ``` Send the same `Idempotency-Key` twice and you are charged once. Empty the workspace and you get a 402 your client can turn into a buy-more prompt. For the pricing side of this, see [charging per API call](/guides/charge-per-api-call-nextjs) and [a credits wallet](/guides/credits-wallet-nextjs); both are written for Next.js, and from the SDK call down they are the same code. `csrf()` refuses cross-site form posts, and that includes a POST with no content type. So API callers send `Content-Type: application/json`, which another site cannot do without a CORS preflight. ### 6. Short entry files, one per runtime ```ts // src/node.ts import { serve } from '@hono/node-server'; import { createApp } from './app.tsx'; serve({ fetch: createApp().fetch, port: Number(process.env.PORT ?? 3000) }); // src/bun.ts export default { port: Number(process.env.PORT ?? 3000), fetch: createApp().fetch, }; // src/deno.ts Deno.serve({ port: Number(Deno.env.get('PORT') ?? 3000) }, createApp().fetch); // src/worker.ts export default createApp(); ``` Run `npm run dev`, `npm run dev:bun`, `npm run dev:deno` or `npm run dev:workers`, and the page tells you which runtime answered. On each of the four we signed in and spent credits. The Worker bundle comes to about 160 KiB, 39 KiB gzipped, and needs no `nodejs_compat` flag. > **Key takeaway:** On Hono, BuildBase is a signed cookie holding a session ID. No user table, no > Node APIs, and a revoked session stops working on the next request. ### Where the alternatives are the better fit **Better Auth** is free and open source, and you own every table. If you already run a database your edge can reach, or you want no vendor in the request path at all, it is the better choice. Its stateless mode also works with no database, as long as you can live with the revocation limit above. **[Auth0](/compare/auth0-vs-buildbase)'s `@auth0/auth0-hono`** is less code: `app.use('*', auth0())` gives you login, logout, callback and session. Its July 2026 launch post calls it beta, with Node and Workers as the fully supported runtimes and Bun and Deno as best-effort. This example goes one step further than sign-in: workspaces and credits from the same session. ### What breaks, and how you can tell **Sign-in answers 503.** A required variable is missing. The example lists them on the home page: `BUILDBASE_ORG_ID`, `BUILDBASE_CLIENT_ID`, `BUILDBASE_CLIENT_SECRET` and `COOKIE_SECRET`. **`POST /api/spend` returns 403 from curl.** The CSRF guard saw a body-less POST. Add `-H 'Content-Type: application/json'`. **Signed in on Node, signed out on Workers.** Different `COOKIE_SECRET`s, so one runtime cannot verify the other's cookie. In production each deployment has its own domain anyway; locally, share one secret. **The hosted page refuses to send you back.** The callback URL must match one registered on the auth client exactly, path included. On localhost the port is ignored, so one entry covers Node on 3000 and `wrangler dev` on 8787; anywhere else it must match too. A wildcard can stand in for one leftmost subdomain on a domain you own, but not for a public suffix like `*.vercel.app` or `*.workers.dev`. **Spends fail with 429 under load.** Credit consumption is limited to 30 requests a minute per IP, and Workers share outgoing IPs, so a busy Worker can reach it sooner than a single server would. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/hono my-app`. ```bash npm i hono @buildbase/sdk npm i @hono/node-server # only for the Node entry file ``` --- ## BuildBase on NestJS: authentication without Passport, JWTs or a refresh table > NestJS authentication without Passport or JWTs: one guard reads a Bearer session ID, RolesGuard keeps working, and ending a session actually ends it. - Source: https://www.buildbase.app/guides/buildbase-on-nestjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 ### In short To add authentication to a NestJS API without Passport or your own JWTs, use one guard that reads the Bearer token as a BuildBase session ID and sets id, role and sessionId on request.user, so RolesGuard and every @Roles() route keep working. Logout ends the session on BuildBase: no refresh tokens to rotate. NestJS's own authentication chapter signs a JWT at login and verifies it on every request, locally, with no call anywhere. That is fast, and it has one gap it never closes: nothing can end a token before it expires. [Fill that gap yourself](/blog/cost-of-building-auth-yourself) and you are building refresh tokens, a table to track them, and a way to revoke them. Look at what NestJS auth actually does, though, and it is **two jobs**. A guard says who is calling. `RolesGuard` says what they may do. Only the first one is about credentials, and only the first one needs replacing. So replace it with one guard. The Bearer token becomes a BuildBase session ID, BuildBase says who it belongs to, and `request.user` gets the same `{ id, role }` it always had. We did this to [nestjs-boilerplate](https://github.com/buildbase-app/examples/tree/main/nestjs-boilerplate-api), the 4.4k-star REST starter: `src` went from 6,268 lines to 4,338, and out went Passport, `@nestjs/jwt`, bcrypt and the session table. `RolesGuard`'s logic did not change. > **Before you start:** A NestJS API, a BuildBase organization, and an auth client created in the > console under **User Management → Authentication**, with its client ID and > secret. Register your frontend's callback URL on the client, and in > development the API's own > `http://localhost:3001/api/v1/auth/buildbase/callback` for trying things in > Swagger. > **Tip:** **Start from the working example.** > [`nestjs-boilerplate-api`](https://github.com/buildbase-app/examples/tree/main/nestjs-boilerplate-api) > in the examples repo runs everything on this page in nestjs-boilerplate. > [Watch it > working](https://github.com/buildbase-app/examples/tree/main/nestjs-boilerplate-api#see-it-working), > or copy it with `npx degit buildbase-app/examples/nestjs-boilerplate-api > my-app`. ### 1. One service owns every BuildBase call ```bash npm i @buildbase/sdk ``` ```ts // src/auth/buildbase.service.ts (trimmed) @Injectable() export class BuildBaseService { private client?: ReturnType; private readonly profiles = new Map< string, { profile: BuildBaseProfile; expires: number } >(); /** The hosted sign-in URL for a client to send people to. */ async signInUrl(redirect: string, state?: string): Promise { const { orgId, clientId } = this.requireConfigured(); const { redirectUrl } = await this.authApi().requestAuth({ orgId, clientId, redirect: { success: redirect, error: redirect }, state, }); return redirectUrl; } /** Swap the one-time code for a BuildBase session ID, with the secret. */ async exchangeCode(code: string): Promise { /* POST /api/v1/auth/token */ } /** The BuildBase user behind a session, cached for a minute, or 401. */ async profile(sessionId: string): Promise { const cached = this.profiles.get(sessionId); if (cached && cached.expires > Date.now()) return cached.profile; this.client ??= BuildBase({ serverUrl: this.serverUrl, orgId: this.orgId }); const user = await this.client .withSession(sessionId) .users.getProfile() .catch(() => { throw new UnauthorizedException(); }); const id = user.id ?? user._id; if (!id || !user.email) throw new UnauthorizedException(); const profile = { id: String(id), email: user.email, name: user.name }; this.profiles.set(sessionId, { profile, expires: Date.now() + 60_000 }); return profile; } /** Forget the session here, and end it on BuildBase. */ async revoke(sessionId: string) { this.profiles.delete(sessionId); await this.authApi() .logout(sessionId) .catch(() => {}); } } ``` Nest has no async request context of its own, so the SDK is bound per call with `withSession()`, the same way [Express](/guides/buildbase-on-express) and [Fastify](/guides/buildbase-on-fastify) bind it. The one-minute cache means a busy API asks BuildBase about once a minute per session per process, instead of on every request. The example's version also drops expired entries as it goes, so the map holds only recent sessions. ### 2. The guard: Bearer token in, `request.user` out ```ts // src/auth/buildbase-auth.guard.ts @Injectable() export class BuildBaseAuthGuard implements CanActivate { constructor(private readonly authService: AuthService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const [scheme, token] = (request.headers.authorization ?? '').split(' '); if (scheme !== 'Bearer' || !token) throw new UnauthorizedException(); request.user = await this.authService.userForSession(token); return true; } } ``` ```ts // src/auth/auth.service.ts async userForSession(sessionId: string) { const user = await this.resolveUser(await this.buildbase.profile(sessionId)); return { id: user.id, role: user.role, sessionId }; } ``` That return value is the whole trick. It is the shape the JWT strategy used to put on the request, so every controller that stacks the guards keeps reading it unchanged: ```ts @Roles(RoleEnum.admin) @UseGuards(BuildBaseAuthGuard, RolesGuard) @Controller({ path: 'users', version: '1' }) export class UsersController { /* upstream's, untouched */ } ``` The only edits in controllers like this are the guard's name and its import, where `AuthGuard('jwt')` used to be. And the role still comes from **your** users table on every request, so promoting someone to admin takes effect on their next call. If you would rather keep roles out of your database, [the Astro setup](/guides/buildbase-on-astro) reads a BuildBase workspace role on every request instead. `resolveUser` finds the user by BuildBase ID (stored where the boilerplate kept social logins, as `socialId` with provider `buildbase`), adopts an existing user by email, or creates one with the `user` role. The migration drops the `session` table and the `password` column. ### 3. Two endpoints for sign-in An API has no pages, so the client drives sign-in: 1. `GET /api/v1/auth/buildbase/url?redirect=&state=` returns `{ url }`, the hosted sign-in page. The client keeps the `state` and sends the person there. 2. BuildBase returns to your page with `?code=` and the `state`. The client refuses a `state` it did not issue, then posts the code to `POST /api/v1/auth/buildbase/login`, and gets back `{ token, user }`. 3. From then on: `Authorization: Bearer `. BuildBase checks the `redirect` against the URLs registered on the auth client, so nobody can point it at an arbitrary site. In development, `GET /api/v1/auth/buildbase/callback` exchanges the code itself and shows the token on a page (it skips the `state` check, which is the client's job). That is how you try the API in Swagger with no frontend at all. In production it answers 404. Try it: open the URL from step 1, sign in, paste the token into Swagger's **Authorize**, and `GET /api/v1/auth/me` returns your user with `provider: "buildbase"`. > **Key takeaway:** In NestJS, BuildBase replaces the guard that says who is calling. RolesGuard, > which says what they may do, keeps reading the same `{ id, role }` from > your own database. ### 4. Logout that actually logs out ```ts @Post('logout') @UseGuards(BuildBaseAuthGuard) @HttpCode(HttpStatus.NO_CONTENT) logout(@Request() request) { return this.authService.logout(request.user); // reads .sessionId, then buildbase.revoke() } ``` This is the part JWTs make hard. A signed token stays valid until it expires, whatever you do on the server, which is why JWT setups end up with refresh tokens and blocklists. Here the token is a session ID, and `revoke()` ends the session on BuildBase. The same token gets a 401 on the next request to the instance that handled the logout. The catch: other instances of your API can still hold that profile in their one-minute cache, so a revoked token works there for up to a minute. If a minute is too long, shorten the TTL or share the cache. And `revoke()` ignores a failed call to BuildBase, so if logout cannot reach it, the session lives on until it expires. ### Where plain JWTs are simpler NestJS's own authentication chapter verifies a JWT locally, with no network call at all. It also registers its guard globally and marks the exceptions with a `@Public()` decorator, so a new controller is protected until someone opts it out. The example does neither: it applies the guard per controller, as the boilerplate already did, and calls BuildBase on a cache miss. If your API cannot make an outbound call on the auth path, or you never need to end a session early, a self-verified JWT has fewer moving parts. ### What breaks, and how you can tell **Sign-in and every protected route answer 503.** `BUILDBASE_ORG_ID`, `BUILDBASE_CLIENT_ID` or `BUILDBASE_CLIENT_SECRET` is missing, and the service refuses to guess. **A logged-out token still works for a minute.** A different instance served it from its cache. See the limit above. **Seeded users cannot sign in.** They have no BuildBase account yet. Adoption by email happens the first time someone signs in through BuildBase with that address, role and all. **`GET auth/buildbase/url` fails.** BuildBase refused the `redirect`: it must match a URL registered on the auth client exactly, path included; the port must match too, except on localhost, where it is ignored. A wildcard can stand in for one leftmost subdomain on a domain you own, but not for a public suffix like `*.vercel.app`. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/nestjs-boilerplate-api my-app`. ```bash npm i @buildbase/sdk ``` --- ## BuildBase on Next.js: add auth, teams and billing to the app you already have > Add auth, teams and billing to an existing Next.js app: the setup, getting the session to server components, and three popular templates swapped over. - Source: https://www.buildbase.app/guides/buildbase-on-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-11-04 ### In short To add auth and billing to an existing Next.js app with BuildBase, send users to hosted sign-in, swap the returned code for a session on the server, and keep it in an httpOnly cookie that server code reads through getSessionId. After that, teams, plans and credits are ordinary SDK calls in client and server code alike. Every auth, billing and teams guide for Next.js starts from a blank app. Yours is not blank. It has a users table, a login page someone wrote in a hurry, maybe a Stripe webhook that mostly works. Here is the part those guides skip: in Next.js, the only thing that differs from any other stack is **how the session reaches a server component**. Get those thirty-odd lines right once and everything after them - [workspaces](/guides/multi-tenant-workspaces-in-an-afternoon), plans, credits, roles - is the same SDK call you would make anywhere else. We checked that the unglamorous way. We pulled BuildBase into three [templates people already clone](/compare/best-saas-starter-solo-founders), then deleted whatever it replaced and counted the lines. > **Before you start:** A Next.js app on the App Router, a BuildBase organization, and an auth client > created in the console under **User Management → Authentication**, with its > client ID and secret. Register your callback URL on that client, for example > `http://localhost:3000`, exactly as your app serves it. > **Tip:** **Start from the working example.** > [`with-buildbase`](https://github.com/buildbase-app/examples/tree/main/with-buildbase) > in the examples repo is the five steps below and nothing else. [Watch it > working](https://github.com/buildbase-app/examples/tree/main/with-buildbase#see-it-working), > or copy it with `npx degit buildbase-app/examples/with-buildbase my-app`. For > a full app, start from > [`saas-starter`](https://github.com/buildbase-app/examples/tree/main/saas-starter) > (teams and plans), > [`ai-chatbot`](https://github.com/buildbase-app/examples/tree/main/ai-chatbot) > (credits per message) or > [`nextjs-boilerplate`](https://github.com/buildbase-app/examples/tree/main/nextjs-boilerplate) > (the Clerk swap). ### 1. Install the SDK and set five variables ```bash npm i @buildbase/sdk ``` ```bash # .env.local NEXT_PUBLIC_BUILDBASE_ORG_ID=demo-org-id NEXT_PUBLIC_BUILDBASE_CLIENT_ID=demo-client-id NEXT_PUBLIC_BUILDBASE_REDIRECT_URL=http://localhost:3000 BUILDBASE_CLIENT_SECRET=demo-client-secret # server only, never NEXT_PUBLIC_ # NEXT_PUBLIC_BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` Only the secret goes without the `NEXT_PUBLIC_` prefix. Next.js inlines anything with that prefix into the client bundle, which is the one place a secret cannot go. ### 2. Wrap the app in the provider The React SDK needs three callbacks from you: where to get the current session, what to do with the one-time code the hosted page returns, and how to sign out. All three talk to your own route handlers, which you write in the next step. ```tsx // app/providers.tsx 'use client'; import '@buildbase/sdk/css'; import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; export function Providers({ children }: { children: React.ReactNode }) { return ( (await (await fetch('/api/auth/session')).json()).sessionId, handleAuthentication: async (code: string) => { const res = await fetch('/api/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); return { sessionId: (await res.json()).sessionId }; }, onSignOut: async () => { await fetch('/api/auth/signout', { method: 'POST' }); }, }, }} > {children} ); } ``` Render `` around `{children}` in `app/layout.tsx`. A button that calls `signIn()` from `useSaaSAuth()` now sends people to the hosted sign-in page, which offers whichever sign-in methods your org has switched on. ### 3. Swap the code for a session, on the server The hosted page comes back with a one-time `code`. Exchanging it needs the client secret, so it happens in a route handler. Whatever session comes back goes straight into an httpOnly cookie. ```ts // app/api/auth/token/route.ts import { NextResponse } from 'next/server'; import { environmentId } from '@buildbase/sdk'; import { SESSION_COOKIE_NAME } from '@/lib/buildbase'; export async function POST(request: Request) { const { code } = await request.json(); const res = await fetch( `${process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app'}/api/v1/auth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, // - in a development or staging environment. orgId: environmentId( process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!, process.env.NEXT_PUBLIC_BUILDBASE_ENVIRONMENT ), clientId: process.env.NEXT_PUBLIC_BUILDBASE_CLIENT_ID, clientSecret: process.env.BUILDBASE_CLIENT_SECRET, }), } ); if (!res.ok) return NextResponse.json({ error: 'Sign-in failed' }, { status: 401 }); const { data } = await res.json(); const response = NextResponse.json({ sessionId: data.sessionId }); response.cookies.set(SESSION_COOKIE_NAME, data.sessionId, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 60 * 60 * 24 * 30, }); return response; } ``` The 30-day `maxAge` matches BuildBase's default session length. Two shorter routes finish the set: `GET /api/auth/session` returns the cookie's value so the client can restore itself after a refresh, and `POST /api/auth/signout` deletes it. Both are a handful of lines in the [with-buildbase example](https://github.com/buildbase-app/examples/tree/main/with-buildbase/app/api/auth). A single-page app with no server of its own needs the same three, and [BuildBase on Vite](/guides/buildbase-on-vite) runs them as serverless functions. ### 4. Teach the server SDK where the session lives This is the Next.js-specific part. The server SDK takes a `getSessionId` function, and in Next.js that function reads the cookie: ```ts // lib/buildbase.ts import { cookies } from 'next/headers'; import BuildBase from '@buildbase/sdk'; // The name `npx buildbase init` writes. A development or staging environment // gets its own (bb-session-id-), so two builds on one host never mix. const environment = process.env.NEXT_PUBLIC_BUILDBASE_ENVIRONMENT; export const SESSION_COOKIE_NAME = environment && environment !== 'production' ? `bb-session-id-${environment}` : 'bb-session-id'; export async function getSessionId() { return (await cookies()).get(SESSION_COOKIE_NAME)?.value ?? null; } let client: ReturnType | undefined; export function bb() { client ??= BuildBase({ serverUrl: process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL || 'https://api.console.buildbase.app', orgId: process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!, environment, getSessionId, }); return client; } ``` Why a function rather than `BuildBase(...)` at the top of the file? Because `BuildBase()` refuses to start without an org ID, and a module-level call breaks `next build` on any machine where the env is not filled in yet. Creating it on first use keeps the build green. ### 5. Read the user in a server component ```tsx // app/profile/page.tsx import { redirect } from 'next/navigation'; import { bb } from '@/lib/buildbase'; export const dynamic = 'force-dynamic'; export default async function ProfilePage() { const profile = await bb() .users.getProfile() .catch(() => null); if (!profile) redirect('/'); return

Signed in as {profile.email}

; } ``` Sign in, open `/profile`, and the email comes from BuildBase via your server, with nothing in client state. Delete the cookie in dev tools and reload: you are sent home. That round trip is the whole integration. The same `bb()` works in a route handler or a server action without changes. > **Key takeaway:** In Next.js, BuildBase is a cookie and a `getSessionId` function. Everything > after that is the same call you would make from any other framework. ### 6. Then add the part you actually came for With the session flowing, each feature is its own guide. They all assume the five steps above: - **Sign-in methods.** [Magic link](/guides/magic-link-login-nextjs) and [passkeys](/guides/passkeys-nextjs) are toggles, not code. [Social login](/guides/social-login-nextjs) needs no new code either: create an OAuth app at the provider and add it in the console. If protected pages bounce you back to login forever, see [the middleware redirect loop](/guides/nextjs-middleware-redirect-loop-after-login). - **Plans.** [A free trial without a card](/guides/free-trial-without-a-card-nextjs), [an annual and monthly toggle](/guides/annual-and-monthly-toggle-nextjs), [proration on plan change](/guides/proration-on-plan-change-nextjs), [changing prices without touching existing customers](/guides/plan-versioning-nextjs) and [charging per seat](/guides/charge-per-seat-nextjs). - **Usage.** [A credits wallet](/guides/credits-wallet-nextjs), [charging per credit](/guides/charge-per-credit-nextjs), [charging per API call](/guides/charge-per-api-call-nextjs) and [enforcing quotas on the server](/guides/quota-enforcement-server-side-nextjs). - **Workspaces.** [Per-org data isolation](/guides/per-org-data-isolation-nextjs) in your own tables, [roles and permissions per workspace](/guides/roles-and-permissions-per-workspace-nextjs) and [team invitations](/guides/team-invitations-nextjs). ### What it replaced in three real templates Guides on blank apps prove the API works. They do not show what you get to delete. So we took three templates with 50,000 GitHub stars between them and swapped BuildBase in, one folder each in the [examples repo](https://github.com/buildbase-app/examples): - **[saas-starter](https://github.com/buildbase-app/examples/tree/main/saas-starter)**, from nextjs/saas-starter (16k stars). Its bcrypt and `jose` sessions, the teams, members, invitations and activity-log tables, and [the Stripe checkout, portal and webhook](/compare/best-way-to-add-billing-nextjs) all went. So did Postgres: the app's TypeScript dropped from 3,586 lines to 1,773. - **[nextjs-boilerplate](https://github.com/buildbase-app/examples/tree/main/nextjs-boilerplate)**, from ixartz/Next-js-Boilerplate (13k stars). [The Clerk swap](/compare/clerk-vs-buildbase): the route guard, provider, sign-in and sign-up pages, user profile and `currentUser()` calls. Two dependencies out, one in. - **[ai-chatbot](https://github.com/buildbase-app/examples/tree/main/ai-chatbot)**, from vercel/chatbot (21k stars). NextAuth and guest accounts are replaced, and the "10 messages per user per hour" cap becomes credits: every message calls `bb.credits.consume()` with the message ID as its idempotency key, and an empty workspace gets a 402. Each README says what changed, what stayed upstream's, and what the swap does not cover. Inviting someone who has no account yet is no longer a gap: since SDK 0.0.71, `inviteMember(workspaceId, email, role)` from `useSaaSWorkspaces()` emails a link that lands on your redirect URL, where the person signs in or registers and accepts. ### What breaks, and how you can tell **The hosted page refuses to send you back.** The URL in `NEXT_PUBLIC_BUILDBASE_REDIRECT_URL` must match one registered on the auth client character for character, scheme and path included; the port must match too, except on localhost, where it is ignored. A wildcard can stand in for one leftmost subdomain on a domain you own (`https://*.app.example.com/...`), but not for a public suffix, so `*.vercel.app` is refused: register each preview domain you use. **The profile page shows the last user who loaded it.** Next.js cached the page. Anything that reads the session cookie must render per request: mark it `force-dynamic`, or read `cookies()` before you fetch. **The old workspace's data stays on screen after a switch.** A cache keyed without the workspace id never learns it changed, so [key every query by workspace id](/guides/stale-data-after-workspace-switch). **`cookies()` wants an `await` on one version and not the other.** It is synchronous in Next.js 14 and asynchronous from 15. The three templates above run 15 and 16, so they await it; on 14, drop the `await`. Next.js 16 also renames `middleware.ts` to `proxy.ts`, which is why the boilerplate's route guard lives there. **Credits stop spending under load, with 429s.** Credit consumption is limited to 30 requests a minute per IP. Serverless functions can share an outgoing IP, so a busy Vercel deployment can hit that where a single server would not. **The secret shows up in your client bundle.** Someone added `NEXT_PUBLIC_` to `BUILDBASE_CLIENT_SECRET`. Treat the secret as leaked: create a new auth client secret, then remove the prefix. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/with-buildbase my-app`. ```bash npm i @buildbase/sdk ``` --- ## BuildBase on React Router (Remix): hosted sign-in, your own session, no loader changes > React Router v7 authentication with hosted sign-in: a login action, a callback route that swaps the code, and your own session, so no loader changes. - Source: https://www.buildbase.app/guides/buildbase-on-react-router - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-10-19 ### In short To add authentication to a React Router v7 app with BuildBase, have the login action redirect to hosted sign-in and a resource route swap the returned code for a session using the client secret. The callback finds or creates your user and opens your usual session, so requireUserId and every loader stay unchanged. Remix apps have always done authentication the same way: a loader reads a cookie session, `requireUserId()` throws a redirect when it is empty, and every protected route calls it. React Router v7 kept all of that. So the useful question is not which auth library to add. It is **how little has to change**. With BuildBase the answer is three routes. The login action redirects to a hosted page, a new callback route swaps the returned code for a session and opens your own session exactly as before, and logout ends both. `requireUserId()` does not know anything happened, and neither does a single loader. We checked that claim on the [Epic Stack](https://github.com/buildbase-app/examples/tree/main/epic-stack), Kent C. Dodds' starter, which [builds passwords, verification emails, GitHub OAuth and passkeys by hand](/blog/cost-of-building-auth-yourself). About 4,200 lines of app code and 1,000 lines of tests came out. The notes app, roles and permissions did not change. > **Before you start:** A React Router v7 app in framework mode (or Remix v2) with a cookie session, a > BuildBase organization, and an auth client created in the console under **User > Management → Authentication**, with its client ID and secret. Register > `http://localhost:3000/auth/buildbase/callback` on the client as a redirect > URL. > **Tip:** **Start from the working example.** > [`epic-stack`](https://github.com/buildbase-app/examples/tree/main/epic-stack) > in the examples repo runs everything on this page in the Epic Stack. [Watch it > working](https://github.com/buildbase-app/examples/tree/main/epic-stack#see-it-working), > or copy it with `npx degit buildbase-app/examples/epic-stack my-app`. ### 1. Install the SDK and add three server variables ```bash npm i @buildbase/sdk ``` ```bash # .env BUILDBASE_ORG_ID=demo-org-id BUILDBASE_CLIENT_ID=demo-client-id BUILDBASE_CLIENT_SECRET=demo-client-secret # BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` No `VITE_` prefix on any of them. Sign-in runs on the server, so the browser never needs them for it. (Step 6's optional React SDK sends the org and client IDs to the browser; never the secret.) ### 2. Write the two BuildBase calls, in one server module ```ts // app/utils/buildbase.server.ts import crypto from 'node:crypto'; import { ApiVersion, AuthApi, BuildBase } from '@buildbase/sdk'; const serverUrl = () => process.env.BUILDBASE_SERVER_URL ?? 'https://api.console.buildbase.app'; export const newState = () => crypto.randomBytes(16).toString('hex'); /** The hosted sign-in URL. BuildBase returns to /auth/buildbase/callback. */ export async function getSignInUrl(request: Request, state: string) { const callback = new URL('/auth/buildbase/callback', request.url).toString(); const { redirectUrl } = await new AuthApi({ serverUrl: serverUrl(), version: ApiVersion.V1, }).requestAuth({ orgId: process.env.BUILDBASE_ORG_ID!, clientId: process.env.BUILDBASE_CLIENT_ID!, redirect: { success: callback, error: callback }, state, }); return redirectUrl; } /** Swap the one-time code for a BuildBase session ID, with the secret. */ export async function exchangeCode(code: string) { const res = await fetch(`${serverUrl()}/api/v1/auth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, orgId: process.env.BUILDBASE_ORG_ID, clientId: process.env.BUILDBASE_CLIENT_ID, clientSecret: process.env.BUILDBASE_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`BuildBase token exchange failed (${res.status})`); return ((await res.json()) as { data: { sessionId: string } }).data.sessionId; } let client: ReturnType | undefined; /** The server SDK, bound to one session per call. */ export function buildbaseFor(sessionId: string) { client ??= BuildBase({ serverUrl: serverUrl(), orgId: process.env.BUILDBASE_ORG_ID!, }); return client.withSession(sessionId); } ``` Why `withSession()` rather than a `getSessionId` callback like the [Next.js setup](/guides/buildbase-on-nextjs)? Next.js can read cookies from anywhere in a request. A React Router loader gets its `request` as an argument and nothing else does, so each loader binds the session it already has. [Express](/guides/buildbase-on-express) works the same way, with `req` in place of `request`, and so does [Hono](/guides/buildbase-on-hono), where the session comes out of a signed cookie on each request. ### 3. The login action: remember two things, then redirect ```ts // app/routes/_auth/login.tsx import { getSignInUrl, newState } from '#app/utils/buildbase.server.ts'; import { authSessionStorage } from '#app/utils/session.server.ts'; import { redirect } from 'react-router'; export async function action({ request }: Route.ActionArgs) { const formData = await request.formData(); const redirectTo = formData.get('redirectTo'); const state = newState(); const authSession = await authSessionStorage.getSession( request.headers.get('cookie') ); authSession.set('buildbaseState', state); authSession.set( 'buildbaseRedirectTo', typeof redirectTo === 'string' ? redirectTo : '' ); return redirect(await getSignInUrl(request, state), { headers: { 'set-cookie': await authSessionStorage.commitSession(authSession), }, }); } ``` The login page shrinks to one form with a hidden `redirectTo` and a **Continue to sign in** button. `state` guards the round trip against forged callbacks. `redirectTo` is the part people lose: the hosted page comes back to one fixed URL, so the page the user wanted has to ride along in your own cookie. Submit the form and you should land on BuildBase's hosted page, offering whichever sign-in methods your org has switched on. ### 4. The callback: check the state, swap the code, open your session A resource route, so it has a loader and no UI: ```ts // app/routes/_auth/auth.buildbase.callback.ts import { createSessionForBuildBaseUser } from '#app/utils/auth.server.ts'; import { buildbaseFor, exchangeCode } from '#app/utils/buildbase.server.ts'; import { authSessionStorage } from '#app/utils/session.server.ts'; import { redirect } from 'react-router'; export async function loader({ request }: Route.LoaderArgs) { const url = new URL(request.url); const code = url.searchParams.get('code'); const state = url.searchParams.get('state'); const authSession = await authSessionStorage.getSession( request.headers.get('cookie') ); if (!code || !state || state !== authSession.get('buildbaseState')) { throw redirect('/login'); } const buildbaseSessionId = await exchangeCode(code); const profile = await buildbaseFor(buildbaseSessionId).users.getProfile(); // The API returns `id`; the SDK type marks it optional beside `_id`. const id = profile.id ?? profile._id; if (!id || !profile.email) throw redirect('/login'); return createSessionForBuildBaseUser({ request, buildbaseSessionId, profile: { id: String(id), email: profile.email, name: profile.name }, redirectTo: authSession.get('buildbaseRedirectTo') || '/', }); } ``` Require the `state`, not just compare it when present. A check written as `state && state !== expected` lets a callback with no `state` straight through. We shipped exactly that in three examples and caught it while writing this. `createSessionForBuildBaseUser` is where your app stays your app. It finds the user by `buildbaseId`, or adopts an existing user with the same email, or creates one with your default role. Then it creates your usual `Session` row and sets your usual cookie, plus the BuildBase session ID beside it: ```ts // app/utils/auth.server.ts (the new part) let user = (await prisma.user.findUnique({ where: { buildbaseId: profile.id } })) ?? (await prisma.user.findUnique({ where: { email: profile.email.toLowerCase() }, })); // ...update or create, then: const session = await prisma.session.create({ data: { expirationDate: getSessionExpirationDate(), userId: user.id }, }); authSession.set(sessionKey, session.id); authSession.set('buildbaseSessionId', buildbaseSessionId); ``` Adopting by email is what lets you move an app that already has users. Nobody re-registers. The first time someone signs in through BuildBase with the email they already had, their old row gets a `buildbaseId` and keeps its notes and roles. To check it, open a protected page while signed out. You go to `/login`, through the hosted page, and land back on the page you asked for. ### 5. Logout ends both sessions ```ts // app/utils/buildbase.server.ts export async function revokeBuildBaseSession(sessionId: string | undefined) { if (!sessionId) return; await new AuthApi({ serverUrl: serverUrl(), version: ApiVersion.V1 }) .logout(sessionId) .catch(() => {}); } // in your logout(), before destroying the cookie await revokeBuildBaseSession(authSession.get('buildbaseSessionId')); ``` Skip this and you are signed out of your app, but the BuildBase session stays alive: anything else holding it keeps working until it expires. > **Key takeaway:** In React Router, BuildBase proves who someone is. Your loaders keep trusting > your own session, so `requireUserId()` and every route built on it stay as > they are. ### 6. Optional: the React SDK, for screens you do not want to build Sign-in does not need the React SDK at all. The Epic Stack example uses it for something else: its five settings pages (email, password, two-factor codes, connections and passkeys) are gone, and three buttons open the SDK's security, devices and account screens in their place. Those screens cover all five: the security screen has the password, two-step sign-in, connected accounts and passkeys, the account screen the email and the rest of the profile, and the devices screen sessions and devices. Two things make it behave in a server-rendered app: - **Hand it the session through a resource route**, not by exposing the cookie. `/resources/buildbase-session` returns the BuildBase session ID only to a signed-in user, with `Cache-Control: no-store`, and the provider's `getSession` fetches it. - **Call `clearAuthIntent()` before the provider renders**, in the browser. The SDK remembers any page it sees while signed out as the place to return after sign-in, and jumps there the next time it finds a session. In this setup the server already returns people to the right page, so the SDK's memory only fights it. A [TanStack Start app on better-auth](/guides/buildbase-on-tanstack-start) needs the same call. The screens are [scoped to a workspace](/guides/multi-tenant-workspaces-in-an-afternoon). The SDK fetches the workspace list only when asked, so the example loads it once per sign-in and picks the first one. ### What breaks, and how you can tell **After sign-in you land on the wrong page, or bounce once.** The React SDK's remembered page is winning over your `redirectTo`. Call `clearAuthIntent()` before `SaaSOSProvider` renders. **Every sign-in lands back on `/login`.** The state cookie is not surviving the round trip. The cookie session must be `SameSite=Lax`, not `Strict`: the hosted page returns with a top-level navigation from another site, and a strict cookie is not sent on it. **Seeded users cannot sign in.** They have no BuildBase account yet. Adoption by email only happens when someone signs in through BuildBase with that email, so sign up once with the seeded address. **The hosted page refuses to send you back.** The callback URL must match one registered on the auth client exactly, path included; the port must match too, except on localhost, where it is ignored. A wildcard can stand in for one leftmost subdomain on a domain you own (`https://*.app.example.com/...`), but not for a public suffix, so `*.vercel.app` is refused: register each preview domain you use. **Account screens open to nothing.** No workspace is selected, or none exists. In the console's workspace settings, check that Auto-Create First Workspace (under Advanced Overrides) is on; it is by default. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/epic-stack my-app`. ```bash npm i @buildbase/sdk ``` --- ## BuildBase on TanStack Start: hosted sign-in without replacing better-auth > TanStack Start authentication for apps already on better-auth: add BuildBase as a better-auth plugin and keep your sessions, roles and server-function checks. - Source: https://www.buildbase.app/guides/buildbase-on-tanstack-start - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-10-19 ### In short To add hosted sign-in to a TanStack Start app on better-auth, add BuildBase as a better-auth plugin with two endpoints: one redirects to the hosted page, one handles the callback, adopts existing users by email and opens a normal better-auth session. Roles and checks stay put, and sign-out ends both sessions. Most TanStack Start authentication guides start from nothing: pick a provider, wire it in. But a lot of Start apps already have better-auth, and with it a session table, an admin plugin, roles, and a permission check in every server function. Tearing that out to get hosted sign-in would be a bad trade. You do not have to. better-auth is built from plugins, and a sign-in method is just a plugin. So **replace the front door, not the house**: BuildBase becomes a better-auth plugin with two endpoints. It proves who someone is, and better-auth opens its own session for them exactly as it would after a GitHub login. Nothing that reads a session can tell the difference. We did this to [Start UI](https://github.com/buildbase-app/examples/tree/main/start-ui-web), BearStudio's TanStack Start template. Its email-code sign-in, GitHub login and login emails came out, the rest stayed, and upstream's 103 unit tests still pass. > **Before you start:** A TanStack Start app using better-auth, a BuildBase organization, and an auth > client created in the console under **User Management → Authentication**, with > its client ID and secret. Register > `http://localhost:3000/api/auth/buildbase/callback` on the client as a > redirect URL. > **Tip:** **Start from the working example.** > [`start-ui-web`](https://github.com/buildbase-app/examples/tree/main/start-ui-web) > in the examples repo runs everything on this page in Start UI. [Watch it > working](https://github.com/buildbase-app/examples/tree/main/start-ui-web#see-it-working), > or copy it with `npx degit buildbase-app/examples/start-ui-web my-app`. ### 1. Four variables, one of them secret ```bash npm i @buildbase/sdk ``` ```bash # .env VITE_BUILDBASE_ORG_ID=demo-org-id VITE_BUILDBASE_CLIENT_ID=demo-client-id BUILDBASE_CLIENT_SECRET=demo-client-secret # server only # VITE_BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app ``` The org and client IDs carry `VITE_` because the React SDK's account screens use them in the browser (step 5). The secret does not: Start builds with Vite, which [inlines every `VITE_` variable](/guides/buildbase-on-vite) into the bundle, and only the plugin reads the secret, on the server. ### 2. The plugin: a session field and two endpoints ```ts // src/server/buildbase-auth.ts import { ApiVersion, AuthApi, BuildBase } from '@buildbase/sdk'; import type { BetterAuthPlugin } from 'better-auth'; import { APIError, createAuthEndpoint } from 'better-auth/api'; import { setSessionCookie } from 'better-auth/cookies'; import { z } from 'zod'; export const buildbaseAuth = (options: BuildBaseAuthOptions) => { const authApi = () => new AuthApi({ serverUrl: options.serverUrl, version: ApiVersion.V1 }); // No round trip it cannot finish: without these, sign-in answers 503. const configured = () => { const { orgId, clientId, clientSecret } = options; if (!orgId || !clientId || !clientSecret) throw new APIError('SERVICE_UNAVAILABLE'); return { orgId, clientId, clientSecret }; }; return { id: 'buildbase', schema: { // The BuildBase session behind each better-auth session. session: { fields: { buildbaseSessionId: { type: 'string', required: false } } }, }, endpoints: { buildbaseSignIn: createAuthEndpoint( '/buildbase/sign-in', { method: 'GET', query: z.object({ redirectTo: z.string().optional() }) }, async (ctx) => { const { orgId, clientId } = configured(); const state = crypto.randomUUID(); const redirectTo = sameOriginPath(ctx.query.redirectTo, ctx.context.baseURL); await ctx.setSignedCookie('buildbase_state', JSON.stringify({ state, redirectTo }), ctx.context.secret, { httpOnly: true, sameSite: 'lax', path: '/', maxAge: 600, secure: ctx.context.baseURL.startsWith('https') }); const callback = `${ctx.context.baseURL}/buildbase/callback`; const { redirectUrl } = await authApi().requestAuth({ orgId, clientId, redirect: { success: callback, error: callback }, state, }); throw ctx.redirect(redirectUrl); }, ), buildbaseCallback: /* step 3 */, }, hooks: { before: [/* step 4 */] }, } satisfies BetterAuthPlugin; }; ``` The new `buildbaseSessionId` field is why this is a plugin and not just a pair of routes. better-auth adds the column to its session table, so each better-auth session remembers the BuildBase session behind it. Sign-out and the React SDK both need that. `sameOriginPath`, a dozen lines in the example's file, keeps only a path on your own site, so the `redirectTo` cannot be turned into an open redirect. Register the plugin next to the ones you have: ```ts // src/server/auth.tsx plugins: [ admin({ /* your roles and permissions, unchanged */ }), buildbaseAuth({ serverUrl: envClient.VITE_BUILDBASE_SERVER_URL, orgId: envClient.VITE_BUILDBASE_ORG_ID, clientId: envClient.VITE_BUILDBASE_CLIENT_ID, clientSecret: envServer.BUILDBASE_CLIENT_SECRET, }), ], ``` Point your login button at `/api/auth/buildbase/sign-in?redirectTo=...` and you land on the hosted page, offering whichever sign-in methods your org has turned on. ### 3. The callback: state, code, then better-auth's own adapter ```ts async (ctx) => { const { orgId, clientId, clientSecret } = configured(); const raw = await ctx.getSignedCookie('buildbase_state', ctx.context.secret); const saved = raw ? JSON.parse(raw) : null; const { code, state } = ctx.query; if (!code || !saved || !state || state !== saved.state) { throw ctx.redirect('/login/error?error=STATE_MISMATCH'); } const res = await fetch(`${options.serverUrl}/api/v1/auth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, orgId, clientId, clientSecret }), }); if (!res.ok) throw ctx.redirect('/login/error?error=INVALID_CODE'); const buildbaseSessionId = (await res.json()).data.sessionId; const profile = await BuildBase({ serverUrl: options.serverUrl, orgId }) .withSession(buildbaseSessionId) .users.getProfile(); const rawId = profile.id ?? profile._id; if (!rawId || !profile.email) throw new Error('BuildBase profile has no ID or email.'); const accountId = String(rawId); const email = profile.email.toLowerCase(); const adapter = ctx.context.internalAdapter; const owner = await adapter.findAccountOwnerByKey({ providerId: 'buildbase', accountId, }); let user = owner?.kind === 'owned' ? owner.user : null; if (!user) { const existing = await adapter.findUserByEmail(email); if (existing) { // A user from before BuildBase, with the same email, is adopted. await adapter.linkAccount({ userId: existing.user.id, providerId: 'buildbase', accountId, }); user = existing.user; } else { ({ user } = await adapter.createOAuthUser( // The example also sets Start UI's onboardedAt, so new users skip onboarding. { email, name: profile.name || email.split('@')[0], emailVerified: true, }, { providerId: 'buildbase', accountId } )); } } const session = await adapter.createSession(user.id, false, { buildbaseSessionId, }); await setSessionCookie(ctx, { session, user }); throw ctx.redirect(saved.redirectTo); }; ``` Everything after the code exchange is better-auth's own machinery. BuildBase users live in better-auth's account table under the `buildbase` provider, the same way GitHub users did, and `createSession` issues an ordinary better-auth session. Your `admin()` plugin's roles and the permission checks in each server function (in Start UI, its oRPC procedures) see a normal signed-in user. To check it, open a protected page while signed out and sign in on the hosted page. You land back where you started. Then sign in as an existing user with their old email: they keep their role. ### 4. Sign-out revokes the BuildBase session ```ts import { createAuthMiddleware, getSessionFromCtx } from 'better-auth/api'; hooks: { before: [{ matcher: (ctx) => ctx.path === '/sign-out', handler: createAuthMiddleware(async (ctx) => { const current = await getSessionFromCtx(ctx).catch(() => null); const id = (current?.session as { buildbaseSessionId?: string } | undefined) ?.buildbaseSessionId; if (id) await authApi().logout(id).catch(() => undefined); }), }], }, ``` A `before` hook runs while the better-auth session still exists, so it can read the BuildBase session ID off it. Without this, better-auth signs you out, but the BuildBase session stays alive: anything else holding it keeps working until it expires. > **Key takeaway:** On TanStack Start with better-auth, BuildBase is a plugin: a session field, > two endpoints and one hook. better-auth still owns the session, so roles and > server-function checks do not change. ### 5. The React SDK for account screens Start UI's account page gains a sign-in and security card, next to upstream's own cards, whose rows open the SDK's security, devices and account screens. Two details matter: - The provider's `getSession` reads `buildbaseSessionId` from `authClient.getSession()`, the field the plugin added. No second cookie. - Call `clearAuthIntent()` before the provider renders. The SDK remembers pages it saw while signed out and jumps back to them when it finds a session; here better-auth already handles the return trip, so that memory only fights it. The [React Router setup](/guides/buildbase-on-react-router) makes the same call for the same reason. And guard where the data is. TanStack Start's own docs are blunt that `beforeLoad` is for route UX and "not the security boundary for the data". A better-auth app already checks the session in each server function; this swap leaves those checks exactly as they were. ### Where Generic OAuth is enough better-auth's own **Generic OAuth** plugin connects any OAuth or OIDC provider without writing a plugin. Discovery, PKCE, token refresh and provider logout are all configuration, not code. For a standards-compliant provider, use it. This example needed its own plugin for three reasons. First, BuildBase's round trip is not OAuth-shaped: the hosted page comes from an API call (`requestAuth()`) rather than a static authorize URL, and the token exchange returns a BuildBase session, not an OAuth token response. Second, sign-out has to revoke that session on the server, not send the browser to a logout page. And the React SDK needs the BuildBase session ID on the better-auth session, which Generic OAuth's docs do not offer. ### What breaks, and how you can tell **`/login/error?error=STATE_MISMATCH` on every attempt.** The state cookie is not surviving the round trip: it must be `SameSite=Lax`, and `secure` only when the site is served over https. **Sign-in answers 503.** `VITE_BUILDBASE_ORG_ID`, `VITE_BUILDBASE_CLIENT_ID` or `BUILDBASE_CLIENT_SECRET` is missing; the plugin refuses to start a round trip it cannot finish. **The account screen buttons stay disabled.** No workspace is selected, and the screens are [scoped to a workspace](/guides/multi-tenant-workspaces-in-an-afternoon). The example loads the user's workspaces once per sign-in and selects the first; in the console, check that Auto-Create First Workspace (under Advanced Overrides) is on, which it is by default. **The hosted page refuses to send you back.** The callback URL must match one registered on the auth client exactly, path included. The port must match too, except on localhost, where it is ignored. A wildcard can stand in for one leftmost subdomain on a domain you own, but not for a public suffix like `*.vercel.app`. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/start-ui-web my-app`. ```bash npm i @buildbase/sdk ``` --- ## BuildBase on Vite: add auth, teams and billing to a React SPA with no server > Add authentication to a Vite React app with no server of its own: three small functions for the code exchange, an httpOnly cookie, then teams and billing. - Source: https://www.buildbase.app/guides/buildbase-on-vite - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-25 - Updated: 2026-11-04 ### In short To add authentication to a Vite React app with BuildBase, send users to hosted sign-in, then swap the returned code for a session in a small serverless function, since the exchange needs a client secret the browser must never see. It sets an httpOnly cookie. After that, teams, roles and billing are SDK calls. The shadcn-admin repo has [a discussion thread](https://github.com/satnaing/shadcn-admin/discussions/85) asking how to add real authentication. The maintainer's answer is fair: you need a backend. The thread ends there, and every Vite auth tutorial takes one of two exits. Keep the token in the browser, or go build that backend. There is a smaller answer. A Vite app does not need a backend to hold a session safely. It needs **three functions**, each a plain `Request -> Response` handler, the longest under twenty-five lines: exchange the code, report the session, sign out. The same three run inside `vite dev` and as serverless functions in production. After that, the teams, roles and plans you actually wanted are hooks. We know it holds because we did it to [shadcn-admin](https://github.com/buildbase-app/examples/tree/main/admin-dashboard) itself: a 14k-star template whose sign-in and team pages were all mock-ups until then. > **Before you start:** A Vite + React app, a BuildBase organization, and an auth client created in > the console under **User Management → Authentication**, with its client ID > and secret. Register `http://localhost:5173/sign-in` on the client as a > redirect URL, and your deployed `https:///sign-in` later. > **Tip:** **Start from the working example.** > [`admin-dashboard`](https://github.com/buildbase-app/examples/tree/main/admin-dashboard) > in the examples repo runs everything on this page in shadcn-admin. [Watch it > working](https://github.com/buildbase-app/examples/tree/main/admin-dashboard#see-it-working), > or copy it with `npx degit buildbase-app/examples/admin-dashboard my-app`. ### 1. Split the variables: four for the browser, one for the server ```bash npm i @buildbase/sdk ``` ```bash # .env.local VITE_BUILDBASE_ORG_ID=demo-org-id VITE_BUILDBASE_CLIENT_ID=demo-client-id VITE_BUILDBASE_REDIRECT_URL=http://localhost:5173/sign-in BUILDBASE_CLIENT_SECRET=demo-client-secret # no VITE_ prefix, ever # VITE_BUILDBASE_SERVER_URL defaults to https://api.console.buildbase.app # VITE_BUILDBASE_ENVIRONMENT: a development or staging key; unset is production ``` This split is the whole design. Vite inlines anything prefixed `VITE_` into the bundle, which is fine for an org ID and a client ID and fatal for a secret. So the secret goes without the prefix, and only server code reads it. ### 2. Write the three handlers One file, no framework. Each export takes a `Request` and returns a `Response`, a shape most serverless platforms accept and the Vite dev server can be made to speak. ```ts // server/auth.ts import { environmentId } from '@buildbase/sdk'; const env = (name: string) => process.env[name] ?? ''; const serverUrl = () => env('VITE_BUILDBASE_SERVER_URL') || 'https://api.console.buildbase.app'; // The same name `buildbase init` writes. A development or staging environment // gets its own cookie, so two builds on one host never read each other's. const environment = env('VITE_BUILDBASE_ENVIRONMENT'); const SESSION_COOKIE = environment && environment !== 'production' ? `bb-session-id-${environment}` : 'bb-session-id'; function cookie(value: string, maxAge: number) { const secure = env('NODE_ENV') === 'production' ? '; Secure' : ''; return `${SESSION_COOKIE}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`; } /** POST /api/auth/token: swap the hosted page's one-time code for a session. */ export async function token(request: Request): Promise { const { code } = await request.json().catch(() => ({})); if (!code) return Response.json({ error: 'Missing code' }, { status: 400 }); const res = await fetch(`${serverUrl()}/api/v1/auth/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, // - in a development or staging environment. orgId: environmentId(env('VITE_BUILDBASE_ORG_ID'), environment), clientId: env('VITE_BUILDBASE_CLIENT_ID'), clientSecret: env('BUILDBASE_CLIENT_SECRET'), }), }); if (!res.ok) return Response.json({ error: 'Sign-in failed' }, { status: 401 }); const { data } = await res.json(); return Response.json( { sessionId: data.sessionId }, { headers: { 'Set-Cookie': cookie(data.sessionId, 60 * 60 * 24 * 30) } } ); } /** GET /api/auth/session: lets the app find its session after a reload. */ export function session(request: Request): Response { const value = (request.headers.get('cookie') ?? '') .split(/;\s*/) .find((part) => part.startsWith(`${SESSION_COOKIE}=`)) ?.slice(SESSION_COOKIE.length + 1); return Response.json({ sessionId: value ? decodeURIComponent(value) : null, }); } /** POST /api/auth/signout */ export function signout(): Response { return Response.json( { ok: true }, { headers: { 'Set-Cookie': cookie('', 0) } } ); } ``` The 30-day cookie matches BuildBase's [default session length](/guides/token-expired-mid-request). The route names and the `bb-session-id` cookie are the ones `npx buildbase init` writes, for Next.js and for Vite, so a page that says `/api/auth/token` means this handler. The names only have to agree between these handlers and the provider in step 4. ### 3. Serve them from `vite dev` and from production In production, on Vercel, each handler is a one-line function file: ```ts // api/auth/token.ts import { token } from '../../server/auth'; export const POST = token; ``` `api/auth/session.ts` exports `GET = session` and `api/auth/signout.ts` exports `POST = signout`. Locally, a Vite plugin answers the same three paths, so `npm run dev` needs nothing else running: ```ts // vite.config.ts import react from '@vitejs/plugin-react'; import { defineConfig, loadEnv, type Connect, type Plugin } from 'vite'; import * as auth from './server/auth'; const routes = { 'POST /api/auth/token': 'token', 'GET /api/auth/session': 'session', 'POST /api/auth/signout': 'signout', } as const; const authMiddleware: Connect.NextHandleFunction = async (req, res, next) => { const name = routes[`${req.method} ${req.url?.split('?')[0]}` as keyof typeof routes]; if (!name) return next(); const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); const response = await auth[name]( new Request(`http://localhost${req.url}`, { method: req.method, headers: req.headers as Record, body: req.method === 'GET' ? undefined : Buffer.concat(chunks), }) ); res.statusCode = response.status; response.headers.forEach((value, header) => res.setHeader(header, value)); res.end(await response.text()); }; const buildbaseAuth = (): Plugin => ({ name: 'buildbase-auth', configureServer: (server) => void server.middlewares.use(authMiddleware), configurePreviewServer: (server) => void server.middlewares.use(authMiddleware), }); export default defineConfig(({ mode }) => { // Let the handlers read the secret from process.env, as a function would. Object.assign(process.env, loadEnv(mode, process.cwd(), '')); return { plugins: [buildbaseAuth(), react()] }; }); ``` Run `npm run dev` and open `http://localhost:5173/api/auth/session`. You should see `{"sessionId":null}`: the server half is alive before any UI exists. What we have run end to end is the `vite dev` path, against a real BuildBase org on a local stack. The Vercel function files follow Vercel's docs, but we have not yet tested a fresh Vercel deploy, or Netlify, or Cloudflare. Since the handlers are plain `Request -> Response`, we expect each host to need a similar one-line wrapper. The snippets here are trimmed from the example's files. The example is the tested version, so copy from it when the two disagree. ### 4. Wrap the app in the provider ```tsx // src/context/buildbase-provider.tsx (`npx buildbase init` writes the same file as src/buildbase-provider.tsx) import '@buildbase/sdk/css'; import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; let cached: string | null | undefined; export async function getSession(): Promise { if (cached === undefined) { const res = await fetch('/api/auth/session'); cached = ((await res.json()) as { sessionId: string | null }).sessionId; } return cached ?? null; } export function BuildBaseProvider({ children }: { children: React.ReactNode }) { return ( { const res = await fetch('/api/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); cached = ((await res.json()) as { sessionId: string }).sessionId; return { sessionId: cached }; }, onSignOut: async () => { await fetch('/api/auth/signout', { method: 'POST' }); cached = null; }, }, }} > {children} ); } ``` `getSession` asks the server once per page load and caches the answer, so route guards can call it freely. A button calling `signIn()` from `useSaaSAuth()` now goes to the hosted page, which offers whichever sign-in methods your org has on, and comes back to `/sign-in` signed in. ### 5. Guard routes, and remember where people were going The hosted page always returns to the one URL you registered, never to the page someone originally asked for. So remember it yourself. The example uses TanStack Router, and its guard is five lines: ```ts // src/routes/_authenticated/route.tsx beforeLoad: async ({ location }) => { if (!(await getSession())) { throw redirect({ to: '/sign-in', search: { redirect: location.href } }); } }, ``` On `/sign-in`, save that `redirect` value to `sessionStorage` right before calling `signIn()`, and navigate to it once `isAuthenticated` turns true. Open `/users` signed out, sign in, and you should land back on `/users`, not the home page. Any router works the same way; only the guard's syntax changes. ### 6. Then teams, roles and plans are hooks This is where the mock pages became real, and none of it needed another server function: - **The team switcher** lists the user's workspaces from `useSaaSWorkspaces()`, and **Add team** creates one. The SDK only fetches that list when asked, so the example calls `fetchWorkspaces()` once per sign-in and selects the first. - **The Users table** of 500 generated people became the workspace's real members: admins add people, move them between the admin, editor and viewer roles, and remove them. Everyone else sees it read-only. - **Profile, Account and Notifications** forms that saved nowhere became one Account page opening the SDK's own screens: profile, security, devices, notifications, workspace, plan, usage and feature flags. For the depth on each, the guides are [workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon), [enforcing quotas in React](/guides/enforcing-quotas-in-react) and [why an invited member cannot see the workspace](/guides/invited-member-cannot-see-workspace). If your app has a server of its own after all, [BuildBase on Next.js](/guides/buildbase-on-nextjs) covers reading the session in server components, [BuildBase on React Router](/guides/buildbase-on-react-router) keeps your own cookie session and loaders, [BuildBase on Express](/guides/buildbase-on-express) keeps Passport and `req.user`, [BuildBase on NestJS](/guides/buildbase-on-nestjs) swaps Passport and JWTs for one guard that `RolesGuard` never notices, [BuildBase on Fastify](/guides/buildbase-on-fastify) puts sign-in behind a decorator your tests can fake, [BuildBase on Hono](/guides/buildbase-on-hono) runs one server on Workers, Bun, Deno and Node, [BuildBase on TanStack Start](/guides/buildbase-on-tanstack-start) plugs into better-auth without replacing it, and [BuildBase on Astro](/guides/buildbase-on-astro) gates every page and endpoint on a workspace role from one middleware. > **Key takeaway:** A Vite app needs three small functions, not a backend. Once the session is an > httpOnly cookie, everything else is a hook. ### What breaks, and how you can tell **Sign-in works, then every reload signs you out.** The session route is not being served. In dev the plugin is missing from `plugins`; in production the function files are not where your host looks for them. Open `/api/auth/session` directly: you should get JSON, not `index.html`. **You get `index.html` back from `/api/auth/token` in production.** A catch-all rewrite for client-side routing is swallowing the API. Exclude `/api/` from it; the example's `vercel.json` rewrites only non-API paths. **The hosted page will not return to your app.** The redirect URL must match a registered one exactly, `/sign-in` path included. A wildcard can stand in for one leftmost subdomain on a domain you own (`https://*.app.example.com/...`), but not for a public suffix, so `*.vercel.app` is refused: register each preview domain you use. **A new teammate never gets in.** Invite them by email: `inviteMember(workspaceId, email, role)` from `useSaaSWorkspaces()` (SDK 0.0.71 and later) reaches an address with no account yet. The email's link lands on your redirect URL, the person signs in or registers there, and the SDK shows the accept dialog. Adding someone who already has an account in your org still works as before. **The team switcher is empty, or Add team does nothing.** An override turned off auto-creation, or the org is in Personal mode, where Add team is disabled. In the console's workspace settings, choose Platform mode; under Advanced Overrides, check that Auto-Create First Workspace is on and Can Invite Members is not Disabled. ### Install Add the SDK to your own app, or start from the example with `npx degit buildbase-app/examples/admin-dashboard my-app`. ```bash npm i @buildbase/sdk ``` --- ## How to add passkeys in Next.js > Every passkey tutorial has you writing four WebAuthn route handlers. This one has you writing none, and making one near-permanent decision instead: which domain runs the ceremony. - Source: https://www.buildbase.app/guides/passkeys-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-23 - Updated: 2026-11-04 ### In short Passkeys are one of the sign-in methods you toggle on in the BuildBase dashboard, so there is no WebAuthn ceremony to write in Next.js. The decision that does fall to you is which domain hosts your auth pages: WebAuthn binds every passkey to that hostname, and changing it later stops existing passkeys working. The passkey tutorials all teach the same four route handlers: registration options, registration verify, authentication options, authentication verify. They are not wrong. But on BuildBase you will write none of them, and the thing that actually costs you something is a decision those tutorials never raise. Which domain runs the ceremony. WebAuthn binds a credential to the hostname it was created on. Not to your app, not to your API, to the exact host the browser saw when the user touched the sensor. Get that wrong and you find out months later, when you move your auth pages and every passkey your users registered stops being offered at once. > **Before you start:** A BuildBase organization with passkeys enabled, and your auth domain settled > before anyone registers a credential. The `redirectUrl` below has to be > registered in your client's redirect URLs as a full URL, same as every other > method. Testing your app on localhost is fine: the ceremony runs on the auth > domain, not on your app, so localhost never ends up inside a passkey. ### What you are building A sign-in button that offers a passkey to people who already have one, and a settings screen where they can see what they have and remove what they do not recognise. When it works, a returning user taps sign in, the browser offers a credential it is already holding, and they are back in your app without a password field ever rendering. The Next.js code is short. Most of this guide is the part that is not code. ### Step one: turn passkeys on Passkeys are one of the sign-in methods in the BuildBase dashboard, and enabling them is a toggle rather than a code change. The hosted portal renders whichever methods your organization has on, which is why there is no `signInWithPasskey()` in the SDK. There is one `signIn()`, and the portal decides what to offer. Under the hood the server runs `@simplewebauthn/server` v13. You never import it. Worth knowing it is there the first time a WebAuthn error turns up in your logs. What you should see: open your auth portal URL in a private window and the sign-in screen offers a passkey option alongside whatever else you have enabled. ### Step two: settle the auth domain before anyone enrols This step is out of order in every other guide, because in every other guide you own the ceremony and can move it later. Here you do not, and that is mostly a good thing. BuildBase runs the ceremony on your organization's auth domain, either your custom domain or the platform default. The relying party ID is that hostname, read straight off the auth base URL. So the credential your user creates says, permanently, that it belongs to that host. Change the auth domain afterwards and the browser will not offer those credentials, because as far as it is concerned they belong to a different site. The server expects this rather than pretending otherwise. Every passkey stores the `rpId` it was registered under, and when your app lists a user's passkeys each one comes back with an `active` flag comparing its stored `rpId` against the current auth domain. An inactive passkey is not corrupt. It is a perfectly good credential for a domain you stopped using. > **Key takeaway:** Pick the auth domain you intend to keep before you let anyone register a > passkey. It is the one auth decision here that is genuinely expensive to > reverse, because reversing it means asking every user to enrol again. Moving from the platform default to a custom domain counts as a change. If you want your own auth domain, set it up and get it verified before you turn passkeys on, not after your first users have enrolled. ### Step three: wire the provider and the sign-in call Nothing here is passkey-specific, which is the point. ```tsx // app/providers.tsx 'use client'; import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; export default function Providers({ children }) { return ( localStorage.getItem('sessionId'), handleAuthentication: async (code) => { const res = await fetch('/api/auth/token', { method: 'POST', body: JSON.stringify({ code }), }); const data = await res.json(); return { sessionId: data.sessionId }; }, onSignOut: async () => localStorage.removeItem('sessionId'), }, }} > {children} ); } ``` Then the button: ```tsx 'use client'; import { useSaaSAuth } from '@buildbase/sdk/react'; export default function SignInButton() { const { signIn, isLoading, isAuthenticated } = useSaaSAuth(); if (isLoading) return ; if (isAuthenticated) return null; return ; } ``` `localStorage` is in that snippet because it is one line and it reads clearly. It is also readable by any script on your page, so if the app touches billing or personal data, [move the session ID to an HttpOnly cookie](/guides/buildbase-on-nextjs) set by `/api/auth/token` and have `getSession` read it server-side. What you should see: a click takes you to the portal, the browser raises its own passkey prompt, and you come back to `/dashboard` with `isAuthenticated` true. ### Step four: give people somewhere to manage them Passwords have a reset flow. Passkeys have a list, and a user who has lost a device needs to reach it. ```tsx 'use client'; import { useSaaSAuth } from '@buildbase/sdk/react'; export default function SecurityLink() { const { openWorkspaceSettings } = useSaaSAuth(); return ( ); } ``` The `security` screen shows each passkey a user holds, flags any registered on an old auth domain as inactive, and will not remove the one that is their only way to sign in. The sessions they are signed in on are on the `devices` screen. Adding one happens at sign-in. If you are building your own UI instead, the session-authenticated endpoints under `/api/v1/public/passkeys` list, rename and remove. Registration is deliberately not among them. A registration call made from your app's domain would mint a credential bound to your app rather than to your auth domain, which is the failure in step two arriving by a side door, so enrolment stays on the hosted pages. ### The failure modes **The prompt expires.** The challenge is stored for 5 minutes and consumed atomically, so it answers exactly once. Someone who starts signing in, gets pulled into a meeting and comes back at minute eight sees an expired-challenge error. There is nothing to fix and nothing to log. Just make the retry obvious rather than showing a generic failure. **A user cannot tell two of your workspaces apart.** On the shared auth domain every organization uses the same relying party, so someone who belongs to two of them would otherwise see two identical rows in the browser's passkey picker, both reading their email address. Passkeys are therefore labelled with a real host taken from the organization's redirect URLs, which turns the picker entry into `you@example.com · app.example.com`. If your redirect URLs are all localhost, private network addresses or wildcards there is no host worth showing, and the label falls back to the bare email. That is a reason to register your production URL early rather than the week you launch. **The domain moved and nobody said so.** Covered above, but it is worth being concrete about the user's experience: they open sign-in, the browser offers nothing, and there is no error because from the browser's point of view nothing went wrong. The pre-built security screen marks those passkeys inactive; if you built your own, read the `active` flag and do the same rather than leaving people to guess. **User verification is preferred, not required.** A device without biometrics can complete the ceremony on presence alone. So a successful passkey sign-in proves possession of the device, and does not by itself prove who was holding it. Worth knowing before you describe the property to anyone. ### What this does not give you A passkey replaces the password. It does not stack on top of one, so if a security review asks for a second factor, the answer to hand them is two-step sign-in: an authenticator app with backup codes, or text-message codes if you allow them, which you can make required for the whole app. The authenticator app is the stronger of the two. A passkey sign-in where the device checked a PIN or biometric already counts as both steps there, so it is not asked for a code. What passkeys do give you is phishing resistance, which is a different property and often the more useful one, because there is no code for anyone to talk a user into reading out. Sessions behave the same as with any other method: 30 days by default, capped at 180 days. A role change that seems not to apply catches people out across every auth method, and [has its own guide](/guides/permission-change-not-taking-effect). ### Related If you want the convenience without the hardware, [magic link](/guides/magic-link-login-nextjs) is the other passwordless method in the same toggle list, and a user can have both. If the redirect comes back and bounces you straight to sign-in again, that is [the middleware redirect loop](/guides/nextjs-middleware-redirect-loop-after-login) rather than anything to do with passkeys. ### Install ```bash npm i @buildbase/sdk ``` --- ## Session cookie not shared across subdomains > Signed in on app.example.com, signed out on admin.example.com. An attribute-by-attribute audit of the Set-Cookie header that decides it. - Source: https://www.buildbase.app/guides/session-cookie-not-shared-across-subdomains - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-23 ### In short A session cookie fails to cross subdomains for one of five reasons, and Domain is only the first. Omit Domain and the cookie is host-only. Path defaults to a directory, not to slash. SameSite is almost never the cause. And on vercel.app no Domain value works at all. You are signed in on `app.example.com`. You open `admin.example.com` and you are signed out. Same browser, same tab group, one `Set-Cookie` that the second host never receives. Five attributes on that header decide whether it crosses, and usually exactly one of them is wrong. None of them fail loudly. A cookie the browser refuses is not a console error, it is a row missing from a table you were not looking at. Before the audit, settle who wrote the header. If you are on BuildBase, we did not. `res.cookie(` appears nowhere in the tenant server or the central server, and two unit tests exist only to keep it that way - `server/test/unit/cookie-auth.test.ts` and `central-server/test/unit/18-cookie-auth.test.ts` both walk every source file and fail if one shows up. The SDK carries the session as an `x-session-id` header instead, and your `getSession` callback decides where that id lives. So the cookie is yours. Which means every attribute below is a value you picked, including the ones you picked by leaving out. ### The audit | Attribute | What it looks like in devtools when it is wrong | What it does, quietly | | ---------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `Domain` | the column is blank, or shows the exact host | Host-only. The cookie is fine, and the sibling subdomain simply never gets sent it | | `SameSite` | `None` on a cookie you only use across your own subdomains | Nothing you wanted. It forces `Secure` and opts you into third-party cookie blocking you did not need | | `Secure` | unchecked, or checked while you test against a LAN IP | Over plain http off localhost the browser drops the whole header and stores nothing | | `Path` | `/api/auth` where you expected `/` | Sent only under that prefix. `Domain` can be perfect and `/dashboard` still sees nothing | | `HttpOnly` | checked, and `document.cookie` comes back empty | Nothing at all to sharing. It is why your console check is lying to you | | `__Host-` prefix | the row is not in the table | The browser rejected the cookie entirely, because `__Host-` forbids `Domain` | Open Application, then Cookies, and click the subdomain that is signed out rather than the one that works. Half of these are only visible from the host that is failing. ### `Domain`: the attribute you get wrong by leaving out Omit `Domain` and you get a host-only cookie. It is stored, it is sent back to the exact host that set it, and it is invisible to every sibling. That is the default, and it is the single most common version of this bug. The leading dot is a distraction. RFC 6265 strips it, so `Domain=.example.com` and `Domain=example.com` produce the same cookie with the same scope, and Chrome renders the dot back to you either way. The question is never which spelling. It is whether the attribute is there. Our consent cookie is the one place in this repo that writes a domain-scoped cookie, and it decides conditionally: ```ts // packages/ui/src/components/analytics/consent.ts const APEX = 'buildbase.app'; function cookieDomain(): string { if (typeof window === 'undefined') return ''; const host = window.location.hostname; return host === APEX || host.endsWith(`.${APEX}`) ? `.${APEX}` : ''; } ``` That comparison is deliberately against a literal apex rather than a derived registrable domain, so a self-hosted tenant never gets a cookie written up to their own apex by our code. It also means the domain is a constant in source. There is no `COOKIE_DOMAIN` variable anywhere in this repo, and grep for one returns nothing, because nothing on our side needs it. If you reach for an env var in your own app, know what an unset one costs here. Our environment notes document the trap: the heredoc in `docker-server.yml` is the allowlist, `env_file` forwards the whole `.env`, and a variable the code reads but the heredoc omits is not "using its GitHub value". It is unset, and it falls back to the default. An unset cookie domain does not throw. It writes a host-only cookie, and your admin subdomain is signed out in production and nowhere else. One more thing about `Domain`, and it is the part that wastes an afternoon: a host-only expiry does not delete a domain-scoped cookie. Widen the scope, reload, and you now have two same-named cookies at two scopes, whose read order is not well defined. Our consent cookie went from `v1` to `v2` partly for this reason, and the code still clears the legacy names at both scopes on every write. > **Warning:** Scoping a session cookie to the apex means every subdomain can read it, > including ones you do not control - a marketing host on a vendor, a status > page, a stale CNAME someone pointed at a third party. The cookie-auth test > names this exact shape: a cookie written by any sibling host that the browser > would then attach to the API. ### `SameSite`: almost certainly not your problem `app.example.com` and `admin.example.com` are the same site. SameSite is computed on the registrable domain, not the origin, so `Lax` sends the cookie between your subdomains without complaint. If you arrived here from a forum thread telling you to set `SameSite=None`, that thread was answering a different question. `None` is for genuinely cross-site: two different registrable domains. It requires `Secure`, and it puts the cookie in the category Safari blocks and Firefox partitions by default. You trade a bug you have for a bug you cannot fix from your own code. We hit the real cross-site case and did not solve it with a cookie. The hosted sign-in pages sit on a different registrable domain from the app that sent the visitor there, so the consent answer written on the app is unreadable at sign-in. The comment on `IAuthData.trackingConsent` in `packages/shared/src/types/auth.ts` spells out the choice: carry the value in the auth state rather than in a cookie or a redirect URL, because a value in the URL is one the visitor can edit into a yes they never gave. ### `Secure`: the one that only breaks in one place `Secure` means https only, with one exception that saves you and one that catches you. Chrome and Firefox treat `http://localhost` as a trustworthy origin and will store a `Secure` cookie there. They do not extend that to a LAN IP. That matters more than it sounds if you test on a phone. Our own setup wizard supports `192.168.x.x` and LAN addresses on purpose, so the habit exists. A `Secure` cookie that works on localhost and works in production disappears the moment you load the same app from your laptop's LAN IP on another device, and the symptom is identical to the one you came here for. Also worth knowing in the other direction: `SameSite=None` without `Secure` is rejected outright. If you took the forum advice above and only did half of it, the cookie is not weakened, it is gone. ### `Path`: the default is not `/` `Path` is subdomain-independent, which is why it survives a `Domain` fix and keeps you stuck. The RFC default path is the directory of the request URI, not `/`. A `Set-Cookie` returned from `POST /api/auth/callback` with no `Path` defaults to `/api/auth`, and `/dashboard` never sees it. Express sets `Path` to `/` for you, which is why most people never meet this, but nothing in the spec requires that and anything hand-rolling the header certainly does not bother. Matching is by path segment: `Path=/admin` covers `/admin` and `/admin/x`, not `/administrators`. Set it to `/` and stop thinking about it. ### `HttpOnly`: not a sharing attribute at all `HttpOnly` changes nothing about which host receives the cookie. It changes whether `document.cookie` can see it, which is why it belongs in this audit: the reader debugging with `console.log(document.cookie)` gets an empty string and concludes the cookie was never set. > **Key takeaway:** `document.cookie` cannot see an HttpOnly cookie. An empty string in the > console is not evidence the cookie is missing. Check Application, then > Cookies, on the failing host instead. There is a structural version of this worth naming, and it is in our own repo: our hosted sign-in app sets `output: 'export'` in `website-auth/next.config.js`. A static export has no Node server, no route handlers and no middleware, so it cannot set an HttpOnly cookie on any attribute at all. It keeps its auth state in `localStorage` (`website-auth/src/services/axios/base.ts`) and sends the token in a header, which is the pairing the cookie-auth test argues for: a header credential is CSRF-safe because a cross-site page cannot set `Authorization`, and no API route in this codebase carries a CSRF token because nothing needs one. If your framework cannot write the header, no attribute table is going to help you. Find that out before you spend an hour on `Domain`. ### `__Host-` and `__Secure-`: a prefix that forbids what you want `__Host-` is incompatible with subdomain sharing by design. The browser accepts a `__Host-` cookie only when it is `Secure`, came from a secure origin, has `Path=/`, and carries no `Domain` attribute whatsoever. Add the `Domain` you came here to add and the cookie is refused. No error, no row in the table, and a name that looks like it should have worked. `__Secure-` is the prefix you want. It only requires the `Secure` flag and is perfectly happy with a `Domain`. We use neither today - grep for `__Host-` and `__Secure-` across the repo returns nothing, which follows from setting no cookies at all. Here is the shape if you are adding one yourself, in a Next.js route handler. `signIn` is your own function; the rest is as written. I have not run this against a deployment, because nothing in this repo sets a cookie to run it against: ```ts import { cookies } from 'next/headers'; // Your variable, not one of ours. Set it to example.com, no leading dot needed. const COOKIE_DOMAIN = process.env.SESSION_COOKIE_DOMAIN; export async function POST(req: Request) { const { sessionId } = await signIn(req); cookies().set('__Secure-app-session', sessionId, { domain: COOKIE_DOMAIN, // absent means host-only, and the sibling is signed out path: '/', // not the RFC default, set it explicitly httpOnly: true, secure: true, sameSite: 'lax', // already same-site: admin.example.com is example.com maxAge: 60 * 60 * 24 * 30, // 30 days, matching the platform session TTL }); return Response.json({ ok: true }); } ``` 30 days is the platform's own session lifetime - `SESSION_DEFAULTS.sessionTTL` in `packages/shared/src/constants/platform-stats.ts` - so a cookie that expires sooner will sign people out while the session behind it is still valid. That is its own confusing bug report. ### The one the attribute list cannot fix On `something.vercel.app`, no `Domain` value shares the cookie. Not `.vercel.app`, not `vercel.app`, not any spelling of it. `vercel.app` is on the Public Suffix List, alongside `github.io`, `pages.dev` and `netlify.app`. Browsers refuse to store a cookie scoped to a public suffix, because otherwise any preview deployment could write a cookie readable by every other customer's preview on the same host. The refusal is silent. You get exactly the symptom you came here with, and every attribute in the table above is already correct. Our own consent test asserts this host boundary directly - `buildbase.vercel.app` sits in the list of hosts where the cookie must stay host-only, next to `localhost` and a customer domain, in `packages/ui/tests/affiliate.test.ts`. We scope to our apex explicitly rather than deriving it, so the test is checking our code. The browser would enforce the same outcome regardless. The fix is a custom domain, and it is not a settings change on the cookie. Put both hosts under one registrable domain you own and the `Domain` attribute starts working again. Our production layout is exactly that. Five of the hosts listed in `packages/shared/src/constants/app-config.ts` are `console.buildbase.app`, `api.console.buildbase.app`, `central.console.buildbase.app`, `docs.buildbase.app` and `www.buildbase.app` - one registrable domain, so a single `Domain=buildbase.app` reaches every one of them. One footnote if you were planning to send that cookie to our API. The public SDK routes in `server/src/routes/v1/index.ts` send `Access-Control-Allow-Origin: *` and no `Access-Control-Allow-Credentials`, so a fetch with `credentials: 'include'` fails the CORS check by construction. A wildcard origin and credentials are mutually exclusive in every browser. Send `x-session-id`, which is already on the allowed-headers list next to `Authorization` and `x-org-id`. If you are still wiring the surrounding pieces, the whole Next.js setup, from the route handler that sets this cookie to the `getSessionId` that reads it, is in [BuildBase on Next.js](/guides/buildbase-on-nextjs). The workspace side of this is in [add multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon), the header-auth pattern shows up again in [enforcing quotas server-side](/guides/quota-enforcement-server-side-nextjs), and the argument for not hand-rolling any of it is in [the cost of building auth yourself](/blog/cost-of-building-auth-yourself). ### Install ```bash npm i @buildbase/sdk ``` --- ## How to add magic-link login in Next.js > Turning magic link on takes one toggle. The decisions that follow - session length, which browser opens the link, and deliverability - take longer. - Source: https://www.buildbase.app/guides/magic-link-login-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-21 - Updated: 2026-11-04 ### In short Magic link is one of the sign-in methods you toggle on in the BuildBase dashboard, so the Next.js side is the same signIn() call as any other method. The work is what follows: a 30-day session with no password behind it, and a link that often opens in a different browser than it was requested from. Magic link is the auth method people ask for last and enable first, because the demo is so good. No password field, no reset flow, no "must contain a symbol". The Next.js work is genuinely small. What follows it is not, and this guide is mostly about that: the link travels through email, which means it arrives in a browser you did not choose, at a time you did not pick, and there is no password behind it to re-establish who is holding the phone. > **Before you start:** A BuildBase organization with an email sender configured - Google, Mailgun or > custom SMTP. Magic link is an email delivery before it is an auth method, so > an org with no working sender has nothing to send. The `redirectUrl` below > also has to be registered in your client's redirect URLs, as a full URL. ### What you are building A sign-in button that sends an email, and a Next.js app that is authenticated when the user comes back from it. When it works, the round trip looks like this: the user clicks sign in, the portal takes their email, the inbox gets a message within a few seconds, and tapping the link returns them to your app signed in. ### Step one: turn it on Magic link is one of the sign-in methods in the BuildBase dashboard, and enabling it is a toggle rather than a code change. The hosted portal renders whichever methods are on for your organization. This is the part that surprises people, so it is worth stating plainly: there is no `signInWithMagicLink()` in the SDK. There is one `signIn()`, and the portal decides what to offer. What you should see: open your auth portal URL in a private window and the email field now offers a passwordless option alongside whatever else you have enabled. ### Step two: wire the provider The provider setup is the same one every BuildBase app uses. Nothing here is magic-link specific, which is the point. ```tsx // app/providers.tsx 'use client'; import { ApiVersion } from '@buildbase/sdk'; import { SaaSOSProvider } from '@buildbase/sdk/react'; export default function Providers({ children }) { return ( localStorage.getItem('sessionId'), handleAuthentication: async (code) => { const res = await fetch('/api/auth/token', { method: 'POST', body: JSON.stringify({ code }), }); const data = await res.json(); return { sessionId: data.sessionId }; }, onSignOut: async () => localStorage.removeItem('sessionId'), }, }} > {children} ); } ``` `localStorage` is in that snippet because it is one line and it makes the example readable. It is also readable by any script on your page. If the app touches billing or personal data, [move the session ID to an HttpOnly cookie](/guides/buildbase-on-nextjs) set by `/api/auth/token` and have `getSession` read it server-side. The [sessions reference](https://docs.buildbase.app/authentication/sessions-and-tokens) lays out the trade-off. What you should see: no errors on first render, and `useSaaSAuth()` resolving to `unauthenticated` rather than hanging in `loading`. ### Step three: the sign-in call ```tsx 'use client'; import { useSaaSAuth } from '@buildbase/sdk/react'; export default function SignInButton() { const { signIn, isLoading, isAuthenticated } = useSaaSAuth(); if (isLoading) return ; if (isAuthenticated) return null; return ; } ``` The argument to `signIn()` is where the user lands after the round trip. Pass it deliberately. The default sends them back to wherever they started, which is the wrong destination more often than you would expect - see the failure modes below. What you should see: a click takes you to the portal, an email arrives, and the link brings you back to `/dashboard` with `isAuthenticated` true. ### Step four: handle the return `handleAuthentication` is already in the provider config above. Its job is to take the auth code and exchange it for a session on your backend, and if it throws, the SDK leaves the user unauthenticated rather than half-signed-in. That failure is silent from the user's side. They tapped a link and ended up on a signed-out page. Render something in the `unauthenticated` branch of your callback route that says the link did not work and offers to send another, rather than showing a generic sign-in form that makes them think they imagined the whole thing. ### The failure modes These are the three that produce support tickets, in the order you will meet them. **The link opens in a different browser.** Someone requests it on a laptop and taps it in their phone's mail client. The phone is not signed in. The hosted pages finish the sign-in with state saved in the browser that asked, so the link only completes there; on the phone the page says to open it where it was asked for, and leaves it unused for the laptop. Tell people to open the link on the device they requested it from, on the screen that says the email is on its way, and make sending another link one click. Or have the method send a 6-digit code instead of a link, or both: a code can be typed on any device. **The email is slow, or not there.** Every other auth method fails loudly. This one fails by nothing happening, and the user's model of "nothing happened" is usually "the site is broken". Two things help: say the address you sent to on the waiting screen, so a typo is visible, and check spam placement before launch rather than after. [Transactional deliverability is its own subject](/guides/transactional-email-landing-in-spam), and magic link is the message where it matters most - a marketing email in spam costs an open, a sign-in link in spam costs the account. **The session outlives the intent.** The default is 30 days, configurable per session and capped at 180 days. With a password, a long session is a convenience; with magic link there is no credential to re-enter, and no second factor unless you turn on two-step sign-in, so the session length is the method's whole security posture. Pick it on purpose. If you are running anything that touches money, treat the 30-day default as a ceiling to argue down rather than a starting point. One more thing that is not a failure so much as a surprise: a role change that seems not to apply. The server enforces it on the next request; what lags is usually an open tab, or an API key's five-minute cache. That trips people up across every auth method, and [it has its own guide](/guides/permission-change-not-taking-effect). ### What this does not give you Magic link is a passwordless method, not a second factor. If your buyer's security review asks for one, set two-step sign-in to Required, and a magic-link sign-in is followed by a code from an authenticator app. SAML sign-in is enterprise SSO through your own WorkOS account, on the Enterprise plan only, so if the review asks for that, magic link is not the answer to it either. The full list of what is available is the sign-in methods in the dashboard, and it is worth reading before you promise anything: Email/Password, Magic Link, Email Code, Phone Code, Passkeys, [Google, LinkedIn, GitHub, Microsoft](/guides/social-login-nextjs), Apple, Custom OIDC, Ethereum Wallet, Solana Wallet and, on the Enterprise plan, Enterprise SSO. If the goal was phishing resistance rather than convenience, [passkeys are the method to reach for](/guides/passkeys-nextjs). They are in the same toggle list, and a user can have both. One thing to settle first, though: a passkey is bound to the hostname of the auth domain that created it, so that choice is much harder to reverse than this one. RemoteWait, our virtual queue product, runs on this auth stack, and queues are exactly the shape of product where passwordless helps: people sign in from a phone, once, in a hurry. ### Related If the redirect comes back and immediately bounces you to sign-in again, that is [the middleware redirect loop](/guides/nextjs-middleware-redirect-loop-after-login), not a magic-link problem. And once people are signed in, the next question is usually [which workspace they land in](/guides/multi-tenant-workspaces-in-an-afternoon). ### Install ```bash npm i @buildbase/sdk ``` --- ## Connection pool exhausted as org count grows > MongoNotConnectedError under load is usually LRU eviction, not a dead database. The arithmetic behind the 30-connection tenant window and where your own ceiling lands. - Source: https://www.buildbase.app/guides/connection-pool-exhausted-multi-tenant - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 ### In short MongoNotConnectedError under load is usually eviction, not a dead database. A tenant server holds at most 30 open tenant connections regardless of org count, so sockets stay bounded near 67 per API process while evictions grow with the number of orgs active in any five-minute window. Two lines show up in the tenant server log, usually a few minutes apart, and it is the second one that wakes someone up: ``` [MongoDB] Pool full (30), evicting LRU tenant MongoNotConnectedError: Client must be connected before running operations ``` The second error almost never names the org that caused it. It lands on some unrelated request that was mid-query on a connection the pool had just decided to close, which is why the first instinct is to go and check whether the database is up. It is up. You ran out of slots in a fixed-size window, and something else paid for it. So the useful question is not "is the pool exhausted", it is "at what org count does it become exhausted, and how far am I from that". That is arithmetic you can run today on your own numbers. > **Before you start:** These figures are the defaults in `packages/server-core/src/config.ts` for a > BuildBase tenant server running per-org MongoDB databases. The shape of the > arithmetic holds for any database-per-tenant system with a bounded connection > cache. The constants will be yours. ### The multiplication almost everyone runs first Orgs times connections per org. You have 500 orgs, `MONGO_ORG_POOL_SIZE` is 3, so the server wants 1,500 sockets and your database tier will not give you 1,500 sockets. Time to shard. That calculation is wrong, and it is wrong in the direction that makes people solve the wrong problem. Sockets are not what grows. ### The multiplication that actually runs The cap is on tenant _connections_, not on orgs. From `config.ts`, on API defaults: | Variable | Default | What it bounds | | ------------------------------ | ------- | ---------------------------------- | | `MONGO_CENTRAL_POOL_SIZE` | 5 | Sockets to the central database | | `MONGO_ORG_POOL_SIZE` | 3 | Base sockets per tenant connection | | `MONGO_ORG_POOL_SIZE_MIN` | 2 | Floor the base scales down to | | `MONGO_MAX_TENANT_CONNECTIONS` | 30 | Tenant connections held at once | | `MONGO_TENANT_IDLE_MS` | 300000 | Idle time before one is reaped | Workers get smaller numbers: central 2, base 2, floor 1. Same shape. The base does not stay the base. Every tenant connection is created with a pool size computed from how many tenant connections are already live, and the scaler is logarithmic: ```ts // Mirrors getTenantPoolSize() in // packages/server-core/src/database/mongo.ts. Pure arithmetic - paste it into // a scratch file with your own constants rather than trusting mine. const BASE = 3; // MONGO_ORG_POOL_SIZE const MIN = 2; // MONGO_ORG_POOL_SIZE_MIN function tenantPoolSize(liveTenantConnections: number): number { if (liveTenantConnections <= 1) return BASE; return Math.max(MIN, Math.floor(BASE / Math.log2(liveTenantConnections + 1))); } ``` Run it and the curve collapses almost immediately. At two live connections, `floor(3 / log2(3))` is 1, which clamps to the floor of 2. Every value above that clamps too. So connections one and two get 3 sockets each and connections three through thirty get 2. That gives one API process a hard ceiling of: ``` 5 central + 6 first two tenant connections at 3 + 56 remaining 28 tenant connections at 2 = 67 sockets ``` A worker process comes out at 34 by the same route. One API replica plus one worker is 101 sockets against your database, whether the deployment serves 30 orgs or 900. > **Key takeaway:** Adding orgs does not add sockets. `MONGO_MAX_TENANT_CONNECTIONS` caps the > tenant connection cache at 30 per process, so socket count is bounded at 67 on > API defaults no matter how many orgs exist. What grows with org count is the > eviction rate inside that fixed window. ### The number that does grow Call it A: the count of distinct orgs one process serves inside the idle window, which is five minutes by default. A is the number to measure, and it is not your total org count. It is your total org count divided across replicas, multiplied by how likely each org is to be active in any given five minutes. Three regimes, and you can tell which one you are in from the logs alone: - **A at or under 30.** Every org in the window is resident. No `Pool full` lines at all. The eviction sweep runs every 60 seconds and reports idle reaps, nothing more. - **A just over 30.** Occasional `Pool full` lines. The orgs that get evicted are the quiet ones, and when they come back they pay a cold connect. Users notice this as a slow first page after switching orgs. - **A well over 30.** Thrashing. The connection you evict to make room is one that another in-flight request is still holding, and that request dies with `MongoNotConnectedError` rather than anything that names an org or a pool. We hit the third regime on a laptop, not in production, and the numbers are in our verification runbook: 45,825 `Pool full` evictions in a single run at 163 orgs, with `MongoNotConnectedError` surfacing on requests that had nothing to do with the cause, including a failed database seed. 163 orgs against a 30-connection window should not produce forty-five thousand evictions. What produced them was a link redirector that did not know which org owned a link, so it asked all of them: one tenant query per org per click, and a full sweep on every miss. O(orgs) per redirect against a bounded pool. Any single code path that touches every org turns a comfortable A into a hostile one, and that path is usually something small that nobody thinks of as a tenant-heavy route. ### Where the ceiling lands Roughly 1,000 orgs per deployment is the documented connection-pool ceiling, and it is the number we plan against. But it is not the number that will bind you first. A deployment with 300 orgs, one API replica and a cron that walks every tenant is in trouble; a deployment with 900 orgs across enough replicas that each one holds fewer than 30 active at a time is not. Total orgs is the headline. A is the operational limit. ### The first symptom is latency, not an error Long before anything throws, org switching gets slow. Here is what a cold tenant connection costs, in order, from `mongo.ts`: 1. An org-existence check, served from Redis on a 5 minute TTL, or a central database lookup on a miss. 2. `mongoose.createConnection` against the tenant URL. 3. A wait for the connection to open, capped at 10 seconds, which fails as `Connection timeout for `. 4. An admin `ping` to validate it. All of that sits in front of the first query of the first request after an eviction. One user, switching orgs, sees a page that used to be fast take a second or two. Nobody files a bug for that. Then it gets worse in a way that does not look like a pool problem. The connection factory retries five times with a 5 second gap between attempts, and each of the six attempts waits out a 5 second server-selection timeout first, so a request against a tenant database that cannot be reached sits there for close to a minute before anything is raised. Meanwhile every other request on that process is fine. You get a p99 that climbs while p50 sits flat, which reads as a network blip, an overloaded replica, a bad deploy - anything except a fixed-size cache doing exactly what it was configured to do. Grep for these before you reach for a profiler: ```bash grep 'Pool full' server.log | wc -l # evictions under pressure grep 'Evicted .* tenant connections' server.log # the 60s idle sweep grep 'Creating tenant connection' server.log # cold connects ``` The third line is the one worth watching over time. A healthy process creates tenant connections at startup and then goes quiet. A thrashing one creates them forever. ### The number you set may not be the number you are running This one costs an afternoon if you do not know it. On the cloud deploy path, the heredoc in `.github/workflows/docker-server.yml` writes the `.env` that compose forwards into the container, and **that heredoc is the allowlist**. A variable with a line there is live. A variable the code reads but the heredoc omits is not using its configured value - it is unset, and the code falls back to its default. `MONGO_ORG_POOL_SIZE` has no line in that heredoc. Neither do `MONGO_ORG_POOL_SIZE_MIN`, `MONGO_MAX_TENANT_CONNECTIONS` or `MONGO_TENANT_IDLE_MS`. That is deliberate, and our environment notes say so: their defaults are right for cloud. But it means setting one in the environment and redeploying changes nothing at all, silently, and you will spend the next hour wondering why the eviction rate did not move. Do not trust the environment. The server prints what it is running, at startup: ``` [MongoDB] Central DB: Standard MongoDB (pool: 5) [MongoDB] Tenant DB pool: 3 per org ``` And every cold connect prints the scaled value in force at that moment: ``` [MongoDB] Creating tenant connection for org (pool: 12 active, poolSize: 2) ``` `poolSize: 2` there is the floor doing its job. If you expected 3 and see 2, nothing is broken. ### What actually moves the number **Lowering `MONGO_ORG_POOL_SIZE` barely helps.** It only applies to the first two tenant connections, so dropping it from 3 to 2 saves 2 sockets out of 67. The variable that governs 28 of the 30 is `MONGO_ORG_POOL_SIZE_MIN`. Take that to 1 and the API ceiling falls to 39. That is a real cut, and it costs you concurrency inside each tenant: one socket per org means two simultaneous queries for the same org queue behind each other. **Shorter idle reaping frees slots, not sockets.** `MONGO_TENANT_IDLE_MS` at 300000 with a sweep every 60 seconds means a quiet org holds a slot for up to five minutes after its last query. Cutting it to 60000 returns slots to the window faster, which lowers `Pool full` evictions of connections that are still in use. It does not lower peak socket count, and it buys more cold connects. On a workload with a long tail of rarely-active orgs this is the cheapest win available. On one where every org is active every minute it does nothing. **Raising `MONGO_MAX_TENANT_CONNECTIONS` trades sockets for evictions, linearly.** At 100 the ceiling becomes 207 sockets per API process. If your database tier has the headroom and A sits somewhere between 30 and 100, this is the correct fix and it is one line. Check what you have before you spend it: ```bash mongosh "$MONGO_CONNECTION_URL" --eval \ 'JSON.stringify(db.serverStatus().connections)' ``` `available` against your replica count is the budget. Spend it deliberately. **Past the ceiling, config stops being the answer.** Every knob above moves a constant. None of them changes the fact that one process can only cache so many tenant connections, and that a route touching every org will exhaust any window you give it. Two things actually change the slope: Remove the O(orgs) paths. The redirector above got fixed by giving links an owner index in Redis, `link-owner: -> orgId`, written at creation and backfilled on the rare sweep that still resolves one. Forty-five thousand evictions became a single key lookup. No pool setting was touched. Go find your equivalent: anything that iterates orgs to answer a request is a pool problem wearing a different hat. Then partition. Route each org consistently to the same replica so that a process's working set is a stable subset rather than a random sample of everything. The code already assumes this is where it goes - the comment above the scaler in `mongo.ts` reads "with org-sticky routing, each instance handles a subset of orgs, so fewer connections per org are needed". Sticky routing is what makes A a number you control instead of a number you observe. ### The trade you actually bought A database per org is not free and it was never sold as free. What it buys is isolation you cannot get wrong: a query that forgets its tenant filter has nothing else to find, because there is nothing else in the database. What it costs is a connection per active tenant, and connections are the one resource that does not scale by adding application memory. That is the trade. It is a good trade for a B2B product with hundreds of orgs and real isolation requirements, and a bad one for a consumer app with a million accounts. We picked it deliberately and we live with a connection ceiling because of it. The full cost breakdown is in [what database-per-tenant actually costs](/blog/database-per-tenant-cost), and the decision itself, including when a shared schema is the better answer, is in [database-per-tenant vs shared schema](/blog/database-per-tenant-vs-shared-schema). If you are earlier than any of this and just wiring up tenancy, start with [multi-tenant workspaces](/guides/multi-tenant-workspaces-in-an-afternoon) and come back to this page when the eviction lines appear. ### Install ```bash npm i @buildbase/sdk ``` --- ## An invited member who cannot see the workspace > The invite is parked in one of the states it passes through, and the admin console renders most of them identically. Walk the states, find yours, stop reading. - Source: https://www.buildbase.app/guides/invited-member-cannot-see-workspace - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 ### In short An invited user who cannot access a workspace is parked in one state of the invite: never sent, sent but silently skipped, accepted under a different address, or a member row written to one of the two places membership lives. Address mismatch is the most common. Org invitations expire after 14 days. Three strings bring people to this page. `User with email demo@example.com not found, ask them to sign up first`. `You are not allowed to accept this invitation`. And the worst one, a bare `401` with no body at all, returned by every route under a workspace the person was definitely added to. They are three different states of the same object. An invite moves through a sequence, and a member who cannot see the workspace is parked at one of the steps, not suffering from one generic problem with one generic fix. So walk the sequence. At each step, what the admin sees and what the invited person sees diverge in a specific way, and the first place those two accounts disagree is your answer. ### First, which invite is this There are two, they share a word, and they are not the same machine. **An organization invitation** is a control-plane object. It lives on central, at `/api/organizations/users/invitations`, it has a real status field (`INVITED`, `ACCEPTED`, `REJECTED`, `EXPIRED`), and it is how you get a colleague into the BuildBase console. **A workspace member** is a row in your own tenant database, created by `POST /api/v1/public/workspaces/:workspaceId/users/add`. This is the one your app's end users hit when they add a teammate to "Demo workspace". > **Key takeaway:** Workspace membership has no pending state. The add is synchronous: either the > person is a member when the request returns, or the request failed. Nothing is > waiting to be accepted, so "they haven't accepted yet" is never the answer on > that path. That single difference kills most of the states below for the workspace path. I will walk both and say which applies. ### State: sent **Org invitation.** The row is created with `status: INVITED` and `validTill` defaulted to 14 days out. That number is the model default and the `INVITE_VALIDITY_DAYS` constant in the invitations route, and the two agree on purpose. The invitations screen shows the row straight away. The invited person sees nothing yet. **Workspace add.** There is no sent. Before anything is written, the route looks the address up: ```ts const newUser = await UsersController.getInstance().findByEmail( orgId, req.body.email ); if (!newUser) { return res.notFound( `User with email ${req.body.email} not found, ask them to sign up first` ); } ``` If no account holds that address, the caller gets a 404 and nobody is contacted. Worth knowing what the wire message actually looks like: `res.notFound(entity)` renders `not found ${entity}`, so the body reads `not found User with email demo@example.com not found, ask them to sign up first`. The doubled phrase is the helper, not a bug in your parsing. Admin sees: a 404, immediately. Invited person sees: nothing, and never will. This state is loud, which is why it is rarely the one people are stuck in. ### State: delivered This is the first quiet one, and it is where a lot of "I invited them and nothing happened" actually lives. On central the invitation is created first and the email is fired afterwards, unawaited, with a rejection handler that returns undefined. The comment in the route is explicit about why: a relay that is down must degrade the notification rather than fail the request that made it. Sound call. The cost is that five separate conditions each return `false` and write nothing the admin can see: - BuildBase is not configured on that deployment - the organization has no workspace yet, which is normal until the owner's first switch, and is logged at info level - the workspace or the audience record cannot be resolved - the `org-invite-sent` notification event has not been created - the trigger call comes back non-2xx On the tenant side the workspace-added email runs a four-layer gate before it reaches the queue: the org-wide email switch, the event's own kill switch, the per-event channel default, and a workspace-level override when the event is user managed. Each returns false on its own. Then the mail worker has its own set of skips, and these ones at least leave a trace: `Audience member has unsubscribed`, `Audience member has invalid email`, `Audience member is blocked`, `User is blocked`, or `Unsubscribed from group `. Each writes a `SKIPPED` row into email history with the reason on it. Admin sees: a pending invitation, or a member who is already in the list. Nothing wrong anywhere. Invited person sees: an empty inbox. So, does a failed send leave the invite in a state the admin cannot see? Not quite, and the distinction matters. The invitation row is perfectly visible. It is the _failure_ that is invisible, because it happened in a promise nobody is holding. Your two places to look are the email history screen, filtered to SKIPPED, and the central log for a line beginning `[BuildBaseNotify]`. ### State: opened There is no opened state. Nothing records whether the message was read, for either path, and you should not go looking for a tracking field that does not exist. One thing worth checking before you blame the recipient, though. The workspace-added email has no accept link in it, because there is nothing to accept. The default template's subject is `You have been added to {{workspaceName}}` and the body says who added them and at what role. If your support reply is "ask them to click the link in the email," you are sending them to look for something that was never there. ### State: accepted Org invitations only. `PATCH /api/organizations/users/invitations/:id/accept` runs five checks in a fixed order, and the order is the diagnosis: 1. The invitation exists. 2. Its status is still `INVITED`. Anything else answers `Invitation already accepted/rejected/expired`. 3. `validTill` is in the future. If it is not, _this call_ is what flips the row to `EXPIRED` and answers `Invitation expired`. 4. The organization and the user both resolve. 5. `sameEmail(invitation.email, user.email)`. Failure here is `You are not allowed to accept this invitation`. Step three is the one that surprises people. Nothing sweeps expired invitations, so a row that timed out eight days ago still reads `INVITED` in the database and on the admin's screen. It expires at the moment somebody tries to use it. The invitee's own screen filters expired rows out, which is the right call for a list of things you can act on, and it is also why the admin sees a pending invitation that the invitee cannot find anywhere. The fix is resend rather than revoke-and-reinvite. Resending keeps the same row, the same inviter and the same role, and winds `validTill` forward 14 days from now rather than adding to a date already in the past. There is a five minute cooldown per invitation and a ceiling of sixty invitation emails per organization per hour, both of which answer with a 429 that tells you how long to wait. ### State: member created Now the workspace path gets interesting, because membership is stored in two places and they are written by two separate statements. `addUserToWorkspace` does step one, `$addToSet` the user id onto the workspace document's `users` array. Then step two, create the row in the `workspaces_users` junction collection. If step two throws, step one is rolled back with a compensating `$pull`, which is a sensible thing to do and is also itself a write against the same database that just refused one. It can fail too. Why does any of this matter to a person staring at an empty workspace switcher? Because the two records answer different questions: | Question | Read from | | ---------------------------------- | -------------------------- | | Which workspaces do I see? | the `users` array | | May I do anything inside this one? | the `workspaces_users` row | `getMyWorkspaces` filters on `users: { $in: [userId] }`. `isWorkspaceMember`, which every route under `/workspaces/:workspaceId/users` runs first, reads the junction. So the two possible splits produce two completely different symptoms: - **Junction row, no array entry.** Every API call inside the workspace works. The workspace never appears in their list. They can be handed a direct link and it functions, which makes this one look like a frontend bug for about a day. - **Array entry, no junction row.** The workspace appears in their list, and every request inside it returns a bare 401. Not a 403, not a message. `res.unAuthorized()` is `sendStatus(401)`, so there is no body to read and nothing in the response that tells you membership was the problem. Query both. If they disagree, that is the whole answer and no amount of role-checking will help. The org path has its own version of this. Accepting creates the membership row on central, and that is all it creates. The tenant user row does not exist until the person's first org-switch, which can be days later. Central is authentication and membership; the tenant database is authorization. Until they switch in at least once, they are a member of an organization with no presence in the database that would let them do anything. ### State: role assigned The inviter picks a role. Whether that role survives the trip depends on which path you are on. **Workspace.** The role has to be one the workspace defines, or the add is rejected before it writes: `Role editor is not valid, valid roles are admin, viewer`. Loud failure, easy to spot. **Org invitation.** Central stores a `tenantRole` string and forwards it verbatim, because it cannot read your tenant's roles and has no way to check it. The tenant decides at org-switch, and it applies the hint under two conditions: the role has to exist in that org's access controls, and only a brand-new local user can be seeded with it. An unknown name falls back to the membership tier. An API-kind role is treated exactly like an unknown one. So the invitation says `editor`, the console member list shows `editor`, and the person is signed in as a plain member because no role by that name exists in the tenant. Nothing errored. Nobody was told. ### State: permissions live Workspace permissions resolve in three steps, first match wins: `workspace.permissions[role]`, then the org-level template in `orgSettings.permissions[role]`, then the built-in `DEFAULT_WORKSPACE_PERMISSIONS[role]`, falling back to the `editor` list when the role has no entry of its own. That fallback is worth a second look if you have defined custom workspace roles. A role nobody wrote a permission list for does not end up with nothing; it ends up with whatever `editor` has, which may be considerably more than you intended. Meanwhile `viewer` holds exactly two permissions by default, `workspace:settings:view` and `workspace:members:view`, so a viewer who "cannot see billing or usage" is working correctly and needs a different role rather than a bug report. And the boring case, which is also a real one: everything above is correct and the change simply has not landed yet. `SESSION_DEFAULTS.permissionRefresh` is `hourly`. If you changed a role two minutes ago and the member's console has not noticed, wait, or have them sign out and back in, which re-reads the role on the way through. ### The two states that look identical from the admin side Here is the payoff. Both of these render as a healthy-looking member row with the right role next to it, and they need opposite fixes. #### Accepted, but the role never arrived Described above: the invitation carried a `tenantRole` the tenant does not have, or the person already had a local user row so the hint was ignored on purpose. Central's member list is showing you central's record of what was invited. The tenant's `users.role` is what the session actually carries. Tell them apart by asking the tenant rather than the console. The role in the member list is the intent; the role on the local user row is the outcome. When they differ, use change-role on the tenant side. Re-inviting will not fix it, and inviting somebody who is already a member is refused outright with `That person is already a member of this organization. Inviting them again does not change what they can do.` #### Accepted under a different address This is the one. In my experience it beats every other cause on this page combined, and it is invisible from the admin console by construction. Everything here keys on the email address. The address the account was created with is not always the address you invited, and nothing reconciles them. Central folds invitation addresses to lowercase on write and matches case-insensitively on read, and accounts are stored lowercased too, so capitalisation is genuinely handled. The comment in `central-server/src/utils/email.ts` records exactly what happened before that was true: an invitation to `Demo@Example.com` and the account `demo@example.com` were different strings to every query, the invitation did not appear on the invitee's screen, and the product behaved as though it had never been sent. Case is fixed. These are not: - **A plus tag.** `demo+team@example.com` reaches the same mailbox and is a different address everywhere in this system. The Mongo filter escapes the `+` rather than stripping it, deliberately, because an unescaped one would match addresses it has nothing to do with. - **A different provider account.** Console sign-in is OAuth, and the account is keyed on whatever address the provider returns, lowercased. Invite the work address, sign in with the personal account, and you have two accounts. - **An alias that forwards.** The mail arrives. The account is under the address it was actually created with, not the one that forwarded. Now the asymmetry, which is the reason this is so hard to see. The invitee's own screen lists invitations matching _their_ account's address. No match means an empty screen: not an error, not "this invitation is for someone else", just nothing to accept. The admin's screen lists invitations by organization, so it shows a perfectly healthy pending invitation to the address they typed. Both screens are correct. They are describing different rows. Pushing through by opening the accept endpoint directly gets you `You are not allowed to accept this invitation`, which is the only place in the whole flow that says the addresses do not match, and almost nobody reaches it. On the workspace path the same mismatch shows up earlier and, honestly, better: you get the 404 from `findByEmail` up front. The genuinely dangerous version is when the address _does_ resolve, to an account that is not the person you meant. Nothing asks you to confirm. Somebody is now a member of Demo workspace and it is not who you think. > **Warning:** Ask the person to read you the address on their account profile rather than > the one they think they signed up with. Comparing it to the invitation is a > ten-second check that settles this, and it is the check people skip because > they are certain they know the answer. ### A quick way to see which side is lying The two ends disagree, so read both ends. From the invited person's session, what comes back is the shortest signal available: ```tsx import { useSaaSWorkspaces } from '@buildbase/sdk/react'; export function MembershipDebug() { const { workspaces } = useSaaSWorkspaces(); // Empty, or missing the one they were added to, means the `users` array // on the workspace document does not contain their id. A workspace that // is listed but 401s on every call means the junction row is missing. return (
      {JSON.stringify(
        workspaces.map((w) => w._id),
        null,
        2
      )}
    
); } ``` I have not run that against a live server while writing this; it is the `useSaaSWorkspaces` shape from the canonical SDK snippet with a render swapped in, so treat it as a sketch rather than tested code. The other end is the event stream. `organization.member_invited` and `organization.member_accepted` are both webhook events and both Slack events. Subscribe to the pair and the invite stops being a black box: an invited with no accepted is parked before acceptance, and an accepted with a member who still cannot see anything moves the whole investigation to the tenant side. For the app path the equivalent is `workspace.member_added`, which fires from the add route itself, so its absence means the add never completed. ### What actually tends to be wrong Ordered by how often I have watched it happen, not by how interesting it is: 1. The address on the account is not the address on the invitation. 2. The email was skipped silently and the invitation is sitting there unseen. 3. The invitation expired at 14 days and still reads `INVITED` to the admin. 4. The two membership records disagree. 5. It has been ten minutes and permissions refresh hourly. Four of those five are invisible from the admin console. That is the real shape of this problem, and it is why "I invited them, it says pending, I don't know what else to tell you" is such a common place for this to stall. If you are building the workspace and membership model rather than debugging one, [multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon) covers the model itself, and [charging per seat](/guides/charge-per-seat-nextjs) covers the other reason an add gets refused: the seat cap, which returns a 402 with the current count and the limit on it rather than failing silently. ### Install ```bash npm i @buildbase/sdk ``` --- ## Middleware redirect loop after login in the App Router > Your middleware sees no cookie and 307s to /login. Your login page sees a session and bounces back. Traced hop by hop, plus the matcher and cookie rules that decide where it turns around. - Source: https://www.buildbase.app/guides/nextjs-middleware-redirect-loop-after-login - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 - Updated: 2026-11-04 ### In short ERR_TOO_MANY_REDIRECTS after sign-in means middleware and your login page are reading different storage. Middleware only sees cookies on the incoming request, so a session in localStorage is invisible to it. Fix the matcher so it cannot catch /login or the auth callback, and check the cookie, do not verify it. Chrome says `ERR_TOO_MANY_REDIRECTS`. The network tab shows the same two rows over and over, `307` on `/dashboard`, `200` on `/login`, `307` on `/dashboard`, until it stops at twenty hops and gives up. Sometimes the address bar never moves at all and the page just spins, with the repeating `307` chain hiding in the RSC requests instead. It is one loop with two symptoms, and the fix is not "add a check to the login page". The fix is realising that your middleware and your login page are reading two different things and each one is right about what it can see. Here is a single request, followed all the way around. ### Hop 1: GET /dashboard **What middleware saw:** an incoming request with a `Cookie` header that does not contain `bb-session-id`. **Why it decided that:** because it is true. The user signed in a second ago, but the session id went to `localStorage`, which is exactly what our own sessions doc shows as the first option: ```tsx callbacks: { getSession: async () => localStorage.getItem('sessionId'), // ... } ``` Middleware runs at the edge, on the request, before any of your JavaScript exists. It gets the URL, the headers, and whatever cookies the browser chose to send. That is the entire input. `localStorage` is not on the list and never will be, so the guard does the only thing available to it: ```ts return NextResponse.redirect(new URL('/login', request.url)); ``` `NextResponse.redirect` defaults to `307`. That is the first row in your network tab, and it is correct behaviour. Nothing has gone wrong yet. ### Hop 2: GET /login **What middleware saw:** `/login`, still no cookie. **Why it decided that:** depends entirely on your matcher, and this is the hop where half of all loops turn around. If your matcher is the negative-lookahead one every tutorial ships: ```ts export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], }; ``` then `/login` is inside it, the guard runs, finds no session, and redirects to `/login`. The loop is two rows long and both of them are `307`. That is the easiest version of this bug to spot and the fastest to fix. Assume your matcher does exclude `/login`, because otherwise you would have found it already. The page renders normally. The provider mounts, calls `getSession`, reads `localStorage`, and finds the session id hop 1 could not see. ### Hop 3: the login page bounces you back **What the page saw:** `isAuthenticated: true`, plus a `redirect` query parameter pointing at `/dashboard`. **Why it decided that:** because a login page that leaves a signed-in user staring at a sign-in form is a bug in its own right, so every login page grows this effect. Ours has it. The console's sign-in form reads the parameter, checks it is same-origin, and pushes: ```tsx const finalRedirect = new URL(redirectUrl, window.location.origin); if (finalRedirect.origin === window.location.origin) { router.push(finalRedirect.toString()); return; } ``` That is `client/src/components/auth/userAuthForm.tsx`, and there is nothing wrong with it. On its own it is right. Paired with a middleware that looks somewhere else for the same fact, it is the return leg of the loop. Which navigation it uses decides which symptom you get. `router.push` and `router.replace` are soft navigations: they fetch an RSC payload, middleware 307s that fetch, the router follows, and the address bar never changes. You get a spinner and a repeating chain in the network tab. Assigning to `window.location.href` is a hard navigation, the browser counts the hops itself, and at twenty you get `ERR_TOO_MANY_REDIRECTS`. Same loop. Different-looking bug report. ### Hop 4: GET /dashboard, again **What middleware saw:** the same request as hop 1. Same headers. Same absent cookie. Nothing in hops 2 or 3 wrote one, because nothing in hops 2 or 3 carried a `Set-Cookie` header. **Why it decided that:** it has no memory. Each invocation is a fresh function over one request. There is no "I already sent this person to /login once" state, which is precisely why the loop is infinite rather than self-limiting. Go back to hop 1 and repeat until the browser stops you. > **Key takeaway:** The loop is not two components disagreeing about whether you are signed in. It > is two components reading different storage and both reporting honestly. Find > the hop where the answer changes, and you have found which one is looking in > the wrong place. ### The state middleware does not have Client-side guards have three states: signed in, signed out, and not known yet. The console's `AuthProvider` opens with the third one: ```tsx useEffect(() => { if (isLoading) return; // ... if (!isLoggedIn && pathname?.startsWith('/dashboard')) { const destination = pathname + window.location.search + window.location.hash; router.replace(`/login?redirect=${encodeURIComponent(destination)}`); } }, [user, isLoggedIn, isLoading, pathname, router]); ``` `if (isLoading) return;` is the whole safety mechanism. While the session is resolving, the guard does nothing at all. Our protected-routes doc lists four patterns for gating a route and every one of them has this branch, whether it is `status !== 'loading'` or the `loadingComponent` prop. Middleware cannot have that branch. It has to answer on the request in front of it, and "not known yet" has to collapse into one of the other two. It collapses into "signed out". Then it redirects. That is not a flaw to be engineered around, it is the shape of the thing. Which leads to the three rules worth actually writing down. ### Rule one: the matcher is an allowlist, not a filter Matchers match the pathname. Not the query string, not the hash. A negative lookahead over the whole site is a filter you have to keep correct forever, and every route you add is a route you have to remember to exclude. Invert it: ```ts export const config = { matcher: ['/dashboard/:path*'], }; ``` One entry is enough: `:path*` means zero or more segments, so the pattern covers `/dashboard` itself as well as everything under it, and it does not catch `/dashboardx`. An allowlist cannot catch `/login`, because `/login` is not under `/dashboard`. It cannot catch your callback either. The bug is structurally unavailable. One trap if you build the matcher from a route constant. Our `CONSOLE_ROUTES` holds entries like `'/dashboard/admin/auth?tab=config'` because the console navigates straight to a tab, and a matcher carrying a `?tab=` on the end of it is not a pattern at all: path-to-regexp reads the `?` as a modifier and throws instead of compiling. Those are navigation targets, not matcher patterns. Match the path, then read the tab inside the function with `request.nextUrl.searchParams.get('tab')`. ### Rule two: the cookie is not readable on the hop that sets it Here is the callback route, the one that turns an auth code into a session: ```ts // app/auth/callback/route.ts import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; // The name `npx buildbase init` writes; bb-session-id- in a development // or staging environment. const SESSION_COOKIE = 'bb-session-id'; export async function GET(request: NextRequest) { const code = request.nextUrl.searchParams.get('code'); if (!code) return NextResponse.redirect(new URL('/login', request.url)); const res = await fetch('https://api.yourapp.com/api/auth/token', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code }), }); const { sessionId } = await res.json(); const response = NextResponse.redirect(new URL('/dashboard', request.url)); response.cookies.set(SESSION_COOKIE, sessionId, { httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production', path: '/', maxAge: 60 * 60 * 24 * 30, // the 30-day session default }); return response; } ``` Two things about that last block. `response.cookies.set` writes a `Set-Cookie` header. It does not put anything into `request.cookies`, not in this function and not in a middleware that does the same thing. If you set a cookie on a redirect response and then read it back in the same invocation, you read nothing. The browser stores it and sends it on the _next_ request, which is the earliest hop any edge code can see it. And if `/auth/callback` is inside your matcher, none of this runs. Middleware executes before the route handler, sees a request with no session cookie, returns its `307`, and the code is never exchanged. The user is now in a loop whose cause is a route that was never allowed to do its job. That is the nastiest version of this bug, because the broken thing and the visible thing are two different files. ### Rule three: check for presence, do not verify The temptation is obvious. You have the session id right there, so why not confirm it is real before letting the request through? Because of what a session id is. In our token catalogue the app session is an opaque handle against a Redis record with a 30-day TTL - there is nothing in the string to check locally, so verifying means a network call from the edge on every request, including every RSC payload and every `` prefetch. Then somebody writes the sensible-looking thing: ```ts try { await verifySession(id); } catch { return NextResponse.redirect(new URL('/login', request.url)); } ``` and now a timeout, a cold start or a deploy is indistinguishable from a user who never signed in. Every blip becomes the loop. Short-lived artifacts make it worse. `SESSION_DEFAULTS.tokenExpiry` is `2-minute`, and that is not the session, it is the handoff: the single-use, PKCE-bound code that carries a login across the redirect from the auth UI to the app. A middleware that tries to verify whatever token-shaped string it finds mid-flow will, on a refresh, be handed one that was already consumed. Verification fails. It redirects to `/login`. Login starts again. Presence is a routing decision and belongs at the edge. Validity is an authorization decision and belongs on the server that serves the data, where the answer to a bad session is `401` and not another `307`. The same split we argue for quotas in [enforcing quotas server-side](/guides/quota-enforcement-server-side-nextjs): the cheap gate up front, the real one where it cannot be skipped. ### The whole thing ```ts // middleware.ts, at the project root, next to app/ import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; // Same name as the callback sets; bb-session-id- in a development or // staging environment. const SESSION_COOKIE = 'bb-session-id'; export function middleware(request: NextRequest) { // Presence only. Whether the session is real is the API's answer to give. if (request.cookies.has(SESSION_COOKIE)) { return NextResponse.next(); } const login = request.nextUrl.clone(); login.pathname = '/login'; login.search = ''; login.searchParams.set( 'redirect', request.nextUrl.pathname + request.nextUrl.search ); return NextResponse.redirect(login); } export const config = { // An allowlist. /login and /auth/callback are not under /dashboard, so this // matcher cannot redirect to a path it also guards. `:path*` is zero or more // segments, so /dashboard itself is covered. matcher: ['/dashboard/:path*'], }; ``` I have not run this in this repo, and I want to be straight about why: there is no `middleware.ts` in it. Not in the console, not in the auth app, not on the marketing site. Seven apps, zero middleware files. The console guards `/dashboard` in a client provider with an `isLoading` branch, because it holds its session where only the client can read it. That is a choice, not a recommendation. Middleware is genuinely good at a cheap, cookie-shaped redirect for a signed-out visitor, and it saves you rendering a dashboard shell for someone who will never see it. It is bad at anything it has to ask another service about. If you take the code above, you are taking the first job and leaving the second one alone. ### Where your own loop turns around Walk your four hops and find the one where the answer changes. **The cookie is in Local Storage, not Cookies.** Open devtools, Application, and look at which panel the session id is in. If it is in Local Storage, hop 1 was always going to redirect. Either [move it to an `HttpOnly` cookie](/guides/buildbase-on-nextjs) in the callback route, or delete the middleware and guard in the layout. **Both rows are 307.** Your matcher covers its own redirect target. Look at `config.matcher` before you look at anything else. **The callback shows a 307 and no 200.** The handler never ran, so the session was never created. Take the callback path out of the matcher. **The cookie exists but arrives on the second request.** Check `sameSite`. With `strict`, a cookie is not sent on a navigation that started on another site, and the hop back from a separate sign-in domain is exactly that. This gives you one bounce, not an infinite loop - unless your login page bounces back, and then it is a loop after all. `lax` is the right default here. **The loop only happens in production.** Check the cookie `domain`. A cookie set on `app.example.com` is not sent to `example.com`, and a middleware running on the apex sees nothing. Localhost hides this completely, because everything is one host. **There are 307s before anyone clicks.** In a production build a `` prefetches as soon as it scrolls into view, and that RSC request goes through middleware and obeys the redirect. A redirected prefetch is one `307`, not the loop, but it tells you the guard is already answering "signed out" for that route before any navigation has happened. If you are wiring the guard for a workspace-scoped route rather than a flat `/dashboard`, the routing side of that is in [multi-tenant workspaces](/guides/multi-tenant-workspaces-in-an-afternoon), and the case for not hand-rolling the session layer at all is the arithmetic in [the cost of building auth yourself](/blog/cost-of-building-auth-yourself). ### Install ```bash npm i @buildbase/sdk ``` --- ## A permission change that has not taken effect yet > A role change in the console or SDK applies on the next request, API keys included. What lags is an open tab or a role written around the routes. Here is which. - Source: https://www.buildbase.app/guides/permission-change-not-taking-effect - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 - Updated: 2026-10-21 ### In short BuildBase enforces a role change in the console or SDK on the next request. Only an open tab lags, until refreshWorkspaces(). An org role change signs the person out. API keys are re-checked once their creator changes role, is blocked or is removed. A role written outside the change-role route waits on caches. If you changed the role through the console or the SDK, the server is almost certainly enforcing it already. Whatever still looks old is usually an open browser tab, or a role that was written without going through the route that tells everything else. The one lag inside the server is a five-minute API key cache, and every route that changes a key or the person who created it clears it, so it only shows when a change goes around them. An earlier version of this guide said "up to an hour" and blamed the copy of the role held in each session. That was wrong for anything an SDK call does. The session does carry a role, and `SessionService.getSession` does re-read it once `SESSION_REFRESH_INTERVAL = 60 * 60 * 1000` has passed. But nothing under `/api/v1/public` reads that copy back. What the hour still does is in [why a permission change no longer waits for the hourly refresh](/blog/why-permissions-refresh-hourly). This page is the checklist. > **Before you start:** You changed a role, or what a role may do, and something still behaves as > though you had not. Know which tier you touched. A workspace role says what > someone may do inside one workspace; an org role says who they are across your > whole app, and decides their console access. [What is > RBAC](/blog/what-is-rbac) covers why there are two. ### Which change did you make? Find your row, read its section, and stop when you find the cause. | You changed | Enforced from | Usually stuck in | | ------------------------------------------- | ----------------------------------- | -------------------------------------------------------- | | A workspace role | The next request | The open browser tab | | An org role, in the console | The next request, after a sign-in | Nowhere: the person was signed out | | What an org role can do (its grants) | One pub/sub message, 60 s at worst | Nowhere, unless you meant SDK calls | | An API token, or the person who created it | The next request | The token's cache, if you went around the routes (5 min) | | `users.role`, outside the change-role route | Whenever something re-reads the row | The profile cache and the console token | ### 1. A workspace role: the server has it, the tab does not This is the common one. And the server is not the side that is behind. The guards on the SDK's workspace routes, `requireWorkspaceMember` and `requirePermission` in `server/src/middleWares/workspaceGuard.ts`, look the member up in the `workspaces_users` rows on every request, with no cache in front. `bb.workspace.update`, for instance, sits behind `requirePermission(WorkspacePermission.SETTINGS_EDIT)`. Change someone's role with `bb.users.updateRole(workspaceId, userId, role)`, or from the members screen of the SDK's settings dialog, and the row is rewritten. Their next request is judged by the new role. Their open tab is not. `usePermissions`, `WhenPermission` and `WhenWorkspaceRoles` take the role from the workspace list the SDK loaded earlier, and nothing updates that tab's copy. Demote an editor to viewer and they keep seeing an editor's buttons, then get a 403 for clicking one. A promotion runs the other way: allowed, but shown nothing new. So before you go hunting, ask the server, signed in as the affected user: ```ts // check-role.ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); // Resolved by the server on this request, from the membership rows. const { role, isOwner, permissions } = await bb.workspace.permissions(workspaceId); console.log({ role, isOwner, canEditSettings: permissions.includes('workspace:settings:edit'), }); ``` `bb.workspace.permissions()` returns what the server enforces now. Then look at what the tab holds: ```tsx 'use client'; import { usePermissions, useSaaSWorkspaces } from '@buildbase/sdk/react'; export function RoleInThisTab() { const { role, isOwner } = usePermissions(); const { refreshWorkspaces } = useSaaSWorkspaces(); return ( ); } ``` Server says `viewer`, tab says `editor`? Found it. Call `refreshWorkspaces()` when the open tab is behind, or reload. Both snippets typecheck against `@buildbase/sdk` 0.0.82. I have not run them against a live API, so treat them as the shape of the check rather than a transcript. One answer is not a lag at all. If `isOwner` comes back `true`, this person created the workspace, and `assertWorkspacePermission` lets the creator through every permission the server knows about, whatever their membership row says. Demoting a workspace's creator changes the row and nothing they can do. Edits to the workspace permission matrix land the same way, on the next request. [Per-workspace roles in Next.js](/guides/roles-and-permissions-per-workspace-nextjs) walks through both sides, including where `refreshWorkspaces()` goes so a stale tab fails once instead of twice. ### 2. An org role, changed in the console: they were signed out Nothing is stuck. The person was signed out on purpose. The console's `PATCH /users/:id/change-role`, in `server/src/routes/users/index.ts`, ends with two calls: `SessionService.revokeUserSessions(orgId, user_id, 'role_changed')` and `markCredentialsChanged(orgId, user_id)`. Why two? Two kinds of credential. `revokeUserSessions()` deletes every SDK session the person holds, so the next call their app makes gets a 401 and the SDK fires `onSessionExpired`. Then the person signs in again, and the new session carries the new role. `markCredentialsChanged` stamps `credentialsChangedAt` on the user, and a console token minted before that instant gets a 401 with the code `CREDENTIALS_CHANGED`. The console handles that itself in `client/src/services/axios/base.ts`: it drops the token and reloads, which re-runs the org switch and mints a token carrying the new role. It does this on every change, promotions included. Promote someone to `admin` and they are signed out of every device too. For a demotion that is the point. For a promotion it buys nothing, since the stale copy was the smaller role. Now the case that sends people here. An SDK call still answers 403 after an org role change? Then the org role was never what decided it. The session gate in `server/src/routes/v1/public/index.ts` copies `session.user.role` into `req.tokenData.role`, and no route or middleware under `/api/v1/public` reads it back. SDK routes authorize on workspace membership and workspace permission, so go back to section 1. Where the org role does show up is the browser. `WhenRoles` reads it from the profile the SDK loads with the session, while `WhenWorkspaceRoles` reads the workspace list, and the docs on [conditional rendering](https://docs.buildbase.app/permissions/conditional-rendering) lay the two side by side. ### 3. What an org role can do: one message, on every instance Editing an org role's grants lands in the time a pub/sub message takes. Saving a role runs `setRolePermissions` in `accessControl.controller.ts`. It deletes the role's Redis entry, which otherwise lives `TTL.PERMISSIONS = 300` seconds, and calls `publishPermissionChange`. That clears the writer's own in-process `Map` directly and announces the change on `rbac:permissions:invalidate` so every other instance drops its copy too. A `Map` entry lives `AC_MEMORY_TTL`, 60 seconds, so a lost message costs a minute at most. Check who you expected to notice. These grants are read by `authenticate`, which guards the console's routes, reached with a console token or an API token. An SDK session never passes through it. If you edited an org role's grants to change what someone can do inside your app, the knob you wanted was the workspace permission matrix. ### 4. An API key: the next request, unless the change went around the routes `SessionService.validateApiToken` caches what it resolves about a key for 5 minutes (`TOKEN: 300` in `server/src/vendors/redis/domains/auth.redis.ts`): which role it acts as and whether its creator may still use it. Only the role's name is cached. The grants behind it are read per request, so section 3 applies to keys unchanged. On a cache miss the key is checked against its creator as they are now. A key issued with a role of its own is refused once that role is above its creator's current role ("API token role exceeds its creator's current role."), and works again if they get the role back. A key without a role of its own acts as its creator's live role. A blocked creator's keys are refused. The routes that change any of that clear the cache, so the change lands on the next request: - editing or deleting the token row (`tokens.controller.ts`) - changing the creator's role through `PATCH /users/:id/change-role`, which calls `refreshCreatorKeys` for every key they created - blocking the creator through `PATCH /users/:id/block`, which does the same - removing the creator from the org, which revokes every key they made (`revokeCreatorKeys`) What still waits for the entry to lapse, up to 5 minutes, is a change that reaches the creator's authority another way: narrowing the grants of a custom role they hold while their key names a broader one, or writing `users.role` by hand (section 5). ### 5. A role written around the route: this is where the hour lives A write to `users.role` that skips the change-role route revokes nothing. Those writes are real. The org switch seeds a role from an invitation, and it drops a former owner to `admin` after an ownership transfer (`server/src/routes/v1/auth/org-switch.roles.ts`). So can a migration, a script or a hand edit in a database shell. Three places can go on holding the old role: - **The session's copy.** Re-read once `SESSION_REFRESH_INTERVAL` has passed, which `SESSION_DEFAULTS.permissionRefresh` calls `hourly`. No SDK route reads it, so this one matters least. On a database error, `getSession` serves the cached session rather than failing the request, and tries again on the next. - **The profile.** `getMyProfile` sits behind a Redis entry that lasts 3,600 seconds, and writes through `UsersController.updateById` clear it. The org switch writes that way. A hand edit does not, so `WhenRoles` can show the old org role for up to an hour. - **The console token.** Nothing stamped `credentialsChangedAt`, so after a script or a hand edit a console token keeps its old role claim until the next org switch mints a new one, or its 7 days (`DEFAULT_TOKEN_EXPIRY`) run out. The fix is to change roles through the route, scripts included. Call `PATCH /users/:id/change-role` rather than writing to the collection, and the revocation comes with it. ### The case that must not wait: locking someone out now Block them. One step covers every credential they hold. Blocking (`PATCH /users/:id/block`) calls `SessionService.revokeUserSessions(orgId, user_id, 'user_blocked')` and `markCredentialsChanged`, the same pair as the change-role route, and drops the cached answer for every API token they created. Their SDK sessions are deleted, their console token is refused on its next request, and each key they made is refused on its next request ("Token creator is blocked."). There is no TTL to wait out, because there is nothing left to expire. The keys are refused only while they stay blocked: unblock them and the keys work again. If they are leaving for good, remove them from the org, which revokes every key they made, or delete the keys yourself. The hourly refresh is the backstop under all of this, not the mechanism. If a script blocks someone without going through the route, the next `getSession` past the hour reads the row, sees `blocked`, deletes the session and returns null. Removing someone from one workspace needs none of it: membership is read per request, as in section 1. If you are still deciding how much of this to own yourself, the tenancy model underneath it is in [database-per-tenant vs shared schema](/blog/database-per-tenant-vs-shared-schema), and the workspace layer these roles attach to is in [add multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon). If the thing you are gating is something the customer paid for rather than something a person's role allows, that is a different system: [entitlements are not feature flags](/blog/entitlements-are-not-feature-flags). ### Install ```bash npm i @buildbase/sdk ``` --- ## A 429 when the quota should not be exhausted > A 429 on the usage endpoint is almost never the quota, which answers 402 QUOTA_EXHAUSTED. How to reconcile the counter you read with the one being enforced. - Source: https://www.buildbase.app/guides/quota-429-not-exhausted - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 - Updated: 2026-10-22 ### In short The counter your dashboard reads and the counter enforcement increments are produced by two different code paths. A 429 on the usage endpoint comes from the rate limiter at 60 requests per minute per IP, not from the plan allowance. Quota rejection returns 402 with QUOTA_EXHAUSTED; bad input returns 400. The counter you are reading is not the counter being enforced. That sounds like a bug report, but it is the design, and once you see it the 429 stops being mysterious. Two different code paths produce the two numbers. `GET /usage/status` and `GET /usage/all` compute what the dashboard shows. `POST /usage` increments what the plan enforces. They read the same field on the same workspace document, and they still disagree, for about five reasons that are all legitimate. Start with the one that resolves most cases: **a quota rejection does not return 429.** It returns 402, with `code: 'QUOTA_EXHAUSTED'`, the `quotaSlug` and `resetsAt` beside the message. Every other failure on the usage route, a bad body, an unknown slug or a missing subscription, still answers 400. The quota side is covered in [enforcing quotas server-side](/guides/quota-enforcement-server-side-nextjs). So if you are holding a 429, something other than your plan allowance said no. > **Before you start:** A workspace on a plan version that defines the quota slug, and the ability to > read the raw HTTP response rather than only the SDK error. In `@buildbase/sdk` > 0.0.90 the SDK throws a plain `Error` carrying the server's message with the > status as `status`, but not the body's `code` (that arrives in the next SDK > release), so the code has to come from a fetch. ### The status code names the ceiling Three ceilings sit on the same request, and the status code with the body's `code` names each one. Anything else is a 400, which means the request itself was wrong: | Code | Body `code` | Who said no | Where it lives | | ---- | --------------------------------------------------------------- | ------------------ | -------------------------------- | | 429 | none | the rate limiter | `middleWares/rateLimit/index.ts` | | 402 | `QUOTA_EXHAUSTED` | the plan quota | `QuotaRefusalError` | | 402 | none on `/credits/consume`; `INSUFFICIENT_CREDITS` on the holds | the credit balance | `InsufficientCreditsError` | | 400 | none | the request | the usage route's catch block | The credits 402 is a separate system entirely, and its body names `available` and `requested`; only the hold routes (`/credits/reserve` and a hold's settle and release) add `code: 'INSUFFICIENT_CREDITS'`. If you are debiting a wallet rather than metering an allowance, the distinction is the whole subject of [quotas are not credits](/blog/quotas-are-not-credits). Because the SDK surfaces the message and the status but not the body's `code`, the message string is your other signal, and the two candidates do not look alike: - Rate limiter: `Too many usage recording requests. Please slow down.` - Quota: `Quota limit reached for 'api-calls'. Included: 250, used: 250, requested: 1, available: 0.` The rate limiter is also built with `standardHeaders: true`, so a 429 from it carries `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`. A response with those headers was not a quota decision. This is the fastest check you can run, and I have not run the snippet below as written, so treat it as the shape rather than a tested script: ```ts const res = await fetch( `${serverUrl}/api/v1/public/workspaces/${workspaceId}/subscription/usage`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-session-id': sessionId, }, body: JSON.stringify({ quotaSlug: 'api-calls', quantity: 1 }), } ); console.log(res.status, res.headers.get('ratelimit-remaining')); console.log(await res.json()); ``` > **Key takeaway:** A 429 with `RateLimit-Remaining: 0` is the limiter. A 402 with `code: > 'QUOTA_EXHAUSTED'` is the plan. They are different ceilings with different > units, different windows and different keys. ### The rate limit counts requests; the quota counts units This is where most of the confusion actually starts. A quota is a plan allowance: units, per workspace, reset monthly. A rate limit is throughput: requests, per minute, keyed on the caller's IP address. The usage endpoint is limited to 60 requests per minute. Credit consume gets 30. Above both sits a global limiter at 500 requests per 3 seconds, and a separate per-key limiter at 1000 per minute that only engages when the request carries an org API key. Per IP is the part that bites. Every workspace your backend records usage for shares one bucket, because they all leave through the same address. A hundred customers on a plan with room to spare will still collide at 60 requests a minute if your server records one unit per call. We have been bitten by exactly this shape internally. The token exchange endpoint used to be capped at 10 requests per minute per IP, which sounds strict until you notice it is a server-to-server endpoint, so the per-IP ceiling was really a ceiling on one integration's entire throughput. Our own provisioning makes up to three exchanges per signup. Ten a minute meant about three signups a minute before the platform started refusing its own work. It is 120 now, tunable by env var, and the code comment explaining why is longer than the change. ### One request is not one unit `POST /usage/batch` takes up to 100 items and shares the same 60-per-minute bucket as the single-record route. That is the intended escape hatch: one request against the limiter, up to 100 units against the quota. It also changes where failures appear. The batch handler runs items through `Promise.allSettled` and returns HTTP 200 with a per-item result array, so a quota rejection inside a batch is not a 402 at all. It is a `success: false` object sitting in the `results` array of a 200 response, next to a `failed` count. If you are only checking `res.ok`, you will record 100 items, get a 200, and never see that 40 of them were refused. And an item's `quantity` has a minimum of 1 but no maximum on the public route, so a single item can consume as much of the allowance as it likes. Your dashboard number can move by 5,000 on one request that cost you one unit of rate limit. ### A reset that has not landed, or will never land Allowances reset monthly whatever the billing interval, which the enforcement guide already states. What it does not say is when. The reset is anchored on `usageAnchorDay`, the day of the month the subscription was created, not the 1st and not the invoice date. The repo's own worked example: a subscription created on Jan 31 resets on Jan 31, Feb 28, Mar 31, Apr 30. The short month clamps, and the month after goes back to the anchor rather than cascading down. A sweep cron runs every 5 minutes, offset by one, at :01, :06, :11 and so on, so a reset lands within about five minutes of its boundary and not at the stroke of it. Then there is the case that produces a counter stuck at the cap for days. Reset eligibility is limited to `active` and `trialing`. Entitlement, the check that decides whether usage may be recorded at all, allows `active`, `trialing` and `past_due`. Read those two sets side by side and the gap is obvious: a past_due subscription can keep recording usage, and will never be reset. It fills to the included amount once, and then every call is refused until the payment recovers. Nothing is broken. The counter is just correct and permanently full. ### The replay that did not deduplicate An idempotency key is matched on three fields together: workspace, quota slug and key. Change any one of them and it is a different operation, and the replay increments again. That is deliberate for the slug, because it lets one request id record against several quotas in the same operation. It is a trap for the workspace, because a retry that resolves the workspace differently, say from a cached session rather than the path parameter, is a new match key and a second unit. There is a narrower path worth knowing about. [The increment and the log row are not one transaction](/blog/idempotency-keys-metering-write-path). The increment happens first, and the log row that stores the idempotency key is written inside a try/catch that only logs on failure. If that write fails, the unit is spent and no record of the key exists, so the retry finds nothing to match and spends another. Rare, and it shows up as a [counter two units ahead of the work you actually did](/guides/usage-does-not-match-invoice). Keys are capped at 255 characters, and the usual real cause is much simpler than any of the above: a fresh uuid per attempt instead of one stable id per logical operation. ### You may be reading a different counter than you think Usage lives at `quotas.` on the workspace document. Not on the org, not on the user. If your app resolves a workspace from a session on the read and from a path parameter on the write, you are looking at two documents. Two more writers touch that same field. The admin path, `PATCH /workspaces/:id/quota/usage`, sets values absolutely rather than incrementing, and when a Stripe record fails it falls back to writing the value locally. The internal Stripe route takes `workspaceId` from the request body, while the public route takes it from the URL. Same field, four ways in. The read and the write also do not resolve your subscription the same way. `getQuotaStatus` calls `getWorkspaceSubscription`, which returns any record that is not canceled, including `paused`, `incomplete` and `unpaid`. Recording calls `getEntitledSubscription`, which also rejects a dunning-suspended record and a `trialing` record whose `trialEnd` has passed. So a workspace with an expired trial that still says trialing will show you a full allowance on the dashboard and throw `No active subscription found` on the record. A 400, and not one word about quotas in it. ### Triage, in the order that settles fastest Read the status code. 429 is the limiter, 402 is the quota or the credit balance, and 400 is the request itself. Then read the body, because 402 covers the quota (`code: 'QUOTA_EXHAUSTED'`) and the credit balance (`available` and `requested`, plus `code: 'INSUFFICIENT_CREDITS'` on the hold routes only), and the message, because 400 covers an unknown slug and a missing subscription with different strings. Then check which workspace id the failing call actually sent, which is where the dashboard-versus-enforcement gap usually turns out to live. If the answer is the limiter, batching is the fix rather than a higher ceiling, and the batch shape is covered in the [server-side enforcement guide](/guides/quota-enforcement-server-side-nextjs). If the answer is a 402 from a credits route, you are on the credits path and the balance is not one number, which [the credits wallet guide](/guides/credits-wallet-nextjs) explains. ### Install ```bash npm i @buildbase/sdk ``` --- ## Stripe webhook signature verification failed in Next.js > One error string covers two different bugs. Five causes for a failed Stripe webhook signature in Next.js, ranked by how often each is actually it, each with its one-line test. - Source: https://www.buildbase.app/guides/stripe-webhook-signature-verification-failed-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 ### In short Five causes, ranked. Most of the time the raw bytes are gone: await req.json() or any re-serialization changes what gets hashed, because constructEvent hashes the timestamp, a dot, and the body exactly as received. A wrong signing secret throws the identical message. Clock skew is real, and it is last. ``` StripeSignatureVerificationError: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? ``` That question at the end is a guess, and it is wrong about as often as it is right. The same string is thrown when the body is perfect and the signing secret is wrong, because both produce the same outcome: a computed HMAC that does not match any signature in the header. So the message is a starting point, not a diagnosis. Below are the five causes in the order they actually turn up, with the one-line test for each. Stop as soon as yours matches. > **Before you start:** A Next.js App Router route handler, and `stripe` installed. Everything here is > checked against `stripe@14.25.0`, the version this repo has in `node_modules`, > and against our own webhook route at > `server/src/routes/organizations/payment/stripe/webhooks/index.ts`. ### Read the exact string before you change anything `stripe.webhooks.constructEvent` throws seven distinct messages, and six of them point at exactly one cause. Only the seventh is ambiguous. Find yours here first, because four of the five sections below become irrelevant the moment you do. | Message | What it means | | ------------------------------------------------------------------ | ------------------------------------------------- | | `No webhook payload was provided.` | The payload argument was empty, null or undefined | | `Webhook payload must be provided as a string or a Buffer` | You passed a parsed JavaScript object. Cause 1 | | `No signatures found matching the expected signature for payload.` | Bytes changed, or wrong secret. Causes 1, 2 and 3 | | `No stripe-signature header value was provided.` | The header is missing. Cause 4 | | `Unable to extract timestamp and signatures from header` | The header arrived mangled. Cause 4 | | `No signatures found with expected scheme` | A `t=` but no `v1=`. Cause 4 | | `Timestamp outside the tolerance zone` | Clock skew. Cause 5, and only cause 5 | One more that is not in that list and is not a signature failure at all: `SubtleCryptoProvider cannot be used in a synchronous context.` That is the edge runtime. `constructEvent` is synchronous and needs Node's crypto, so on edge you either add `export const runtime = 'nodejs'` or switch to `constructEventAsync`. Nothing about your secret or your body is wrong. ### 1. The body was parsed, or re-serialized, before it was verified **The test:** search your route handler for `req.json()`. If it appears anywhere above the `constructEvent` call, this is your bug. This is most of them. Here is why it is fatal rather than merely untidy. The signed material is built in `Webhooks.js` as: ```js function makeHMACContent(payload, details) { return `${details.timestamp}.${payload}`; } ``` `payload` is the body as a string, character for character. Not the object it parses into. `JSON.parse` followed by `JSON.stringify` is not an identity function on a JSON document: key order survives, but whitespace, indentation and line endings do not, and Stripe signed the bytes including those. Change one space and the HMAC is different, so the comparison fails and you get the "Are you passing the raw request body" message even though you are passing a string. Passing the parsed object directly is the friendlier failure. stripe-node detects that the payload is neither a string nor a `Uint8Array` and swaps in a message that says so outright: ``` Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead. ``` In the App Router the trap has a second edge. `Request` has a one-shot body stream, so calling `await req.json()` and then `await req.text()` does not give you a second look at the bytes, it throws. There is no ordering that rescues this. You read the body once, as text, and parse it afterwards from the string you already hold. And if a forum answer told you to add this, delete it: ```ts export const config = { api: { bodyParser: false } }; ``` That is a Pages Router directive. A route handler under `app/` ignores it, so it changes nothing and it will not fix anything. ### 2. It is the wrong signing secret **The test:** print the first eight characters of the secret your handler is reading. If it does not start `whsec_`, stop. If it does, check which endpoint issued it. Cause 2 produces the identical error string as cause 1, which is the whole reason this post is ranked rather than a single fix. Once the raw body is ruled out, this is next, and the secret is wrong in four distinct ways. **You reached for the API key.** The secret key does not participate in the HMAC at all. Our own route constructs a client only to reach the method: ```ts const stripe = new Stripe(stripeCredentials.secretKey, {}); event = stripe.webhooks.constructEvent( req.rawBody, stripeSignature as string, endpointSecret ); ``` `endpointSecret` is `stripeCredentials.webhookSecret`, a separate stored field. Swap the two arguments and verification fails every time, and nothing in the error text tells you that is what happened. **It is a different endpoint's secret.** Every endpoint gets its own `whsec_`. A `stripe listen` CLI session issues one that is unrelated to the one on your dashboard endpoint, which is why a webhook that works locally can fail on the first deploy with no code change between them. **Test against live, or live against test.** Our setup checker classifies a key by prefix and warns when the pair disagrees: ```ts if (key.startsWith(`${p}_live_`)) return 'live'; if (key.startsWith(`${p}_test_`)) return 'test'; ``` Signing secrets have no such prefix, so nothing catches a test-mode `whsec_` sitting in a live deployment except the failures themselves. **There is whitespace in it.** Copy a secret out of a dashboard into an env file and a trailing newline comes with it more often than you would think. stripe-node checks for this and appends a note to the error: ``` Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value ``` If that sentence is in your log, you are done reading. > **Key takeaway:** You cannot compare a stored signing secret against the one Stripe holds. > Stripe shows a `whsec_` once, at creation, and never again. Our setup page > says exactly that and falls back to comparing deliveries instead: it lists the > events Stripe created for the endpoint and reports how many were never > accepted. A count above zero with no connection errors is a wrong secret. ### 3. Something between Stripe and your handler rewrote the body **The test:** log `body.length` at the top of the handler and compare it with the payload size Stripe's dashboard shows for that delivery attempt. If they differ, nothing about your code is the problem. stripe-node names this case in the error itself, which is a good signal for how common it is: _"If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved."_ Tunnels, request-replay tools and anything that pretty prints JSON on the way through will all do it. Middleware counts too. Our tenant server captures the raw body in a single place, a `verify` callback on the JSON parser: ```ts app.use( express.json({ limit: '5mb', verify: (req: express.Request, res, buf: Buffer) => { req.rawBody = buf.toString(); }, }) ); ``` There is a quiet condition in there. `express.json()` runs `verify` only for requests it recognises as JSON, so a proxy that strips or rewrites `Content-Type` leaves `req.rawBody` undefined and the failure arrives as `No webhook payload was provided.` rather than a signature mismatch. That is why the route logs the header state and the byte count before it does anything else: ``` [Webhook] Headers: stripe-signature=present, content-type=application/json, rawBody=2143 bytes ``` `rawBody=MISSING` in that line ends the investigation on the spot. In Next.js, middleware is a less likely culprit than it looks. Next buffers the request body and replays the same bytes to the route handler, so a `middleware.ts` that reads the body does not change what gets hashed. What middleware can do is answer first. An auth guard whose matcher catches `/api/*` returns a `307` to `/login`, Stripe does not follow redirects, and the delivery fails without your handler or `constructEvent` ever running. If the dashboard shows a `307` on the attempt rather than a `400`, exclude the webhook path from the matcher. ### 4. The signature header never arrived intact **The test:** log the header itself. It should look like `t=1726790400,v1=`, and a valid one always has both parts. Three of the seven messages live here and each one tells you precisely how far the header got. Missing entirely gives you `No stripe-signature header value was provided.` Present but unparseable gives `Unable to extract timestamp and signatures from header`. A timestamp with no `v1=` gives `No signatures found with expected scheme`. There is also a failure mode the App Router removes for you. In Express, `req.headers['stripe-signature']` is typed `string | string[]`, and an array makes stripe-node throw a plain `Error` rather than a `StripeSignatureVerificationError`, so a `catch` that narrows on the Stripe error type misses it. Our route casts with `as string` and accepts the risk. `req.headers.get('stripe-signature')` in a route handler returns `string | null`, never an array, so that class of bug cannot occur. Worth checking one layer out: a CDN or WAF that allowlists headers will drop `stripe-signature` silently, and from inside the handler that is indistinguishable from Stripe not sending one. ### 5. Clock skew **The test:** does the error say `Timestamp outside the tolerance zone`? If not, your clock is fine and you can stop considering it. This is last because it is the only cause with a message of its own, so it never hides behind another. The check is four lines: ```js // Condensed from Webhooks.js; the real line lets a caller inject `receivedAt`. const timestampAge = Math.floor(Date.now() / 1000) - details.timestamp; if (tolerance > 0 && timestampAge > tolerance) { throw new StripeSignatureVerificationError(header, payload, { message: 'Timestamp outside the tolerance zone', }); } ``` `tolerance` defaults to `DEFAULT_TOLERANCE: 300`, five minutes, and our webhook route passes three arguments to `constructEvent`, so that default is what runs in production. It is a one-sided window: a clock running fast produces a negative age and sails through, a clock five minutes slow rejects everything. Five minutes is the same window we apply to our own outgoing webhooks, where `SESSION_DEFAULTS.webhookMaxAge` is `5 minutes` and the docs tell integrators to reject anything older. Two independent systems landing on the same number is not a coincidence so much as the obvious size for a replay window. Containers with a drifting host clock are the realistic version of this. Serverless is not, so if you are on Vercel or similar, skip it. ### The route handler that works Raw body first, header second, everything else after verification: ```ts import Stripe from 'stripe'; // constructEvent is synchronous and needs Node crypto, not Web Crypto. export const runtime = 'nodejs'; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: '2023-10-16', }); export async function POST(req: Request) { // Read once, as text. After this, req.json() is no longer available, // which is the point. const body = await req.text(); const signature = req.headers.get('stripe-signature'); if (!signature) { return Response.json({ error: 'Missing signature' }, { status: 400 }); } let event: Stripe.Event; try { event = stripe.webhooks.constructEvent( body, signature, process.env.STRIPE_WEBHOOK_SECRET! ); } catch (err) { // The message is the diagnosis. Log it, do not swallow it. console.error('[stripe] verification failed:', (err as Error).message); return Response.json({ error: 'Invalid signature' }, { status: 400 }); } await enqueue(event); // your queue, your worker return Response.json({ received: true }); } ``` I have not executed this file. It is the App Router shape of the Express route linked above, which does run in production, with the same argument order and the same three failure branches. Two decisions in there are worth defending. The API version is pinned because we pin it wherever a client makes API calls: `STRIPE_API_VERSION = '2023-10-16'` in `stripe-client.util.ts` is what the shared client factory speaks and what new webhook endpoints get created with. The verify-only client in our webhook route, quoted above, is the one exception and passes `{}`, which is safe because verification does not depend on the version. A client that calls the API does, and an unpinned one changes event shape under you on Stripe's schedule rather than yours. And the failure returns 400, not 200. A 2xx tells Stripe the event was delivered and it stops retrying, so a 200 on an unverifiable request means an endpoint with a wrong secret discards every event forever while its dashboard shows a clean green column. A 400 shows up as a failed delivery, which is where an operator will actually look. The comment in our route says as much. ### Verification passing is not the same as the event landing Worth knowing before you close the tab, because a fixed signature is where the next class of bug starts. Our webhook route verifies, stores the event, then enqueues a BullMQ job and answers 200. The job id used to be the Stripe event id. That is wrong, and it cost us: one Stripe account can be connected to more than one organization, and every test setup that reuses a key does exactly that. Stripe delivers the same event id to both. Keyed on the event alone, whichever org enqueued first was the only one that processed it, while the second org's webhook had already answered 200 so Stripe never retried. The fix is one line: ```ts export function webhookJobId(orgId: string, eventId: string): string { return `webhook-${orgId}-${eventId}`; } ``` The payment lifecycle suite found it, and there is now a test in `stripe-webhook-path-hygiene.test.ts` asserting that two orgs receiving one event id get two different job ids. The other silent one is a missing event type. Our `STRIPE_WEBHOOK_EVENTS` constant exists because a setup page once listed a hand-picked eight and called them essential. `checkout.session.completed` was not among them. Nothing fails loudly without it: the subscription is still recorded through `customer.subscription.created`, so billing looks healthy while every credit-pack purchase and every server-side conversion quietly never happens. We found that in our own production org, which is why the list is now a constant with a test that fails when it and the handler switch disagree. If you are wiring the rest of this path, the events above are the ones behind [charging per API call](/guides/charge-per-api-call-nextjs), [proration on a plan change](/guides/proration-on-plan-change-nextjs) and [a free trial without a card](/guides/free-trial-without-a-card-nextjs). ### Install ```bash npm i @buildbase/sdk ``` --- ## Token expired mid-request on a long operation > A 401 halfway through an upload, while the user is still signed in for another 29 days. Two clocks, not one, and the fix is a refresh before the call rather than a retry after it. - Source: https://www.buildbase.app/guides/token-expired-mid-request - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 - Updated: 2026-11-04 ### In short Two different clocks fail this request. SESSION_DEFAULTS in packages/shared holds tokenExpiry of 2-minute and sessionTTL of 30 days. The short one belongs to a handoff token crossing a server boundary, not to your API calls, so a user who is definitively still logged in can still see a 401 mid-flight. The request that failed was running for four minutes. The user who started it is signed in for another 29 days. Both are true at once. That contradiction is the entire bug report. What you pasted into Google was probably one of these: ```text Request failed (401: Unauthorized - Please check your session) Token verification failed: jwt expired BuildBase: Not authenticated (getSessionId returned null) ``` None of them means the user logged out. They mean something in the path ran out of time while the work was still going, and the thing that ran out was not the session. ### Two clocks, and the one you are watching is the long one `SESSION_DEFAULTS` in `packages/shared/src/constants/platform-stats.ts` holds both numbers, three lines apart: ```ts export const SESSION_DEFAULTS = { sessionTTL: '30 days', sessionTTLShort: '30-day', permissionRefresh: 'hourly', tokenExpiry: '2-minute', webhookMaxAge: '5 minutes', batchLimit: '100', } as const; ``` `sessionTTL: '30 days'` is the session. It is a server-side record, and `SESSION_TTL` in `server/src/routes/v1/auth/constants.ts` is the same value in seconds. On a device the user asked you to remember it stretches further, to whatever `rememberMeDays` the org set, defaulting to 90, under a hard ceiling of 180. That clock is generous on purpose. `tokenExpiry: '2-minute'` is a different thing entirely, and the gap between the two is where your request died. > **Key takeaway:** A 401 mid-request usually means a short-lived credential somewhere in the path > expired, not that the session did. The session record can have 29 days left > while a two-minute handoff token, minted when the flow started, ran out before > the step that redeems it. ### The two-minute clock is not sitting on your API calls Here is the part that catches people. The two-minute expiry does not belong to every authenticated request. It belongs to tokens that cross a boundary between two servers and are meant to be redeemed the instant they arrive. Look at `signOrgSwitchToken` in `central-server/src/utils/es256-jwt.ts`. It signs with ES256, stamps a `jti`, locks `aud` to one specific tenant server URL, and sets `expiresIn: '2m'`. The comment above it says what the number is for: just enough for the client-to-tenant handshake. The token goes central, then client, then tenant, and never back. The social login path does the same thing a different way - `LOGIN_HANDOFF` in the tenant's Redis TTL table is 120 seconds, described as the "token pickup window after a redirect," and the code behind it is consumed with an atomic get-and-delete so it can only be read once. So the short clock is deliberate, and raising it is not the fix you want to file a ticket for. Two minutes is not a guess about how fast your API is. It is the window in which a bearer credential is allowed to sit in a browser before it stops being useful to anyone who steals it. Stretch it to an hour to survive your long upload and you have not fixed the upload; you have widened the window on the one credential in the system that travels through a URL bar. The honest gap in our own constants: `tokenExpiry: '2-minute'` does not say which token it describes, and I had to read two server files to find out. ### What actually straddles the boundary Four shapes of work outlive a short credential, and they are the four that generate this error: - **A file upload** where the browser is still streaming bytes when the call that authorized it has already aged out. - **A long report** that queries, aggregates and renders before it answers. - **A batch import** that walks thousands of rows under one request. - **An agent call that thinks for a while**, where the model, not your code, decides how long the request takes. Before you blame the token, check which clock you actually hit, because the SDK has one of its own. `timeout` on the client config defaults to 30000ms, and `maxRetries` defaults to 0 with the note that it "only retries on network errors and 5xx responses, never on 4xx." That gives you a clean split. If the work died at roughly 30 seconds with an abort, you hit the SDK timeout and no token was involved. If it died at some other point with a 401, the credential expired. And whichever it was, nothing retried it for you, because the SDK refuses to retry a 4xx and it is right to. A third cause looks identical from outside. It is not a clock at all. `SessionService.getSession` [re-reads the user from the database roughly hourly](/blog/why-permissions-refresh-hourly), which is the `permissionRefresh: 'hourly'` line in the same constant. If that read comes back with the user blocked or deleted, the session is removed everywhere and the next call fails. Your `onSessionExpired` callback receives `'expired'` for that too: the type allows `'invalid'`, but 0.0.70 never sends it. Refreshing will not help, and a retry loop that keeps trying is just noise in your logs. ### Where the refresh is supposed to fit Before the long call. Not in a catch block after it. That sounds obvious until you look at how the credential is resolved. I read the shipped bundle of `@buildbase/sdk` 0.0.68 to check this rather than guessing from the types: the server client's action modules resolve the session by awaiting your `getSessionId` callback **on every call**. So a fresh cookie is picked up by the next call without you doing anything. `withSession(id)` is the opposite by design - it resolves once and pins that id for the life of the scoped client, which is exactly what you want for a background job and exactly what you do not want for a user-facing client running for hours. Two things worth knowing before you lean on this: `bb.auth()` does not phone the server. It calls your `getSessionId`, returns `{ sessionId }` if it got a string, and returns `null` if it did not. That proves the cookie is present. It proves nothing about whether the session behind it is alive. To learn that, make a cheap authenticated call and let it fail fast, while the request is young and a failure costs you nothing. And `BuildBaseSession` is `{ sessionId: string }`. There is no expiry on it, and the SDK exposes no explicit refresh method - I grepped for one. `getSessionId` is the refresh seam, and it is the only one. ### The shape of the fix Resolve the credential first, then hand the long work a session that belongs to the job rather than to somebody's browser tab. The canonical server setup is the one from our own snippets: ```ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl: 'https://api.yourapp.com', orgId: 'your-org-id', getSessionId: async () => { const cookies = await getCookies(); return cookies.get('bb-session-id')?.value ?? null; }, }); ``` Then the import route. Every chunk carries a key derived from the batch and the row index, so a replay lands on the same keys and cannot count anything twice: ```ts import BuildBase from '@buildbase/sdk'; export async function POST(req: Request) { const batchId = req.headers.get('x-request-id') ?? crypto.randomUUID(); const { workspaceId, rows } = await parseUpload(req); // 1. Resolve the credential while the request is young. A cheap call here // fails in milliseconds; the same failure after the import costs minutes. const session = await bb.auth(); if (!session) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } await bb.workspace.get(workspaceId); // 2. Run the long part under a session the job owns, not the user's cookie. const api = bb.withSession(process.env.BB_SERVICE_SESSION_ID!); // 3. One request per 100 rows, each item keyed so a replay is a no-op. for (let i = 0; i < rows.length; i += 100) { await api.usage.recordBatch(workspaceId, { items: rows.slice(i, i + 100).map((_row, n) => ({ quotaSlug: 'rows-imported', quantity: 1, idempotencyKey: `${batchId}:${i + n}`, })), }); } return Response.json({ imported: rows.length }); } ``` I have not run this against a live stack; `parseUpload` and the service session id are yours to supply. The `recordBatch` ceiling of 100 items per request is real and matches `batchLimit: '100'` in the same constant, and the batching argument is worked through properly in [enforcing quotas server-side](/guides/quota-enforcement-server-side-nextjs). Splitting the work into chunks of 100 buys you something beyond the ceiling: a credential that expires at chunk 14 loses one chunk, not the import. Replay from 14 with the same keys and the first thirteen stay exactly as they were. > **Warning:** A retry without an idempotency key is how a refresh-and-replay turns one > import into two. The key is matched on workspace, quota slug and key together, > so a replay returns the current status instead of incrementing again. Use > something stable across attempts of the same logical operation, never a fresh > uuid per attempt. ### Reading the 401 you actually got Four failures, four different reads. Work through them in this order: **The message contains `jwt expired`.** That is a handoff or org-switch token being verified after its two minutes. Something is holding a token that was meant to be redeemed immediately - a retry queue, a saved link, a tab that sat open through a redirect. Mint a new one rather than extending the old one. **The body is bare text, not JSON.** The tenant's `unAuthorized()` helper sends a plain 401 status with no JSON body, so the SDK's parse fails and it falls back to its own status map. That is where `Unauthorized - Please check your session` comes from. It is the SDK's generic string for a 401, not a description of what happened, so it tells you nothing about which clock fired. **`getSessionId returned null`.** No credential was found at all. The cookie is missing or your callback threw and swallowed it. This is not an expiry. **`onSessionExpired('expired')` with a session that should be alive.** Check whether the user was blocked or removed. The hourly re-read deletes the session the moment it sees either, and that is a permissions event wearing a 401. Building this plumbing yourself is a week you will spend twice, which is part of the arithmetic in [the cost of building auth yourself](/blog/cost-of-building-auth-yourself). The session and workspace side of it is in [add multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon). ### Install ```bash npm i @buildbase/sdk ``` --- ## Why your webhook is rejected after five minutes > A BuildBase delivery older than five minutes fails verification before the signature is ever compared. Why the max age exists, and the three things that trip it legitimately. - Source: https://www.buildbase.app/guides/webhook-rejected-after-five-minutes - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-20 - Updated: 2026-11-04 ### In short A delivery is refused when the x-buildbase-timestamp header sits more than 300 seconds from your clock, and it is your own handler doing the refusing. parseWebhookEvent checks the age before it compares the signature, and returns null for both. Backlog causes this far more often than clock drift does. The rule is flat: a delivery whose `x-buildbase-timestamp` sits more than five minutes from your clock is refused. Not slowed, not flagged. Refused, before the signature is ever compared. And the refusal is yours. Nothing on our side expires anything - the sending service posts the delivery and forgets about it. The five minutes is enforced inside `verifyWebhookSignature` in `@buildbase/sdk`, running in your process, on your host, against your clock. Which is why the error string you are looking at almost certainly reads `Invalid signature`, and why grepping for "webhook timestamp too old" turns up forum threads instead of anything we print. `parseWebhookEvent` returns `null` for a stale delivery and `null` for a forged one, and the return value cannot tell you which. ### Why a maximum age exists at all An HMAC signature proves who sent something. It does not prove when, and it never stops being true. Work through what that means. We sign `{timestamp}.{body}` with your endpoint's secret and put the result in `x-buildbase-signature`. That signature is valid the second it is generated and it is equally valid a year later, because nothing in the math decays. So anyone who ends up holding one valid delivery - a reverse proxy access log that captured headers, an error reporter that attached the full request, a laptop with a tunnel history - holds something they can POST at your endpoint again. Byte for byte. It verifies every time. Our own inbound receiver spells this out. The Mailgun handler at `server/src/services/email/providers/mailgun-webhook.ts` lists three checks and says why the second one is not optional: > The timestamp, within a window. Without it a single captured delivery stays > valid forever, because the signature over it never expires. A maximum age converts "forever" into a bounded window. Five minutes is the window. The timestamp cannot simply be advanced by whoever captured the delivery, because it is inside the signed string, not beside it - move the timestamp and the HMAC no longer matches. Here is the part that should bother you slightly. Mailgun's deliveries carry a per-delivery token, so our receiver records the token and refuses a repeat inside the window. Ours carry an event id instead: `id` in the body and the `x-buildbase-event-id` header, the same on every attempt, so recording the ids you have handled refuses a repeat for as long as you keep them. Nothing on our side refuses one for you, though, and an id store you prune is a window of its own. The age check is the half that needs no storage at all. That is the honest reason the default is tight, and the reason I would push back on anyone widening it to an hour because retries were failing. > **Key takeaway:** The five minutes is not about freshness of data. It bounds how long a captured > delivery stays replayable without your receiver storing anything; the event id > is the other half, and only as good as the ids you keep. ### What the check compares, exactly Two numbers, and it is worth being precise about which two, because the wrong mental model here sends people to chrony when the problem is their own queue. The number that ships is `maxAgeSeconds`, defaulting to `300`, declared in the SDK's own type. The number our marketing and docs quote is `SESSION_DEFAULTS.webhookMaxAge`, the string `'5 minutes'`, in `packages/shared/src/constants/platform-stats.ts`. Same value, two homes. Transcribed from the shipped bundle, the check is: ```ts // inside verifyWebhookSignature, @buildbase/sdk if (maxAgeSeconds > 0) { const sent = parseInt(timestamp, 10); if (isNaN(sent)) return false; if (Math.abs(Math.floor(Date.now() / 1000) - sent) > maxAgeSeconds) return false; } ``` Three things fall out of those lines. It compares the **signature timestamp** against `Date.now()` **at the moment verification runs**, not against the time your server accepted the connection. Those are different clocks in any handler that does work before it verifies. It uses `Math.abs`, so the window is symmetric. A delivery stamped in your future fails exactly as hard as one stamped in your past. That is not an accident and it is the single most useful diagnostic signal available to you - more on that below. And it runs **before** the HMAC comparison. A stale delivery never reaches the signature check, which is why a perfectly signed payload comes back as `Invalid signature` and sends people off to re-check a secret that was never wrong. Our sending side does its half of this in `server/src/services/webhooks/webhook-dispatch.service.ts`: ```ts const timestamp = Math.floor(Date.now() / 1000); ``` That stamp goes in the body as `timestamp`: when the event fired, the same on every attempt. It is not the one your handler checks. The delivery worker signs each attempt, the first and every retry, right before it sends it, with the time of that attempt in `x-buildbase-timestamp` and the endpoint's secret and URL as they are at that moment (`server/src/vendors/bullmq/queue/webhooks/delivery.ts`). So the clock your handler checks starts when the request leaves us. Carry that fact into everything below. ### Where it trips legitimately > **Before you start:** You have an endpoint in the console, you are reading its delivery log, and the > deliveries are arriving. If they are not arriving at all, you are looking at > throttling or an auto-disabled endpoint, which is a different page of the log. **Your handler queues deliveries behind slow work.** The clock keeps running while a request sits in your runtime. We allow 15 seconds per attempt before giving up, with a delivery worker concurrency of 10, so a receiver that takes the full 15 seconds caps the whole instance at about 40 attempts a minute - and yours is not the only endpoint in the queue. Meanwhile, on your side, every second a request spends waiting on a database pool, a cold Lambda or an event-loop block is a second of the 300 spent before `parseWebhookEvent` is called. Verify first, answer 2xx, then do the work. That ordering is not a style preference here. **What no longer trips it: our retries and our queue.** Retries used to carry the timestamp stamped at dispatch, so the fifth attempt, about 2.5 minutes after the first, arrived signed 2.5 minutes old, and any wait in our queue on top of that came out of your 300 seconds. Now each attempt is signed when it is sent, so neither does. A delivery that fails is retried 4 more times at roughly 10s, 20s, 40s and 80s, and every one of them arrives freshly signed. A retry after you rotate the signing secret or change the URL uses the new one. The same holds for our backlog. `server/src/constants/webhook-limits.ts` lets one organization enqueue 240 deliveries a minute and limits the delivery worker to starting 300 a minute instance-wide, and one organization may hold only three deliveries in flight at a time, so a slow receiver costs its owner throughput instead of everyone else's. A delivery over that cap waits a few seconds for a slot, and it is signed after it gets one. A campaign, where `email.sent` fires once per recipient, can make your deliveries late. It no longer makes them stale. **A paused local tunnel.** Every developer hits this one. The tunnel drops, your laptop sleeps, you come back, and a run of deliveries lands at once carrying timestamps from before lunch. Every one of them fails, and every one of them fails correctly. Nothing is broken. Do not go fixing it. **Genuine clock drift on the receiving host.** Real, and rarer than its reputation. Containers that never run an NTP client, a VM resumed from a snapshot, a bare-metal box nobody has looked at since it was racked. ### Clock skew is the answer people reach for, and usually it is not it The reasoning is understandable. The word "timestamp" is in the failure, and clock skew is the famous timestamp bug, so the investigation starts at `timedatectl` and burns an afternoon there. But drift big enough to break a 300-second window means a host five minutes wrong, and a host five minutes wrong usually has louder symptoms than webhooks - expiring tokens, certificate complaints, log lines out of order. The test takes one line, and it hinges on the `Math.abs` in the SDK. That absolute value throws away the sign. Keep the sign yourself: ```ts import { parseWebhookEvent } from '@buildbase/sdk'; export async function POST(req: Request) { const body = await req.text(); const sentAt = Number(req.headers.get('x-buildbase-timestamp')); // Signed, not absolute. The sign is the whole diagnosis. const delta = Math.floor(Date.now() / 1000) - sentAt; console.log('webhook delta seconds', delta); const event = parseWebhookEvent({ body, signature: req.headers.get('x-buildbase-signature'), timestamp: req.headers.get('x-buildbase-timestamp'), secret: process.env.BUILDBASE_WEBHOOK_SECRET!, maxAgeSeconds: 300, // the default, named so the rejection is greppable }); if (!event) { return Response.json({ error: 'stale or unsigned' }, { status: 401 }); } await enqueueForProcessing(event); // answer first, work later return Response.json({ received: true }); } ``` I have not executed this handler as written; it is the shape the SDK's own type declaration requires, with the age check named rather than left to the default. Now read the deltas: - **Negative delta.** The delivery is stamped in your future. Backlog cannot do that - queueing only ever makes a delivery older. A negative delta is clock skew, every time, no further investigation needed. - **Positive, large, and roughly constant at 3am and at peak.** Also skew. A fixed offset does not care how busy you are. - **Near zero when quiet, climbing when busy.** Backlog, and it is yours: `x-buildbase-timestamp` is stamped as the attempt leaves us, so our queue is not in the delta. Our share of the delay shows up elsewhere: each delivery-log row stores the exact `requestBody` we sent, whose `timestamp` is when the event fired, alongside the row's own creation time. Subtract them to see how late we sent it. Delivery logs are kept for 30 days. ### What not to do about it Do not reach for `maxAgeSeconds: 0`. It is a real option and it does exactly what it says, which is to hand back the unbounded replay window the check exists to close. If your deltas genuinely run long for a reason you have measured, raise the number deliberately and pair it with event-id deduplication, the same way our Mailgun receiver pairs a 15-minute window with a recorded per-delivery token. And do not let a rejected delivery be a silent one. A refused `subscription.trial_started` is a trial your app never learned about, which matters more than it sounds once [the gate is checking for an active subscription](/guides/free-trial-without-a-card-nextjs). A refused `credit.granted` is a balance that never moved. Log the delta, alert on `null`, and treat a 401 from your own webhook route as an incident rather than noise. A fresh signature on every attempt does not make a retry a new event. A retry can repeat one your handler already processed, for example one it answered after our 15-second timeout, so your handler has to be safe to run twice regardless of any of this. Every attempt carries the same `id`, so key on it, not on a hash of the body: a retry normally resends the first attempt's body, but when that copy cannot be read the body is built again and can differ. The discipline is the same one the [credit debit path](/guides/charge-per-credit-nextjs) and [server-side quota enforcement](/guides/quota-enforcement-server-side-nextjs) already need: an idempotency key you have seen before. ### Install ```bash npm i @buildbase/sdk ``` --- ## How to enforce quotas server-side in Next.js > The record call is the lock, not the if-statement after it. How quota enforcement actually behaves on hard-cap and overage plans. - Source: https://www.buildbase.app/guides/quota-enforcement-server-side-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-18 - Updated: 2026-11-04 ### In short Record usage with bb.usage.record() in the route handler. The record call is the enforcement: it increments atomically and rejects at the cap on hard-capped plans. The available <= 0 check from the docs snippet is not what stops the work, and it gives the wrong answer in all three situations it can meet. The quota snippet in our own docs ends with a guard that never fires on a hard-capped plan, and fires wrongly on a plan with overage enabled: ```ts if (usage.available <= 0) { return Response.json({ error: 'Quota exceeded' }, { status: 429 }); } ``` It looks like the enforcement. It is not. The enforcement already happened one line earlier, inside `record()`, and what you do with the return value depends on a plan setting that snippet does not mention. This guide is the server half of [enforcing quotas in React](/guides/enforcing-quotas-in-react). That post gates what a user sees. This one is the part a user with devtools cannot skip. > **Before you start:** A quota item defined on the plan version, and a workspace on an active or > trialing subscription. The examples use the slug `api-calls`, matching > [charging per API call](/guides/charge-per-api-call-nextjs). ### Step one: record the usage One call, in the route handler, before you do the expensive thing: ```ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl: 'https://api.yourapp.com', orgId: 'your-org-id', getSessionId: async () => { const cookies = await getCookies(); return cookies.get('bb-session-id')?.value ?? null; }, }); export async function POST(req: Request) { const usage = await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1, idempotencyKey: req.headers.get('x-request-id'), }); return Response.json({ remaining: usage.available }); } ``` What you should see: `consumed` goes up by one, and `available` comes back as whatever is left. Fire the same request with the same `x-request-id` twice and `consumed` moves once. The increment is a single conditional update, not a read followed by a write. That matters more than it sounds. Two requests arriving together against the last remaining unit cannot both be told there is room, because there is no window between the check and the increment for the second one to land in. ### Step two: handle the shape your plan actually has Here is the part the snippet skips. Enforcement branches on whether the plan hard-caps, and a plan hard-caps when the subscription is trialing **or** when overage is disabled on that quota. **On a hard-capped plan, a rejection throws.** It does not come back as `available: 0`. The conditional update refuses to match, the service raises, and the usage route returns HTTP 402 with `code: 'QUOTA_EXHAUSTED'`, the `quotaSlug` and `resetsAt` beside the message. In `@buildbase/sdk` 0.0.90 the thrown error carries the status as `status` but not the body's `code`, so branch on the status: ```ts try { const usage = await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1, idempotencyKey: req.headers.get('x-request-id'), }); return Response.json({ remaining: usage.available }); } catch (err) { // A used-up quota arrives here as a 402. On @buildbase/sdk 0.0.90 the error // carries the status but not the body's code, so test the status. if (err.status === 402) { return Response.json({ error: 'Quota exceeded' }, { status: 429 }); } throw err; } ``` So the `if` never runs on these plans. The `catch` is the branch that matters, and if you want your own callers to see a 429 you have to map it yourself, because the platform does not send one. **On a plan with overage enabled, nothing throws at all.** Usage past the included amount is accepted and billed, and `available` is floored at zero. It reports `Math.max(0, included - consumed)`, so it sits at 0 for every request after the cap. Keep the docs' guard here and you reject every overage call you had already agreed to bill. > **Key takeaway:** `available` is computed after the increment. A call that consumes the last > unit succeeds and returns `available: 0`. Treating 0 as "this request was > refused" rejects the one request that was fine. There is a third case worth knowing: `quota.limit_exceeded` fires only on the first crossing into overage, not on every call past the cap. On a hard-capped plan it never fires at all, because usage there can never exceed the included amount. If you are waiting on that event to email someone, a trialing workspace will wait forever. ### Step three: make the retry safe `idempotencyKey` is the difference between a retry and a double charge. A replay is matched on workspace, quota slug and key together, and a match returns the current status with `used: 0` rather than incrementing a second time. Because the slug is part of the match, one request id can safely record against several quotas: ```ts await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1, idempotencyKey: requestId, }); await bb.usage.record(workspaceId, { quotaSlug: 'storage-mb', quantity: 5, idempotencyKey: requestId, // same key, different quota, both land }); ``` Leave the key off and every retry your queue makes is a unit your customer pays for. Use something that is stable across retries of the same logical operation, not a fresh uuid per attempt. Send retries one after another, though: [two copies of one key in flight at the same moment can both count](/blog/idempotency-keys-metering-write-path), because the replay check is a read that runs before the counter moves. ### At volume, stop sending one call per unit The usage endpoint is rate limited to 60 requests per minute. Record one unit per API call synchronously and that limit, not your quota, becomes the thing that breaks first. `recordBatch` takes up to 100 items per request and returns a result per item, so partial failures are visible rather than silent: ```ts const result = await bb.usage.recordBatch(workspaceId, { items: [ { quotaSlug: 'api-calls', quantity: 1, idempotencyKey: 'req-1' }, { quotaSlug: 'storage-mb', quantity: 5, idempotencyKey: 'upload-1' }, ], }); ``` This is the shape any per-run product ends up needing. PlugNode bills [per flow run rather than per seat](/guides/charge-per-credit-nextjs), and a single run that fans out across steps produces far more than one billable event, so the batch endpoint is the only version of this that holds. ### What breaks, and how you will know **A 400 you read as the limit.** A used-up quota answers 402 with `code: 'QUOTA_EXHAUSTED'`, the `quotaSlug` and `resetsAt`. "Quota slug not on this plan version" and a missing subscription answer 400, so a 400 is never the limit. Branch on the status, not the message: `@buildbase/sdk` 0.0.90 puts the status on the thrown error but not the body's `code`, which arrives on the error with the next SDK release. **Overage that bills late.** Stripe sync is asynchronous. If the enqueue fails, the record stays unbilled until the sweep picks it up, and that sweep runs every 10 minutes - so a usage row that has not reached Stripe yet is late, not lost. **Counting the work you did not do.** Recording before the operation means a failure after the record still consumed the unit. For cheap idempotent work that is the right trade. For an expensive job, record after it succeeds and accept that a caller can start one more than the plan allows. **A quota that resets when you did not expect.** Allowances reset monthly whatever the billing interval, so a yearly subscription still gets a monthly reset rather than one annual pool. That is the opposite of what most people assume from an annual plan. If you are deciding whether this should be a quota at all, the distinction from a balance you buy is in [quotas are not credits](/blog/quotas-are-not-credits). ### Install ```bash npm i @buildbase/sdk ``` --- ## How to add a credits wallet in Next.js, and why the balance is not one number > Add a credits wallet in Next.js: sell packages, show the balance, spend FIFO from dated buckets, and warn before expiry. The balance is an aggregate over buckets, not a column you decrement. - Source: https://www.buildbase.app/guides/credits-wallet-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-17 ### In short A credits wallet is not a number on the workspace row. Credits arrive in dated buckets from three sources and spend earliest-expiring first. Show the balance with useCreditBalance, sell top-ups with CreditStorePage, and warn with useExpiringCredits, which fires only on buckets that carry an expiry at all. Search for a credits system and every result on page one starts the same way: a `credits_remaining` column on the user row, decremented after the work. Then the post spends its second half fighting the bug it just introduced, because two requests read 100, both subtract 100, and the customer gets 200 credits of work for 100 credits of money. The patches are familiar. A transaction. A row lock. A `SELECT ... FOR UPDATE` someone will later remove for being slow. All of that is downstream of the first decision, which nobody flags as a decision: a wallet was stored as an integer. It is not one. It is a stack of dated allocations, and the questions that actually break credit systems - what gets spent first, what expires when, what a retry does - only have answers once you stop pretending otherwise. ### What you are building A wallet a customer can read, top up and spend down, on a workspace. When it works, the billing screen shows a balance and a history, a "buy credits" button returns from Stripe with the balance already higher, and a job that runs twice charges once. Underneath, no line of your code subtracts anything. > **Before you start:** A BuildBase project with the billing module, and a workspace to hang the > wallet on. Selling credit packs needs Stripe connected. Granting them with a > plan does not. ### Step one: decide where credits come from Before any code, pick which of the three sources you are turning on. A bucket records where it came from, and the source decides the rules that follow it for the rest of its life: | Source | Created by | Typical use | | ---------------------- | ---------------------------------- | -------------------- | | `plan_grant` | A plan version with a credit grant | Credits with a plan | | `credit_pack_purchase` | Stripe checkout completing | Self-serve top-ups | | `admin_grant` | Your console, or a workflow action | Goodwill, migrations | Most products want two of these: a grant attached to the plan so a new customer starts with something, and packs they can buy when that runs out. A pack is defined once, in the dashboard, and carries a `creditAmount`, pricing per currency, and an optional `validityDays`. That last field is the one to think about now rather than later. Set it and a bucket bought from that pack gets an `expiresAt` of the purchase date plus that many days. Leave it unset and those credits sit there until spent. You are choosing between an open liability on your balance sheet and a support conversation with someone whose credits vanished, and both are real. Pick on purpose. (`validityDays` only applies where a pack is actually bought or granted by hand. A plan grant pointing at the same pack resolves its expiry a different way, which step five gets to.) The admin grant has a split worth knowing before you build a support flow on it. From the console it hands over the package's `creditAmount`, so granting 250 credits means having a 250-credit pack to grant from. The `grant_credits` workflow action takes an arbitrary number instead and needs no pack at all. There is a fourth value in the enum, `refund`, and nothing in the server ever writes it. A refund does not mint a bucket. It reaches back into the original purchase, which the failure modes below come back to. ### Step two: show the balance, which is five numbers The balance endpoint returns five fields, and the reason to know all of them is that `available` alone cannot answer a customer's question: ```tsx 'use client'; import { useCreditBalance } from '@buildbase/sdk/react'; export function Balance({ workspaceId }: { workspaceId: string }) { const { balance } = useCreditBalance(workspaceId); if (!balance) return null; return (

{balance.available} credits left, {balance.totalConsumed} used of{' '} {balance.totalGranted} granted

); } ``` `GET /api/v1/public/workspaces/:workspaceId/credits` also carries `totalExpired` and `totalRefunded`. When somebody writes in asking where their credits went, `totalExpired` is the answer, and a balance screen that never shows it turns a one-line reply into an investigation. The read needs the billing-view permission, which is worth noting before you drop the component into a page every member can see. ### Step three: sell a top-up The purchase flow is a Stripe Checkout session, and the pieces are already built. `openCreditStore()` from `useSaaSAuth` opens the purchase UI from anywhere, which is what you want behind a "buy credits" button in an out-of-credits error state. For a page of your own, `CreditStorePage` is headless and hands you the packages through a render prop: ```tsx import { CreditStorePage } from '@buildbase/sdk/react'; export function BuyCredits() { return ( {({ loading, packages, selectPackage }) => loading ? (

Loading packages...

) : ( packages.map((pkg) => ( )) ) }
); } ``` Server-side, `POST /credits/purchase` takes a `creditPackageId`, a `successUrl` and a `cancelUrl`, and it needs the billing-manage permission rather than billing-view. Buying is not reading. The part you would otherwise have to build is the webhook. A Stripe checkout webhook that fires twice is not an edge case, it is Tuesday, and the guard here is a unique index on `stripeCheckoutSessionId` across buckets. The second delivery tries to mint a bucket with a session id that already exists, the index refuses it, and nothing is granted twice. The database is the referee, not a check-then-write in the handler, which would be its own race. ### Step four: spend, and let the guard arbitrate Spending is one call: ```ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); try { await bb.credits.consume(workspaceId, { amount: 50, description: 'Batch export', idempotencyKey: jobId, }); } catch (err) { if (err.code === 'INSUFFICIENT_CREDITS') { return Response.json({ error: 'Not enough credits' }, { status: 402 }); } throw err; } ``` Two things happen inside it, and the order matters. First, one conditional update against the aggregate balance, filtered on `available` being at least the amount requested. Mongo applies the filter and the decrement atomically, so at most one caller succeeds per available unit. That single line is the whole concurrency story. Nothing reads the balance and then decides: the filter and the decrement are the same operation, so losing the race means your update matched nothing. Only then is the balance read, so the 402 carries a fresh number rather than a stale one. This is the same shape as the conditional write the roll-your-own tutorials arrive at eventually, minus the three attempts. Then the buckets are drawn down, earliest-expiring first and oldest after that. One consume of 50 can take 20 from a pack that lapses on Friday and 30 from a grant with no expiry, writing a ledger row for each. Credits about to expire leave first, which is the behaviour a customer would pick if you asked them. If you pass an `idempotencyKey`, a repeat returns the original result instead of charging again. [Pass a stable id for the logical job](/blog/idempotency-in-billing) rather than a fresh one per attempt. [Where the debit sits relative to the work](/guides/charge-per-credit-nextjs) is a separate decision, and it has real consequences, because no call reverses a consumed credit. ### Step five: warn before an expiry that might not exist Here is where a wallet quietly diverges from what its own pricing page promises. Plan-granted credits get an `expiresAt` in exactly one configuration: | `renewOnPeriod` | Mode | Expiry | | --------------- | ------- | ------------------------- | | off (default) | any | none, a one-time balance | | on | `topup` | none, they accumulate | | on | `reset` | at the next monthly reset | Three of the four give you credits that never lapse. `renewOnPeriod` is off unless someone turns it on, so the default for a plan grant is a lifetime balance, not a monthly allowance. The grant is configured on the plan version rather than the plan, which means [changing it is a versioning decision](/guides/plan-versioning-nextjs) like any other commercial term. If your pricing page says "500 credits a month" and nobody set that flag, each customer is given 500 credits once, and the gap shows up as a margin problem months later rather than as an error. Even the one expiring row has a way out. The expiry is set to the subscription's period end, and if the subscription carries neither a usage period end nor a Stripe one, the grant comes out with no expiry at all rather than an error. Purchased credits are the other path and they follow `validityDays` on the pack, independent of any of this. Wherever expiry is live, warn on it: ```tsx import { useExpiringCredits } from '@buildbase/sdk/react'; const { expiringCredits } = useExpiringCredits(workspaceId, 7); ``` Seven days is the default window and 90 is the ceiling. `WhenCreditsLow` covers the other failure, a balance running out rather than timing out, and renders once the balance is at or below the `threshold` you give it. Warning at a threshold sells a top-up. Hitting zero with no warning ends the session. ### The failure modes **A shortfall throws instead of undercharging.** The aggregate balance and the buckets are two records of the same fact, and they can disagree. If the guard allows a spend that the buckets cannot cover, the deduction does not quietly take what it can find: the balance decrement is rolled back and the call throws a desync error naming the workspace. Loud is correct here. A wallet that silently serves work it could not account for is worse than one that returns a 500, and the log line tells you reconciliation is owed. **A plan change expires the old grant whatever the mode.** This is the one I expected to work the other way. Moving a customer to another plan expires their existing plan-granted buckets before any new ones land, and it does that without consulting the grant's mode, so a `topup` customer who has been accumulating credits all year loses them on an upgrade. Canceling expires them too. Mode only decides what happens on the monthly re-grant, not on a plan change. Purchased and admin-granted credits survive all of it, which is the right split and the sentence to have ready when somebody upgrades mid-month and asks where the balance went. Their invoice moves on [a different set of rules](/guides/proration-on-plan-change-nextjs) again. **A refund claws credits back, and your code cannot start one.** When Stripe reports a refund, the matching pack is found by its payment intent and the same fraction of it is taken back, rounded up. A dispute takes all of it the moment it is opened. What the customer already spent stays spent, because it cannot be un-spent, so a full refund on a half-used pack pulls back what is left and stops there. This used to be missing: both webhooks reached the router, fell through as unhandled, and the credits stayed spendable after the money had gone. There is still no route or SDK call that reverses a purchase from your own code, which matters if you were planning a self-serve refund button. **Spending is rate limited, and 429 is not 402.** The consume route allows 30 requests per minute per IP. A 402 means the wallet is empty. A 429 from the same route means you are calling it too fast, and a batch job that fans out is the usual way to find that out. **Read the transactions, reconcile against the ledger.** These are two collections doing two jobs. Transactions are the user-facing feed, paginated newest first at up to 100 a page, filterable by type, which is what your billing screen renders. The ledger is the immutable trail, one row per bucket touched, carrying `balanceBefore` and `balanceAfter`, with the idempotency key stamped on the first of them. Render the first. Reconcile with the second. A UI built on the ledger shows a customer one purchase as three rows and invites a support ticket. **Check who is allowed to spend.** The consume route requires a usage-record permission on top of workspace membership. It did not always: for a while it carried the rate limiter and the membership check and nothing else, which meant the read-only viewer role could drain a workspace's balance. That is fixed, and it is the kind of thing worth checking in your own routes, because spending a customer's credits is spending their money. ### Where this sits next to the rest Credits are the prepaid half of consumption billing. The allowance that comes with a plan and resets on renewal is a quota, and the two behave differently enough that [choosing the wrong one shows up as an email](/blog/quotas-are-not-credits). Plenty of products run both. The full hook and component inventory, including the pieces this guide skipped, is at [docs.buildbase.app/credits/overview](https://docs.buildbase.app/credits/overview). I have not stood this exact sequence up as a single app end to end. The component and hook names are the documented SDK surface, and the server behaviour described here was read from the routes, the models and the credit service as they are today, not from how they ought to work. ```bash npm i @buildbase/sdk ``` --- ## How to change pricing without affecting existing customers in Next.js > Change SaaS pricing without affecting existing customers: publish a new plan version, leave subscriptions pinned to the old one, and decide what a v1 customer sees when you ship v3. - Source: https://www.buildbase.app/guides/plan-versioning-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-16 ### In short Changing a price never means editing one. Publish a new plan version, leave the old one attached to existing subscriptions, and both keep billing correctly. The hard part is not the price. It is whether a customer on version 1 gets the feature you shipped in version 3, which your entitlement check decides. The price change is the easy half. Publish new numbers, leave existing subscriptions where they are, and both keep billing correctly. Most billing systems will do that much. Then you ship a feature six weeks later and have to answer a question that never came up in the pricing meeting. Does the customer who signed up in March get it? That is not a pricing decision. It is decided by which object your entitlement check reads, and you made that decision months ago without noticing. ### What you are building A pricing change that leaves every existing subscriber where they are, and an entitlement check that keeps them there on purpose rather than by accident. When it works, three things are true at once. Your pricing page offers the new version. A workspace that subscribed last month still reports version 1 from `bb.subscription.get`, still bills the old amount, and still resolves its features from the version it signed up to. And nothing you deployed moved it. > **Before you start:** A BuildBase project with the billing module, a plan that already has one > published version, and at least one workspace subscribed to it. If nobody has > subscribed yet, skip this entire guide: a draft version is freely editable, so > change the numbers and publish. Versioning is for plans that already have > customers on them. ### Step one: create the next version from the current one Create the new version from the one you are replacing. Post to the plan's versions route naming the version you want copied: ```ts // POST /api/subscriptions/plans/:planId/versions { "baseVersionId": "" } ``` `baseVersionId` is optional, and leaving it out is rarely what you want: you get an empty draft with no features, no limits, no quotas and no prices, which is a new plan wearing a version number. Name the version you are copying. You get back a new row: the next version number, status `draft`. The copy brings across subscription items, features, limits, the quota values (`included`, `overage`, `unitSize`), and the pricing amounts, trial and credit grant. Not the Stripe price ids. Those get minted fresh on publish, and that omission is the whole reason a copy is safe. Two refusals to expect here. A plan can hold one draft at a time, so a second `POST` fails while an unpublished draft exists. And the version number comes from the highest existing version plus one, with a unique index on plan and version as the race guard, so two people clicking at once produces one version and one error rather than two v3s. ### Step two: edit the draft, because the published version will refuse you Put the new price on the draft. If you aim the same edit at the published version instead, the route rejects it: > Cannot modify pricing variants for a published version. Create a new version > or change status to draft first. That refusal covers `subscriptionItems`, `features`, `limits`, `quotas` and `pricingVariants`. The priced surface of a published version is frozen, and that is the sentence the rest of the guide rests on: "what was this customer sold?" has an answer that is a row, not a reconstruction from invoices. Know where the freeze stops, though. Alongside the lifecycle flags you would expect, `trial` and `creditGrant` still pass through on a published version. A trial length, [whether it asks for a card](/guides/free-trial-without-a-card-nextjs), [the credits that come with the plan](/guides/credits-wallet-nextjs): those are commercial terms by any reasonable reading, and they are editable in place. Treat the guard as protecting the price and the entitlements, not everything a customer agreed to. ### Step three: publish, and watch the old version go legacy Publishing runs a short list of guards first. Only a draft can publish. Only the highest version number can publish, so you cannot resurrect v2 after v3 exists. The version needs at least one subscription item. And it needs a pricing variant for every currency your organization bills in, which is the one to watch: the bar is set by your organization's currency list rather than by the version you copied from, so a currency added after v1 shipped is a currency v2 has to carry. Then the supersession happens in one pass. The previously current version is marked not-current, flagged legacy, and stamped with a deprecation time. Its replacement becomes current and gets a publish time, and the plan's pointer to its latest version moves with it. Now the important part, which is a thing that does not happen: **nothing writes to any existing subscription.** No loop over subscribers, no migration job. Grandfathering here is not a feature you enable. It is the absence of a write, which is why it cannot half-fail the way a migration can. ### Step four: read what a subscriber is actually on In your app, the subscription tells you its version directly: ```ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); const { subscription, plan, planVersion } = await bb.subscription.get(workspaceId); ``` `plan` is the stable thing the customer would name out loud, like Launch. It carries a name, a slug and a pointer to the newest version, and that is roughly all it carries. Price, features, limits and quotas live only on `planVersion`. There is nothing on a plan to mutate, which is less a design decision than the consequence of one. So a workspace that subscribed to our own Launch plan when it was $49 and a workspace that subscribes to it today at $19 are both on Launch. They are not on the same version, and every number that matters hangs off the version. ### Step five: resolve entitlements from the version, not the plan Here is the line that decides whether your grandfathering survives contact with your roadmap: ```ts // Right: reads what this customer actually bought. const canExport = planVersion.features['csv-export'] === true; // Wrong: reads what you are selling today. const canExport = plan.latestVersion.features['csv-export'] === true; ``` The second one works perfectly until the day you publish v2. Then every legacy subscriber silently inherits whatever you just put on the newest version, and you find out from a support conversation rather than a test. An entitlement [resolves from a published plan version](/blog/entitlements-are-not-feature-flags), and the version a subscription is pinned to is the only correct source. Reading from the version is not the same as nothing being stored. Assignment writes a copy of the features and the limits onto the workspace, and the subscription itself is cached for ten seconds. What saves you is the read order, not the absence of a snapshot: features come back as defaults, then the workspace's copy, then the pinned version last, so the version wins every collision. Quotas are computed from the version the same way. Limits are the exception, and that one has teeth. ### The failure modes **Limits never read from the version.** Features and limits are both written onto the workspace when a plan is assigned, so far so symmetrical. Quotas are never written there at all: `workspace.quotas` holds usage counters, not allowances, and the allowance is computed from the version on every read. The difference shows on the way out. Features resolve through the pinned version, which gets the last word, and quotas come straight from it. Limits are returned from the workspace and the version is never consulted. Most of the time you will not notice, because a plan change re-syncs the limits the new version defines. The case that bites is a workspace with no live subscription. Cancel one and its plan-managed features fall back to their defaults, exactly as you would want, while its limits sit there at the numbers its last paid plan wrote. A canceled workspace loses the features it stopped paying for and keeps the limits. If you are reasoning about "what does this customer get", you are reasoning about two mechanisms wearing one name. **The pricing page shows the current group, not a customer's version.** The public plans endpoint filters to the published, current, unarchived _group_ version and then takes whichever plan versions that group pins. That is [correct for a pricing page](/guides/annual-and-monthly-toggle-nextjs) and wrong as a way to answer "what is this customer on", because a legacy subscriber's version is reachable through their subscription and nowhere else. A billing settings screen built from the pricing list will show a grandfathered customer a plan they are not on. **You cannot archive a version that still has subscribers.** The route refuses it and tells you why: active subscriptions still point at that version. Active here is broader than you would guess: past-due, paused, incomplete and unpaid subscriptions all count, not just active and trialing. This is a good guard. It is also worth knowing before you plan a tidy-up, because a version with one unpaid subscriber on it is a version you keep. **Deleting the plan is not guarded the same way.** The archive check exists on plan versions, on group versions and on pricing groups. The plan delete route soft-archives without checking for active subscriptions at all. We found that asymmetry writing this guide, and no test covers either guard, so treat the protection you get on versions as a property of that one route rather than a rule the billing service enforces everywhere. Neither route deactivates the Stripe prices, either. A helper to do it exists on the plan-version controller and nothing calls it, so archiving in our console leaves live prices behind in Stripe. Harmless while nothing references them, and worth knowing before you assume archived means gone on both sides. **There is no "migrate everyone" button.** In a deployed app, one thing repoints a subscription at a different plan version: the customer changing plan themselves. Publishing a group version does sweep every affected subscription, but the only field it writes is the group pointer, and only for subscriptions whose pinned version is in the new group. The rest keep the legacy version on purpose, and none of them changes plan version at all. There is a third path in the codebase that assigns a plan to a workspace directly, and it is worth knowing it is not an option: it is test scaffolding, mounted only when `NODE_ENV` is not production. If you go looking for an admin override because a customer asked to be moved, that is the route you will find, and it is not there in the environment you need it in. So a price rise reaches new subscribers immediately, existing ones one at a time, and everybody else never. That is the correct default. It is also the thing to say out loud in the pricing meeting, because "we raised prices" and "our revenue per customer went up" are separated here by however long it takes people to choose to move. ### When not to version Versioning has a real cost. Every published version is a row you keep, a set of Stripe prices you keep, and a branch in every later question about what a given customer gets. Two cases are not worth that. A plan nobody has subscribed to yet is one, and it needs no ceremony at all: edit the draft, publish, done. The other is fixing wording that was never priced, like a plan description. Changing it does not change what anyone owes. The case that looks like a third one is a price you are still testing. Version it properly or do not ship it. A version you publish and deprecate a week later leaves a handful of customers pinned to it for as long as they keep paying, and that is a long time to support a price you already regret. The moment a change is worth a version is the moment someone would be annoyed to be moved off what they have. That is a commercial judgement rather than a technical one, and it is the right way round. ### What the customer sees Nothing. That is the point, and it is worth saying out loud because it makes this work hard to demo. A successful pricing change looks exactly like no pricing change to every existing customer: same invoice, same features, same quotas, same [credit balance](/blog/quotas-are-not-credits). The only people who see the new numbers are the ones who have not bought yet, plus anyone who chooses to switch, at which point [proration decides what they are billed today](/guides/proration-on-plan-change-nextjs). I have not run this exact sequence end to end as one app. The API shapes match the documented SDK surface and our own constants rather than being variants written for this post, and the server behaviour described is what the billing service does today, read from the routes, not what it should do. ```bash npm i @buildbase/sdk ``` --- ## An annual and monthly toggle in Next.js, and why it is not a boolean > How to add an annual and monthly toggle in Next.js: why the display interval is not the billing interval, what happens to plan allowances, and where the savings percentage should come from. - Source: https://www.buildbase.app/guides/annual-and-monthly-toggle-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-14 - Updated: 2026-10-13 ### In short A pricing toggle changes which prices are on screen, not how anyone is billed. Keep the display interval as its own type: the price follows the toggle, the allowance does not, because monthly allowances reset every month whatever the billing interval. Derive the savings badge from the two prices. A pricing toggle looks like the smallest component on the page. Two buttons, one piece of state, swap a number. Then someone on annual billing asks why their allowance did not go up, and you find out what the toggle was actually promising. The price column moved. The allowances underneath it moved too, because they were rendered from the same variable, and now the yearly card offers 100,000 users a month against a figure the metering resets every month regardless. The toggle is a display control. It decides which prices are on screen. It does not decide how anyone is billed, and the moment those two ideas share a type, the page starts making claims nobody wrote. ### What you are building Two buttons above a set of plan cards. Click Yearly and every price on the page switches to the annual figure, a badge appears with the real saving, and the line under each price reads "that's $41 per month, billed annually". The allowances in the card body do not move at all. Working looks like this: on our own [pricing page](/pricing), Launch reads $19 on the monthly column and $190 on the yearly one. The included figures below the price are identical in both. That is not a bug someone has not got round to. It is the whole point. > **Before you start:** [A Next.js app with `@buildbase/sdk` installed](/guides/buildbase-on-nextjs) > and a plan group configured, so `usePublicPlans` has something to return. You > do not need a subscription or a signed-in user: this is the public plans > payload, which is the same data an anonymous visitor sees. ### Step one: give the display interval its own type Start with the type, because it is the decision the rest of the guide falls out of. ```ts export type PricingDisplayInterval = 'monthly' | 'yearly'; ``` That lives in `pricing-presentation.ts` in our shared package, and it is deliberately not the `BillingInterval` enum that the subscription types export. That one has three members, `monthly`, `yearly` and `quarterly`, because it describes the period Stripe charges on. This one has two, because it describes which column you are looking at. They look like the same string union. They are not the same fact. One is a billing decision a customer makes at checkout; the other is a UI state that resets when they reload the page. ```tsx 'use client'; import { useState } from 'react'; import { usePublicPlans } from '@buildbase/sdk/react'; import type { PricingDisplayInterval } from '@ord/shared'; export function PricingInner() { const { items, plans, loading, error } = usePublicPlans('main'); const [interval, setInterval] = useState('monthly'); if (loading) return ; if (error || !plans?.length) return ; return ; } ``` You should see `plans` come back with a `pricingVariants` array on each one, and `items` as the catalog of everything a plan can include. Two payloads, because what a plan costs and what a plan contains are configured separately in the console. Default to monthly. Annual-first is a real conversion tactic and I am not going to pretend it never works, but it means the first number a visitor sees is not the number they will be charged if they click through on the default path, and that gap is where refund emails come from. ### Step two: read the price for the column on screen Answer first: index the plan's base pricing by the display interval, and handle the null rather than rendering it. ```ts function getPlanPrice(plan: any, interval: string): number | null { const variants = plan.pricingVariants || []; const variant = variants.find((v: any) => v.currency === 'usd') || variants[0]; if (!variant?.basePricing) return null; return variant.basePricing[interval] ?? null; } ``` `basePricing` carries `monthly`, `yearly` and `quarterly`, all optional. So the null is not defensive padding. A plan priced monthly and never given an annual figure returns null on the yearly column, and that is a real state in a catalog someone is still filling in. What you render for that null is a product decision worth making on purpose. Our page falls through to "Custom", which is right for the Enterprise tier and wrong for a plan an admin simply has not finished pricing. Hiding the card would be worse. A plan that vanishes when you click Yearly reads as a bug to everyone except the person who knows why. Then the line under the price: ```tsx function PriceNote({ interval, pricing, currency }: PriceNoteProps) { if (interval !== 'yearly') return null; return ( That's {formatPrice(pricing / 12, currency)} per month, billed annually ); } ``` Watch the rounding here. `formatPrice` is set to zero fraction digits, so Launch at $190 a year divides to $15.83 and prints as $16. Multiply the printed figure back out and you get $192, which is not a price we charge. Nobody has ever complained about this and I would still not put the derived number next to the real one without knowing it is rounded, because "$16 x 12" is arithmetic a buyer does in their head on the way to a budget meeting. ### Step three: leave the allowances alone This is the step every pricing-toggle tutorial skips, and it is the one that produces a false claim. The figure a plan includes of a metered item follows the toggle. The period label does not. ```ts const tier = quota[interval] ?? quota.monthly ?? quota; const included = tier?.included ?? quota.included; return { amount: formatNum(included), unit: item.name, period: NAME_CARRIES_PERIOD.test(item.name) ? '' : 'per month', note: !allowOverage ? 'hard limit' : overageCents != null && overageCents > 0 ? formatRate(overageCents, unitSize, currency) : undefined, }; ``` Both halves of that are load-bearing. The included figure is read per interval, because a catalog can price the same quota differently on an annual plan. The period stays "per month" whatever the column, because [monthly allowances reset every month whatever the billing interval](/blog/quotas-are-not-credits). Paying a year up front buys twelve monthly allowances in sequence, not one annual pool to spend how you like. > **Key takeaway:** The price follows the toggle. The allowance figure follows the toggle. The > period label never does, because the reset is monthly on every interval. Get this wrong in the obvious direction, by multiplying the included figure by twelve on the yearly column, and the page promises an annual pool. A customer who burns through it in March has been told something the metering will not honour, and they have it in a screenshot. One more detail in that snippet, which cost us a rewrite. `NAME_CARRIES_PERIOD` checks whether the item's own name already says how often it resets. Plenty of catalogues name the item "Emails sent / mo" or "Monthly active users", and appending our period to either gives you "Monthly active users per month". The name wins, because it is the author's wording and it is what the comparison table prints as the row label. ### Step four: derive the savings badge, do not type it The badge on the Yearly button is where hardcoded numbers go to rot. ```ts function annualSavingPercent(plan: any): number | null { const monthly = getPlanPrice(plan, 'monthly'); const yearly = getPlanPrice(plan, 'yearly'); if (!monthly || !yearly) return null; return Math.round(((monthly * 12 - yearly) / (monthly * 12)) * 100); } ``` Our three paid plans are each priced at ten months for twelve. Launch is $19 a month or $190 a year, Grow is $49 or $490, Scale is $99 or $990, and Free is $0 on both columns. Two months free on all three paid plans, which is 16.67%, which is the 17% our page prints. And our page prints it as a string literal. The prices come live from the database and the badge is typed into the JSX, so the day someone edits an annual price in the console the badge goes on claiming 17% and no build, test or type error says otherwise. It is right today. It is right by coincidence, and I would rather write that down than let this guide recommend something our own page has not got round to doing. The derived version also lets you say the true thing when plans disagree. If Launch saves 17% and Scale saves 22%, "Save up to 22%" is honest and "Save 22%" is not. ### The failure modes **Reusing the billing-interval type for the toggle.** The one that starts all the others. Widen the display type to three members so it matches the enum, and the label map goes out of sync with it: ours holds `monthly` and `yearly` only, with `INTERVAL_LABELS[interval] || INTERVAL_LABELS.monthly` as the fallback. A quarterly column would render the quarterly price with "/mo" beside it, silently, because the fallback is doing what it was written to do. **Assuming two intervals because the toggle has two buttons.** A catalog can price quarterly as well, and a two-button toggle shows no column for it. That is a choice rather than an oversight: a third button costs more attention than quarterly billing earns on a marketing page, and checkout is where a customer picks the period they are actually billed on. Just do not write code that believes yearly is the only alternative to monthly. **Putting the interval in the URL and forgetting the default.** `?billing=yearly` is a reasonable thing to support, because it makes the annual column linkable from an email. Read an unknown value straight into state and you get a column with no labels and no prices, since both lookups miss. Validate against the two allowed strings and fall back to monthly. **Treating the toggle as a commitment.** It sets no state on the server. A visitor who clicks Yearly and then starts a trial is still on whatever interval the checkout passes, and [the interval is an argument to the subscription call](/guides/proration-on-plan-change-nextjs), not something the page remembered about them. Our own trial is [7 days and takes no card](/guides/free-trial-without-a-card-nextjs), so there is a stretch where the customer has picked a plan, seen an annual price, and has no billing interval at all yet. **Letting the card and the table format money differently.** Once the price appears on a card, in a comparison row and in an overage note, three renderers can round three ways. Keep one `formatPrice` and one `formatNum` and import them everywhere, which is why ours live in the shared package rather than in the page. I have not run this exact file end to end as one app. `getPlanPrice` and the allowance block are lifted from our own pricing surface rather than written for this post; `PriceNote` is the same render pulled out into its own component, because ours sits inline in a card. The behaviour described is what the page does today. ```bash npm i @buildbase/sdk ``` --- ## Proration on plan change in Next.js, and why a downgrade needs the opposite setting > Proration on plan change in Next.js: why upgrades and downgrades need opposite proration behavior, and how to read direction without mistaking a yearly plan for a bigger one. - Source: https://www.buildbase.app/guides/proration-on-plan-change-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-13 - Updated: 2026-10-30 ### In short Proration is not one setting, it is a direction. An upgrade invoices the difference now. A downgrade should not, because the customer keeps the old plan features until the period ends, so a credit refunds what they are still using. Read direction from monthly-equivalent price, never the ticket amount. Every proration tutorial ends at the same line. ```ts proration_behavior: 'always_invoice'; ``` It is right half the time. On an upgrade it does exactly what you want: Stripe credits the unused part of the old plan, charges the new one from today, and cuts an invoice for the difference. On a downgrade the same line hands money back for features the customer has not stopped using yet. Proration is not a setting you configure once. It is a decision that depends on which way the change goes, and getting the direction wrong is not a rounding error - it is a refund you did not mean to issue. ### What you are building A plan switcher in a Next.js app. A customer on Launch picks Grow and sees an invoice for roughly $15 on a mid-month change, because the gap between $19 and $49 is $30 and half the period is still to come. The same customer going the other way sees no invoice at all, keeps their Grow features until the period ends, and the change shows up as pending rather than done. > **Before you start:** A BuildBase project with the billing module, a plan group with at least two > plan versions, and a workspace that already has an active subscription. If > there is no subscription yet, that is a checkout flow, not a plan change. ### Step one: read where the subscription is now `useSubscriptionManagement` gives you the current subscription, the plans available to switch to, and the mutation, in one hook. ```tsx import { useSaaSWorkspaces, useSubscriptionManagement, } from '@buildbase/sdk/react'; function PlanSwitcher() { const { currentWorkspace } = useSaaSWorkspaces(); const { subscription, planGroup, loading, updateSubscription, refetch } = useSubscriptionManagement(currentWorkspace?._id); if (loading) return

Loading plans

; if (!subscription?.subscription) return ; return ; } ``` You should see `planGroup.plans` come back as plan _versions_, each with its own `_id`. That `_id` is what you pass to change the plan. Not the plan id, and not the plan name. Versions are the priced copies, which is what [lets pricing move without rewriting what last year's customers agreed to](/guides/plan-versioning-nextjs). ### Step two: ask for the change ```tsx const result = await updateSubscription(planVersionId, { billingInterval: 'monthly', successUrl: window.location.href, cancelUrl: window.location.href, }); ``` Notice what you did not pass. There is no proration flag in that call, and that is deliberate: the server works out the direction and picks the behavior, because the client is the wrong place to decide how much to bill someone. What it decides, and why, is worth knowing even if you never touch it. Direction is read from the monthly-equivalent price of the old and new base prices, not from the amounts on the tickets. A yearly Launch price and a monthly Grow price are not comparable numbers. Launch at $190 a year is the smaller commitment and the bigger integer, so a naive comparison reads the move to Grow at $49 a month as a downgrade and skips the invoice you were owed. Then the behavior follows the direction: an upgrade invoices immediately, a downgrade does not prorate at all. So what happens if the price lookup itself fails? The direction stays null, and the two decisions that depend on it handle that null differently. Billing never sees it as a null at all: `plannedDowngrade ? 'none' : 'always_invoice'` reads falsy, so an unknown direction gets billed as an upgrade. Feature sync checks explicitly, and only when the direction is unknown does it fall back to the sign of the latest invoice. Whenever the direction is known, both agree. The unknown case is where it gets interesting, because that fallback does not work. It tests `amount_due < 0`, and `amount_due` does not go below zero. Stripe's own field documentation says it "may be 0" when account credit applies, which is exactly the downgrade case: the credit lands on the customer's balance and the invoice reports nothing due. The negative shows up in `total` and in `ending_balance`, neither of which the fallback reads. So both paths land on "upgrade" when the direction is unknown, by two different routes: billing because null is falsy, feature sync because the sign it is looking for never arrives. A downgrade whose price comparison failed gets invoiced like an upgrade and has its features cut on the spot. Rare, because it needs a Stripe call to fail first. Worth knowing it fails in that direction rather than the safe one. You can quote the customer a figure first. The preview route, `POST /api/v1/public/workspaces/:workspaceId/subscription/preview`, prices the change without making it. For a change it answers `dueToday` and `nextInvoice`, so "you will be charged $25 today" is a number you can render before the change commits; a downgrade on the same interval answers `deferred_downgrade`, with nothing due now. Pass the preview's `prorationDate` back on the change, so Stripe charges for the moment it priced. The `usePreviewSubscriptionChange` hook and the `prorationDate` option on `updateSubscription` need `@buildbase/sdk` 1.0.0 or later; on 0.0.90 and earlier, call the route yourself and make the change without it. The details are in the [billing docs](https://docs.buildbase.app/billing/overview). ### Step three: handle both shapes of the result `updateSubscription` returns one of two things, and the split is not about payment. A workspace with a Stripe subscription gets that subscription changed in place. A workspace without one gets a checkout session, because there is nothing to change yet - it is a first purchase wearing a plan change's clothes. ```tsx if ('checkoutUrl' in result) { // No subscription to modify. Send them through checkout. window.location.href = result.checkoutUrl; return; } await refetch(); ``` Then the part that actually bites. A change in place does not mean money moved. The update runs with `pending_if_incomplete`, so the subscription can come back active while the proration invoice sits open behind a declined card or a 3DS prompt, and the feature sync waits for the payment before it runs. A 200 is not a receipt. An app that renders one as "you're on Grow now" has shipped a bug, and it is the kind you find out about from a customer rather than a log. The API does tell you, on the branch where it matters. When payment is outstanding the response carries `paymentRequired`, the `invoice`, and a `paymentUrl` to send the customer to. On the clean path all three are simply absent, so do not destructure them blind. In TypeScript you will need a cast to read them. None of the three are declared on `ISubscriptionUpdateResponse`, and that is not a version you can upgrade out of: they are missing from the whole type surface in 0.0.70, the latest published SDK, the same as in 0.0.56. The route sends them, the types do not mention them, so narrow on `'checkoutUrl' in result` first and cast for the rest. ### Step four: show a downgrade as pending, not done A downgrade is not one event. Four things move on different clocks, and a UI that treats them as one is how support tickets start. | What | When it changes | | --------------------- | ----------------------------------- | | The proration invoice | Never, on a downgrade | | Quota allowances | Immediately, to the lower plan | | Features and limits | At the next period rollover | | Existing credits | Kept until they expire on their own | So the subscription reports the new plan straight away while [the old plan's features are still switched on](/blog/entitlements-are-not-feature-flags). Render that gap honestly. "Your plan changes to Launch on 14 October" is true; "You are now on Launch" is not, and the customer who still sees their Grow features will believe the UI over the invoice. The credit half surprises people most. What happens to credits the customer already paid for? They stay, and the smaller allowance arrives at the next renewal rather than clawing back what is already in the account. Credits and quotas behave differently here because [they are different things](/blog/quotas-are-not-credits), and a downgrade is where that distinction stops being academic. ### The failure modes **Comparing ticket prices to find the direction.** The yearly price is always the larger number, so this one survives testing: everybody tests monthly-to-monthly. Add a yearly plan and a real upgrade starts skipping its invoice. **Using `always_invoice` in both directions.** A downgrade that credits back unused time pays for the same period twice: once in the refund, once in the features that stay on until rollover. Stripe will not stop you: direction is yours to work out, and the setting that is correct going up is a refund coming down. **Letting a plan change eat reported usage.** Two Stripe behaviors collide here. Removing a metered subscription item that has usage records is refused unless `clear_usage` is set, and `clear_usage` throws the usage away. `always_invoice` does not rescue it, which we found out the expensive way: measured against live Stripe, a downgrade over 10,101 reported units produced an invoice with exactly one line - the unused-time credit - and the usage was gone. Every plan change was discarding a period of overage, on precisely the accounts most likely to have any. The fix is to convert reported usage into an invoice item _before_ the subscription items change, which also puts it on the bill as its own readable line. If you are metering per call, [that guide covers the recording side](/guides/charge-per-api-call-nextjs). **Offering the switcher to a subscription that cannot take it.** Only `active` and `trialing` subscriptions can change plan. Everything else returns a 400 with a reason attached - past due, in dunning, paused, suspended, incomplete, or already cancelling - and "Cannot upgrade a past-due subscription. Please resolve the payment issue first." is a better thing to render than a generic error. A past-due customer trying to upgrade is someone actively trying to give you money, so route them to the payment problem instead of a dead end. Two more refusals live in the same place: you cannot move a workspace between plan groups, and you cannot change its currency. **Assuming a trial upgrades like a subscription.** A workspace still trialing has no paid period to prorate against, so a plan change during a trial charges nothing. The trial keeps running on the new plan and ends when it would have, and the first real charge is the new plan's price. Ending the trial at the change is worse than it sounds: our own trial is [7 days and takes no card](/guides/free-trial-without-a-card-nextjs), and a trial with no card that ends has nothing to charge, so Stripe cancels the subscription. Someone comparing plans has not agreed to pay today. **Not expecting the seat line to move.** A plan change does reconcile seats, and that is the surprise. Billable seats are recomputed against the new plan's included allowance, so the seat item gets repriced, added, or deleted by a change the customer thought was only about the base plan. Say your smaller plan includes three seats and a team of five pays for the two past them. Move that team to a plan that includes eight, and the seat line does not shrink - it disappears. [Per-seat billing has its own failure modes](/guides/charge-per-seat-nextjs). I have not run this exact file end to end as one app. Each snippet matches the canonical SDK usage in our own docs and constants rather than being a variant written for this post, and the proration behavior described is what the billing service does today, not what it should do. ```bash npm i @buildbase/sdk ``` --- ## How to add a free trial without a card in Next.js > A free trial with no credit card in Next.js: turn the card requirement off on the plan version, then handle the part Stripe cannot - what your app renders, and who the gate lets through. - Source: https://www.buildbase.app/guides/free-trial-without-a-card-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-12 - Updated: 2026-10-22 ### In short A card-less trial is one setting and one real decision. Turning off the card requirement on a plan version is configuration. The decision is the gate: a trialing subscription is not active, so code that checks for 'active' locks out every trial user you have. Dropping the credit card from your trial does not remove billing work. It moves it into your app. With a card on file, conversion is something Stripe does to the customer while you sleep. Take the card away and that machinery is gone. Nobody is charged automatically on day 8, which means the only things standing between a trial and a paying customer are the emails you send and the wall you put up. Both are yours to build. Most guides on this stop at the checkout flag, and the flag is the easy half. > **Before you start:** A BuildBase project with the billing module connected to your own Stripe > account, and at least one published plan version. Billing needs Stripe > credentials, a plan, a published version and a pricing group configured in the > dashboard before any of the SDK components return data. ### Step one: turn the card requirement off Trials are configured per plan version, not globally. Each version carries a trial block with three fields: whether it is enabled, how many days it runs, and whether it collects a card. ```ts // The plan version's trial config, set in the dashboard trial: { enabled: true, durationDays: 7, requireCard: false, } ``` That last field is the whole feature, and it defaults to `true`. Card-less is something you opt into on a specific plan version, not a platform default, so flipping it is a deliberate pricing decision rather than a checkbox you forgot. Per version also means you can still change it after that version is published: [the freeze on a published version](/guides/plan-versioning-nextjs) covers pricing, features, limits and quotas, and the trial block sits outside it. Set `durationDays` deliberately too: the schema default is 14, and the 7 above is our own choice rather than the number you inherit. With `requireCard` off, the checkout session is built with `payment_method_collection: 'if_required'`, whose own default is `always`. Both knobs point the same way until you turn them. Read `if_required` literally, though: it skips the card only when the total due for the session comes to zero, and a trial is what makes that true. Add a setup fee and the card form is back. In the plain case checkout completes with nothing entered, and the subscription opens in `trialing` rather than `active`. Our own paid plans' trial runs on exactly this: 7 days, no card required. The "no credit card required" line on our signup page is derived from `PLAN_FACTS`, our mirror of the published plan terms, rather than typed out next to the button - so it removes itself the day that flag flips. Worth copying. A trust badge nobody owns is a trust badge that eventually lies. ### Step two: know what the trial's end already does Cancellation is already handled for you. The same checkout session that skips the card also carries an end behavior: ```ts trial_settings: { end_behavior: { missing_payment_method: 'cancel', }, } ``` `cancel` is one of three values that field takes. The other two are `pause`, which freezes the subscription and stops it invoicing until a card arrives, and `create_invoice`, which bills anyway and hands the problem to your dunning settings. We chose `cancel`. It is the honest default for a trial nobody paid for, but it is a choice, and the other two are there if your product would rather hold the account open. So the subscription does end. What it does not do is decide anything about your product. Stripe can cancel or pause a subscription; it cannot grey out your dashboard or pick which message the user reads on day 8. So what does that user actually see? Stripe hands that part back to you, and it is the rest of this guide. ### Step three: render the three states A trial is not a boolean. It has three states worth drawing differently, and `useTrialStatus` returns all three. ```tsx import { useTrialStatus, WhenTrialEnding } from '@buildbase/sdk/react'; function TrialBanner() { const { isTrialing, daysRemaining, isTrialEnding } = useTrialStatus(); if (!isTrialing) return null; return ( {daysRemaining <= 0 ? 'Your trial ends today' : `Your trial ends in ${daysRemaining} ${daysRemaining === 1 ? 'day' : 'days'}`} ); } ``` | Return | What it is | | --------------- | -------------------------------------------- | | `isTrialing` | In the trial period | | `daysRemaining` | Days left, which reaches zero before it ends | | `isTrialEnding` | Inside the warning window | The ternary on `daysRemaining` is not defensive padding. Our console renders this same banner and needs that branch, because "your trial ends in 0 days" is what you ship without it. One ordering note, learned the annoying way. A payment problem outranks a trial warning, so check `past_due` and `unpaid` before you check the trial. A user whose card just failed does not need to hear about a countdown. ### Step four: get the gate right A trialing subscription is not `active`. `trialing` is a status of its own. The obvious check locks out every trial user you have. Quietly, and at your own expense: ```ts // Wrong. Your trial users are not 'active'. const { subscription } = await bb.subscription.get(workspaceId); if (!subscription || subscription.subscriptionStatus !== 'active') { return Response.json({ error: 'Subscription required' }, { status: 403 }); } ``` I am not holding up a strawman. That is the server-side snippet in our own billing docs, and it is fine for the case it was written for - a paid subscription, no trial in the picture. Add a trial and it is a lockout. Ours is the kind of example that gets pasted, so treat it as the default you have to override rather than a mistake nobody makes. Two statuses beyond `active` should get through: ```ts const LIVE_STATUSES = ['active', 'trialing', 'past_due']; const { subscription } = await bb.subscription.get(workspaceId); const status = subscription?.subscriptionStatus?.toLowerCase(); if (!status || !LIVE_STATUSES.includes(status)) { return Response.json({ error: 'Subscription required' }, { status: 403 }); } ``` `past_due` belongs on that list. A failed charge starts Stripe's retry cycle, and cutting access off on the first failure is hostile when the usual cause is an expired card. Now the half that matters because you skipped the card. A status check alone trusts `trialing` forever. Normally an ended trial is moved out of `trialing` by webhook, so the status is authoritative - but a card-less trial is the case where that is least reliable. There is no payment to fail, nothing to retry, and a webhook that never lands leaves the subscription sitting in `trialing` indefinitely. A free pass with no expiry. So check the date too. Read it off the subscription object as `trialEnd`, not from the React hook, which cannot run inside a route handler: ```ts const trialExpired = status === 'trialing' && subscription?.trialEnd && Date.parse(subscription.trialEnd) < Date.now(); if (!status || trialExpired || !LIVE_STATUSES.includes(status)) { return Response.json({ error: 'Subscription required' }, { status: 403 }); } ``` One deliberate asymmetry: an absent or unparseable `trialEnd` should be treated as not expired. Trusting the status beats locking a paying customer out over a date you could not read. That is how our own gate behaves, and it is pinned by a test rather than left to whoever edits it next. > **Key takeaway:** Check the status against all three live values, then check `trialEnd` > separately. `status === 'active'` is wrong twice over: it excludes your trial > users, and it trusts a `trialing` that a missing webhook can leave stuck. ### Step five: send the emails, because nothing else converts With a card on file you could skip this and still get paid. Without one, these emails are the conversion mechanism, not a courtesy. Three events fire across a trial's life: `subscription.trial_started`, `subscription.trial_will_end` and `subscription.trial_expired`. The middle one earns its keep. Subscribe a workflow or a webhook to it and send the `trial-ending` template, which takes `WorkspaceName` and `DaysRemaining`. Note what that template keys on. Workspace, not user. `trialUsedAt` is stamped on the workspace document the first time a trial starts, and checkout skips the trial when that field is already set or the workspace already has a Stripe subscription. One workspace, one trial, however many people you invite. **Correction, 22 October 2026.** An earlier version of this guide said the workspace alone decides who gets a trial. Since 23 October 2026 the default is once per person: checkout records the person who starts a trial and the workspace's owner, by account and by verified email, and someone who has had a trial in any workspace is not offered another. `trialUsedAt` is still stamped and still read, so one workspace still gets one trial. A plan version's **Who can trial** setting chooses once per person (the default), once per person per plan, or once per workspace. Leave auto-create on in a team app, though, and [an invited user gets a workspace of their own](/guides/auto-created-first-workspace-nextjs), with a trial nobody has claimed yet. Give each user a trial clock of their own on the same workspace instead and you have built a renewable free plan: invite a colleague, get another 7 days. Once per person is the opposite of that: it counts people so nobody gets a second trial by opening a second workspace. That invite is worth gating properly anyway, for [reasons the seat guide covers](/guides/charge-per-seat-nextjs). If a per-account allowance is what you actually want, [that is a quota, not a trial](/blog/quotas-are-not-credits), and it is a different module. ### The failure modes **Gating on `status === 'active'`.** Covered above. It is the expensive one, because the users it breaks are the ones you have not sold yet, and they will not file a bug - they will leave. **Trusting `trialing` indefinitely.** Without the `trialEnd` check, a webhook that never arrived is an indefinite free pass. This is likelier on a card-less trial than on a normal one. **Printing `daysRemaining` raw.** It hits zero while the trial is still running. Branch on it or ship "ends in 0 days". **Letting the trial banner outrank a payment failure.** Two banners can be true at once. Decide the priority yourself, or the user gets a countdown when what they needed was "your card was declined". **Re-trialing on plan change.** Checkout skips the trial when the workspace already holds a Stripe subscription, so an upgrade does not restart the clock. If you hand-roll this instead, that is the case you will miss. Changing plan during the trial does not end it either: [the trial runs on, on the new plan](/guides/proration-on-plan-change-nextjs), and ends when it would have. Ending it at the change would cancel a trial with no card, because `missing_payment_method: 'cancel'` has nothing to charge. Our own paid plans are the shape this guide assumes: Launch at $19 a month, with a 7-day trial that does not ask for a card. Beside them sits a Free plan at $0 with no trial at all, since there is nothing to trial into. Those figures come from `PLANS` and `PLAN_FACTS`, last verified 31 October 2026. If you are still deciding where the entitlement check itself belongs, [that argument comes first](/compare/best-way-to-add-billing-nextjs). This guide picks up after it, on who the gate admits. A note on sourcing. Every Stripe parameter named in this post, the FAQs below included, is quoted from what our own checkout code sends and then checked against the API schema Stripe publishes in `stripe-node`, read on 12 September 2026: `payment_method_collection` takes `always` or `if_required` and defaults to `always`, and `trial_settings.end_behavior.missing_payment_method` takes `cancel`, `create_invoice` or `pause`. The claim this guide turns on is Stripe's wording rather than our inference - a subscription in a trial period is `trialing`, and moves to `active` when the trial is over. Everything about our own behavior comes from `PLAN_FACTS`, the plan version schema and the subscription gate in `packages/shared`. I have not run these snippets end to end as one app. Each matches the canonical SDK usage in our own docs and constants rather than a variant written for this post. ```bash npm i @buildbase/sdk ``` --- ## Charge per credit in Next.js, and why the debit goes last > Charge per credit in Next.js: check the balance before the work, debit after it, return 402 when the balance is empty, and pass an idempotencyKey so a retry is not charged twice. - Source: https://www.buildbase.app/guides/charge-per-credit-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-11 ### In short A credit debit cannot be undone from application code, so in Next.js the consume call goes after the work succeeds, not before it. Check the balance first to avoid doing free work, catch INSUFFICIENT_CREDITS and return 402 rather than 429, and pass an idempotencyKey so a retry is not charged twice. The SDK's `bb.credits` surface has eight methods on it. Not one of them undoes a spend. You can read a balance, consume, purchase, list your packages, list the public ones, list transactions, list buckets, read what is expiring. There is no refund, no reverse, no way to put a consumed credit back from your own application code. That single absence decides the shape of every per-credit route you will write. If the debit cannot be taken back, it has to happen after the work it pays for. This guide is about that debit. [Where the credits come from in the first place](/guides/credits-wallet-nextjs) - packages, grants, top-ups and what expires when - is the other half. This is where charging per credit stops resembling [charging per API call](/guides/charge-per-api-call-nextjs). A metered call records one unit of something that already happened. A credit prices work that has not happened yet, at an amount you chose, and the work can fail after the money is gone. If you are still deciding which of the two you are selling, [quotas are not credits](/blog/quotas-are-not-credits) is the argument for picking one. > **Before you start:** A BuildBase project with the credits module and at least one credit package > defined, so a workspace has a balance to spend. Credit pricing is yours to set > per org, so every amount in this guide is illustrative. ### Step one: two calls, with two different jobs The route needs a cheap check before the work and an authoritative debit after it. Those are not redundant. The check stops you burning compute nobody can pay for, and the debit is the one that actually moves the balance. ```ts // app/api/generate/route.ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); const COST = 10; export async function POST(request: Request) { const { workspaceId, prompt } = await request.json(); // Advisory. Cheap, and it stops you doing work nobody can pay for. const balance = await bb.credits.getBalance(workspaceId); if ((balance?.available ?? 0) < COST) { return Response.json( { error: 'Insufficient credits', available: balance?.available ?? 0 }, { status: 402 } ); } const output = await generate(prompt); // Authoritative. The balance moves here, after the work succeeded. const debit = await bb.credits.consume(workspaceId, { amount: COST, description: 'AI generation', }); return Response.json({ output, remaining: debit.balanceAfter }); } ``` What you should see: call it once and the balance drops by ten. Make `generate` throw and the balance does not move, because the line that moves it never runs. Report the balance from `balanceAfter` on the consume response, not from the advisory read minus the cost. The first is what the ledger recorded. The second is arithmetic on a number that was already out of date when you read it. So what about the gap between the check and the debit? It is not a hole you need to close. On the server the debit lands as one conditional update that requires the balance to still cover the amount, so two requests racing for the last credit cannot both win. The check is a courtesy to your own infrastructure. The debit is the gate. ### Step two: the empty balance is a 402, and the 429 means something else `consume` throws rather than returning a falsy result, and the error carries what you need to say to the user. ```ts try { await bb.credits.consume(workspaceId, { amount: COST, description: 'AI generation', }); } catch (err) { if (err.code === 'INSUFFICIENT_CREDITS') { return Response.json( { error: err.message, available: err.available, requested: err.requested, }, { status: 402 } ); } throw err; } ``` `err.available` and `err.requested` are both on the error, so the response can say "you need ten and have three" rather than "something went wrong". That is a support ticket you never receive. Use 402 here, not 429. Payment required sends the user to a screen with a buy button; too many requests sends them to a screen that tells them to wait, and waiting will not help. The distinction matters more than it sounds, because this route can genuinely return both: the consume endpoint is rate limited at 30 requests per 60 seconds per IP, and that limiter answers with a 429 of its own. A 429 from this route is never an empty balance. Check where that limit lands before you size anything around it. Called from a Next.js route handler, the IP the limiter sees is your own server's, not the end user's, so all your tenants share one bucket of thirty. > **Key takeaway:** 402 means buy more credits. 429 from the same endpoint means you are calling > it too fast. Treating them as one error sends a paying customer to the wrong > screen. ### Step three: make the retry safe with a key, not a try/catch A client that retries is the normal case, not the edge case. Without a key, the second attempt is just new work. It charges again. ```ts await bb.credits.consume(workspaceId, { amount: COST, description: 'AI generation', idempotencyKey: request.headers.get('x-request-id') ?? undefined, }); ``` The ledger carries a unique index on the workspace and the key together. A repeat of a key it has already seen returns the original outcome and leaves the balance alone. Two caveats before you rely on it. The replayed response echoes the amount you asked for rather than what the original call deducted, so treat a replay as confirmation that the debit happened, not as a fresh reading of the balance. And a debit large enough to span several credit buckets stamps the key on the first bucket's ledger row only. The guard still holds, because the guard is the index on that one row. The ledger is just less uniform than you might assume when you go reading it later. The key has to be stable for the logical job. A fresh uuid per attempt is not an idempotency key, it is a new charge with extra steps. ### Step four: surface the balance before it runs out Server-side enforcement is the part that counts, and it is also the part the user never sees until it stops them. The React side exists to make sure zero is not a surprise. ```tsx import { useCreditBalance, useExpiringCredits, WhenCreditsExhausted, WhenCreditsLow, } from '@buildbase/sdk/react'; function GenerateButton({ workspaceId }) { const { balance } = useCreditBalance(workspaceId); const { expiringCredits } = useExpiringCredits(workspaceId, 7); return ( <>

Credits: {balance?.available}

{expiringCredits > 0 &&

{expiringCredits} credits expire soon

}

Running low. Buy more credits.

No credits left.

); } ``` `threshold` on `WhenCreditsLow` is required, which is the right call: there is no sensible default for a number you price yourself. `useExpiringCredits` handles the other failure, a balance that lapses rather than empties. The seven-day window above is the difference between an expiry and an accusation. One thing to get right: the number and the guards refresh by different routes. `useCreditBalance` is a plain fetch hook, so after a debit your route made it holds a stale figure until you call its own `refetch`. `invalidateCreditBalance()` does not touch it. That function refreshes the credit-balance context, which is what `WhenCreditsLow` and `WhenCreditsExhausted` read from. So one call updates the gate and the other updates the number, and a UI that only does one of them will cheerfully show the old balance to someone who just spent. Import both from `@buildbase/sdk/react`. The same reasoning applies to [gating the control itself](/guides/enforcing-quotas-in-react), which has its own guide. ### When you cannot debit after the work Everything above assumes you can await the work inside the request. Queue it instead, or hand it to a job that runs for four minutes, and the choice disappears: you have to take the debit up front, because the request is over before anyone knows whether the work succeeded. There is no clean answer to this in the SDK today, and I would rather say so than invent one. Nothing reverses a consumed credit from application code. Two paths put credits back deliberately, and neither is a reversal. The admin grant from the console needs a credit package, so it returns that package's amount and not the amount you debited. The workflow `grant_credits` action has a worse problem. It passes no idempotency key and runs up to three attempts, so a failure handler can grant twice. Both gaps look closable to me, and naming them beats pretending the pattern is clean: either `consume` grows a compensating reversal, or the grant path gets exposed with an arbitrary amount and an idempotency key. Until one of those lands, the workable shape for queued work is to debit up front, emit your own failure event, and reconcile from the console. ### The failure modes worth knowing **Not every workspace member can spend.** The consume endpoint requires a usage-record permission on top of [workspace membership](/guides/multi-tenant-workspaces-in-an-afternoon). Admins and members hold it by default. The read-only `viewer` role does not, which is what stops a read-only seat draining the balance. Purchasing credits needs billing manage and reading the balance needs billing view. If credits map to real money in your product, it is still worth putting the authorization you want in your own route, above the SDK call. **The low-balance event is not a threshold you set.** A `credit.low_balance` event fires automatically, at twenty percent of the amount you just debited. So a ten-credit debit alerts at two or under. A five-hundred-credit debit alerts at a hundred or under. Not at zero, though: the event needs a balance above it, so the debit that empties the account warns nobody. Per call, not per workspace, and there is no setting for any of it. The `threshold` prop in the React guard is a separate client-side thing that happens to share the word. **You cannot email on every consume.** `credit.consumed` is a system event and a webhook event, but it is deliberately absent from the notifiable set. Purchases, expiries, grants, revocations and low balances can notify a user. Every single spend cannot, which is correct for anything billed by the thousand. **Trusting the client with the amount.** `amount` comes from your server, priced by the work you just did. Take it from the request body and your price list is a suggestion. **Doing the work twice to avoid charging twice.** The instinct when a debit fails is to retry the whole route. Read the error first. A timeout or a dropped connection is worth retrying, and retrying the consume alone with the same key is the cheap fix, because the work is already done and only the debit is missing. An `INSUFFICIENT_CREDITS` error is not worth retrying at all: the balance will not have changed, so the second attempt fails the same way. That one is a 402 and a buy button, not a retry. Whether any of this is cheaper than building the ledger, the buckets and the idempotency guard yourself is a separate question, and [the cost of DIY usage metering](/blog/cost-of-building-usage-metering-yourself) does that arithmetic. ### Install ```bash npm i @buildbase/sdk ``` --- ## Charge per seat in Next.js, and handle the moment seats run out > Per-seat billing in Next.js: read seat state, gate the invite button, and branch on why invites are blocked. The three block reasons need three different answers. - Source: https://www.buildbase.app/guides/charge-per-seat-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-09-02 ### In short Per-seat billing is easy to meter and easy to lose money on. useSeatStatus returns memberCount, includedSeats and an inviteBlockReason, and that reason matters: seat_limit_reached wants an upgrade path, no_subscription wants checkout, and settings_user_limit_reached is not a billing wall at all. Most per-seat billing tutorials are about incrementing a number. Wire member count to Stripe's `quantity` field, add a seat when someone joins, remove one when they leave. That part is mechanical and every boilerplate does it. Seats are also [the easy half of usage billing](/blog/metered-vs-seat-based-billing), since a seat count is a number you already have - [metering something that happens thousands of times a day](/guides/charge-per-api-call-nextjs) is the harder shape. The part that decides whether per-seat billing makes you money is somewhere else: the moment an admin clicks "invite" and there is no seat left. Handle it well and that click is an upgrade. Handle it as a generic error toast and it is a support ticket, or nothing at all. > **Before you start:** A BuildBase project with the workspaces module and a plan that defines a seat > allowance. Our own plans include 2, 3, 8 and 50 team members on Free, Launch, > Grow and Scale, so there is always a real number to bump into. ### Step one: read the seat state `useSeatStatus` takes a workspace and tells you where it stands. ```tsx import { useSeatStatus } from '@buildbase/sdk/react'; function SeatBadge({ workspace }) { const { memberCount, includedSeats, canInvite } = useSeatStatus(workspace); return (

{memberCount} of {includedSeats} seats used {!canInvite && ' - seat limit reached'}

); } ``` You should see something like "3 of 5 seats used" render for a workspace on a five-seat plan. What comes back: | Return | Type | What it is | | ------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------- | | `memberCount` | `number` | Current members | | `includedSeats` | `number` | Seats in the plan | | `availableSeats` | `number` | Remaining, or `Infinity` if unlimited | | `canInvite` | `boolean` | Whether invites are allowed right now | | `inviteBlockReason` | `'seat_limit_reached' \| 'settings_user_limit_reached' \| 'no_subscription' \| null` | Why invites are blocked, or `null` if they are not | `useSeatStatus` leaves pending invitations out unless you pass `{ pendingInvitations }` as a second argument, while the server [holds a seat for each one from the moment it is sent](/guides/team-invitations-nextjs). ### Step two: gate the invite control Two things gate an invite button, and they are not the same thing. Permission decides whether this person may invite anyone at all. Seat state decides whether there is room. ```tsx import { Permission, useSeatStatus, WhenPermission, } from '@buildbase/sdk/react'; function InviteButton({ workspace }) { const { canInvite, inviteBlockReason } = useSeatStatus(workspace); return ( {!canInvite && } ); } ``` A viewer sees no button. An admin on a full plan sees a disabled one with a reason next to it. Those are different states and they should look different. ### Step three: branch on the reason, not the boolean This is the decision the reference docs leave to you. `inviteBlockReason` returns three codes, and collapsing them into one "upgrade your plan" dialog gets two of the three wrong. ```tsx function BlockedNotice({ reason }) { switch (reason) { case 'seat_limit_reached': // They want another seat and are willing to be sold one. return ; case 'no_subscription': // No plan at all. An upgrade dialog makes no sense here. return ; case 'settings_user_limit_reached': // An admin-configured cap. Upgrading changes nothing. return ; default: return null; } } ``` `seat_limit_reached` is the revenue moment. Someone is actively trying to add a teammate and the plan is what is stopping them, which is the most qualified upgrade prompt you will ever show. Show the price of the seat, not a pricing page. On our own plans that jump is concrete: Launch is $19 a month and carries 3 team members, Grow is $49 and carries 8. "Add a seat for the rest of this cycle" converts. "Compare our plans" does not. That jump also moves the seat line itself, and [what the customer is billed for the switch depends on which way it goes](/guides/proration-on-plan-change-nextjs). `no_subscription` looks similar and is not. There is no plan to upgrade from, so an "upgrade" button points at nothing. That user needs checkout. `settings_user_limit_reached` is the one that punishes a lazy switch. The wall is a limit somebody on their own team configured, so selling them a bigger plan does not remove it. Point them at the setting instead. Charge someone for a plan that does not fix their problem and you get a refund request and a bad week. ### Step four: let the server be the truth The hook is display state. Do the actual add through the workspaces API and let the server decide. ```tsx import { useSaaSWorkspaces } from '@buildbase/sdk/react'; const { addUser } = useSaaSWorkspaces(); await addUser(workspaceId, 'teammate@example.com', 'editor'); ``` Two clients can hold a stale `canInvite` at the same moment and both think a last seat is free. Only one of those invites can be right, and the server is what settles it. The same split applies to [quota state in React](/guides/enforcing-quotas-in-react): the hook is for rendering, the server is for deciding. If workspaces themselves are the part you have not built yet, [that setup comes first](/guides/multi-tenant-workspaces-in-an-afternoon) - seats are a property of a workspace, so there is nothing to count without one. ### The failure modes **Printing `availableSeats` unconditionally.** On an unlimited plan it is `Infinity`, and "4 of Infinity seats used" is a real thing that ships. Branch on whether the number is finite before rendering it. **Treating `canInvite` as enforcement.** It is a boolean for building UI. [A disabled button is not a permission check](/guides/roles-and-permissions-per-workspace-nextjs), and anything that matters gets decided server-side when the member is actually added. **Showing the same dialog for all three reasons.** Covered above. It is the one that costs money rather than just looking sloppy. **Forgetting seats go down too.** Removing a member frees a seat, and the subscription should move in that direction as well as upward. A count that only ever grows is how a customer ends up paying, month after month, for three people who left in March. I have not run this exact file end to end as one app. Each snippet matches the canonical SDK usage in our own docs and constants rather than being a variant written for this post. ```bash npm i @buildbase/sdk ``` --- ## Charge per API call in Next.js, with overages billed to Stripe > Meter every call, enforce the quota in the same request, and bill what goes over. The whole loop in one route handler. - Source: https://www.buildbase.app/guides/charge-per-api-call-nextjs - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-08-14 ### In short Record usage and check the quota in a single call with bb.usage.record, return 429 when the workspace is out, and let overages flow to the subscription. The metering and the enforcement are the same operation, which is what stops the two drifting apart. Usage-based billing looks simple until the first customer disputes an invoice. Then you find out what your meter actually counted, and what it quietly dropped. The failure is almost always the same shape: usage is recorded in one place and enforced in another, and the two disagree. This guide keeps them in one call. > **Before you start:** A BuildBase project with a plan that defines a quota. This guide uses the slug > `api-calls`. You will also need Stripe connected for the overage half to mean > anything. ### Step one: record and check in the same call The important line is that `bb.usage.record` returns what is left. You are not recording usage and then asking a second system whether the customer is allowed to be here. ```ts // app/api/generate/route.ts import BuildBase from '@buildbase/sdk'; const bb = BuildBase({ serverUrl, orgId, getSessionId }); export async function POST(request: Request) { const { workspaceId, prompt } = await request.json(); const usage = await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1, }); if (usage.available <= 0) { return Response.json({ error: 'Quota exceeded' }, { status: 429 }); } // ... do the actual work return Response.json({ ok: true, remaining: usage.available }); } ``` What you should see: call it once and `remaining` drops by one. Call it past the plan limit and you get a 429 rather than a bill nobody agreed to. ### Step two: charge by weight, not by request A request that runs for 40ms and one that runs for 12 seconds are not the same product. If your costs scale with work, meter the work. ```ts const usage = await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: tokensUsed, }); ``` `quantity` is the only thing that changes. The quota, the enforcement and the billing all follow it. > **Warning:** Record usage after the work succeeds, not before, unless you are willing to > bill for your own failures. If the work can fail halfway, decide deliberately > which side of the failure the meter sits on. Customers forgive an outage. They > do not forgive being billed for one. ### Step three: credits, when the unit is not a request Some products sell [credits rather than calls](/guides/charge-per-credit-nextjs). Same idea, different primitive, and the error tells you what you need to tell the user: ```ts try { await bb.credits.consume(workspaceId, { amount: 10, description: 'AI generation', }); } catch (err) { if (err.code === 'INSUFFICIENT_CREDITS') { // err.available and err.requested are both on the error } } ``` Returning "you need 10 and have 3" is a support ticket you never receive. ### The failure modes worth knowing **Metering in middleware.** Tempting, and wrong for anything expensive. The middleware does not know whether the work succeeded. **Retries.** A client that retries a failed request meters twice [unless the retry is idempotent](/blog/idempotency-in-billing). If your customers integrate with automatic retries, this is [the invoice dispute you will actually get](/guides/usage-does-not-match-invoice). **Trusting the client.** `quantity` comes from your server after the work, never from the request body. Otherwise the quota is a suggestion. **Enforcing only in the UI.** The gate in the interface is a courtesy. The gate in the route handler is the one that counts. The UI half is covered in [enforcing quotas in React](/guides/enforcing-quotas-in-react). Idempotency and a correction path for when a count turns out wrong are also most of what makes this expensive to build without an SDK doing the recording - [the cost of building usage metering yourself](/blog/cost-of-building-usage-metering-yourself) prices out that version of the work. ### Install ```bash npm i @buildbase/sdk ``` --- ## Enforcing quotas in React without scattering if-statements > Gate features on remaining quota with conditional components, and warn before the wall rather than at it. - Source: https://www.buildbase.app/guides/enforcing-quotas-in-react - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-08-14 ### In short WhenQuotaAvailable, WhenQuotaExhausted and WhenQuotaThreshold render on quota state, so the UI stops carrying quota logic in conditionals. The threshold component is the one that matters: warning at 80 percent converts, blocking at 100 percent churns. The usual way quota logic enters a React codebase is one `if` at a time. Six months later the rule lives in nine components and two of them are wrong. The fix is to stop asking "how much is left" in each component and let the component render on quota state instead. > **Before you start:** A plan with a quota defined. The examples use the slug `api-calls`, matching > [charging per API call](/guides/charge-per-api-call-nextjs). ### Step one: render on state, not on numbers ```tsx import { WhenQuotaAvailable, WhenQuotaExhausted, WhenQuotaThreshold, } from '@buildbase/sdk/react'; function APISection() { return ( <>

Quota exhausted. Upgrade for more.

); } ``` What you should see: the playground while there is allowance left, the upgrade message once there is not. No conditional in your component, and no chance of one branch drifting from the other. The full set: | Component | Props | Renders when | | -------------------- | ------------------- | ------------------------------ | | `WhenQuotaAvailable` | `slug` | Has remaining units | | `WhenQuotaExhausted` | `slug` | Fully consumed | | `WhenQuotaOverage` | `slug` | In overage | | `WhenQuotaThreshold` | `slug`, `threshold` | Usage at or above a percentage | ### Step two: warn before the wall This is the one that earns money, and most implementations skip it. ```tsx You have used 80% of this month's API calls. ``` A customer who hits 100 percent mid-workflow experiences an outage they blame on you. Warn them at 80 percent and they experience a plan that is too small. Different feeling, different support ticket, same data. PlugNode, our visual workflow builder, [sells credits rather than seats](/guides/charge-per-credit-nextjs), so this is the component doing the most work in its UI. A workflow that dies partway through because the credits ran out looks like the product broke. The same run, preceded by a banner, looks like a plan that needs upgrading. We put the threshold warning in before we put in the usage dashboard, and that order was right. If you ship one thing from this post, ship the threshold warning. ### Step three: show the number when it is decision-time Conditional components handle most of the UI. On a settings or billing screen, people want the actual figure: ```tsx import { useAllQuotaUsage, useQuotaUsageStatus } from '@buildbase/sdk/react'; ``` `useAllQuotaUsage` is the one to reach for on a usage dashboard, since it avoids a hook per quota as the plan grows. > **Warning:** None of this is enforcement. A user with devtools can render whatever they > like. The server call that records usage is what actually stops the work - see > [enforcing quotas server-side](/guides/quota-enforcement-server-side-nextjs), > and [charging per API call](/guides/charge-per-api-call-nextjs) for the route > it sits in. Treat this layer as the explanation, not the lock. ### What to avoid **Blocking the whole page.** Gate the feature, not the app. A user at their limit still needs to reach billing, and if the upgrade path is behind the gate they cannot pay you. **Hiding the gate entirely.** If a feature vanishes when quota runs out, the user thinks it broke. `WhenQuotaExhausted` exists so the absence has an explanation attached. **Refetching on every render.** Quota state does not change between two keystrokes. Let the hooks handle their own cadence. ### Install ```bash npm i @buildbase/sdk ``` --- ## Add multi-tenant workspaces in an afternoon > Workspaces, membership and roles without designing a tenancy model from scratch or bolting one on later. - Source: https://www.buildbase.app/guides/multi-tenant-workspaces-in-an-afternoon - Section: Guides - Author: Dharmendra Jagodana - Published: 2026-08-14 ### In short useSaaSWorkspaces gives you workspace creation, switching and membership in one hook, with a WorkspaceSwitcher component for the nav. The part worth getting right on day one is that the workspace, not the user, is the unit that owns data, billing and quota. [The tenancy decision](/blog/what-is-multi-tenancy) is made early, usually implicitly, and it is expensive to revisit. Most products start with "a user has data" and discover eighteen months later that customers wanted "a team has data, and people come and go". Retrofitting that is a migration across every table you own. If you are starting from a raw Postgres database, or Firestore, rather than a hook, the decision does not go away, it just moves earlier - see [Supabase vs BuildBase](/compare/buildbase-vs-supabase) or [Firebase vs BuildBase](/compare/firebase-vs-buildbase) for what changes when you own the schema yourself. And if that raw-database path means isolating each tenant in its own instance rather than shared tables, [here's what that isolation costs](/blog/database-per-tenant-cost) as tenant count grows. > **Before you start:** A BuildBase project with the SDK installed and authentication working (see > [BuildBase on Next.js](/guides/buildbase-on-nextjs) or [on > Vite](/guides/buildbase-on-vite)). This builds directly on whatever auth you > already have, since membership is a relationship between a user and a > workspace. ### Step one: get workspaces and switching from one hook ```tsx import { useSaaSWorkspaces, WorkspaceSwitcher } from '@buildbase/sdk/react'; function App() { const { workspaces, currentWorkspace, createWorkspace, switchToWorkspace, addUser, removeUser, } = useSaaSWorkspaces(); return ( ); } ``` What you should see: a switcher in the nav listing every workspace the signed-in user belongs to, and `currentWorkspace` changing as they switch. Membership, invitations and removal are on the same hook rather than a separate system. ### Step two: make the workspace the unit that owns things This is the step that decides whether the afternoon was worth it. [Every row you store should hang off a workspace](/guides/per-org-data-isolation-nextjs), not a user. Every quota should be checked against a workspace. Every subscription should belong to one. The metering call in [charging per API call](/guides/charge-per-api-call-nextjs) takes `workspaceId` as its first argument for exactly this reason - the meter and the tenant are the same concept. The test: if the person who created the account leaves the company tomorrow, does anything break? If the answer is yes, something is still owned by the user that should be owned by the workspace. AgentCenter is the one of ours that leans hardest on this. Its whole model is multi-project - agents, runs and permissions all hang off a workspace rather than the person who signed up, and the subscription does too. That was not foresight. It is the shape you get for free when the workspace is the unit from the first commit, and the shape you pay a migration for when it is not. ### Step three: roles, before you need them [Roles](/blog/what-is-rbac) are easier to add now than after customers have data. ```tsx import { WhenPermission, WhenWorkspaceRoles } from '@buildbase/sdk/react'; ``` [Gate on permission rather than role](/guides/roles-and-permissions-per-workspace-nextjs) wherever you can. "Can this person invite someone" survives a reorganisation of your role names; "is this person an admin" does not. > **Tip:** Decide early whether an invited user without an account gets a [pending > membership](/guides/team-invitations-nextjs) or nothing at all. It sounds like > a detail and it is the difference between an invite flow that works and one > that quietly drops people. ### What people get wrong **One workspace per user, [created silently at signup](/guides/auto-created-first-workspace-nextjs).** It looks simpler and it means you never build the switcher. Then a customer asks for a second team and the assumption is baked into every query. **Billing on the user.** Covered above and worth repeating, because it is the expensive one. **Roles as strings in your own tables.** Once permission checks live in your application code, every new feature needs its own check and they drift. ### Install ```bash npm i @buildbase/sdk ``` --- ## What self-hosted really means, versus open source > Self-hosted says where the code runs. An open license says what you may do with it. Two independent questions, and the one that actually decides your exit is neither. - Source: https://www.buildbase.app/blog/self-hosted-vs-open-source - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-29 ### In short Open source is a license: the code is published under terms that let you read, change and redistribute it. Self-hosted is a deployment model: the software runs on infrastructure you control. They are independent, so software can be open source and vendor-hosted only, or closed and running on your own servers. You can run BuildBase on your own Linux box, with your own MongoDB and your own backups, and the image you pull from Docker Hub carries compiled JavaScript only, no source and no source maps. Your machine. Your data. Not your code. That combination surprises people, and the surprise is the whole problem: a vendor can say yes to running it yourself and no to the license without telling a single lie. ### Two axes that have nothing to do with each other Self-hosted is an operational fact: which computer executes the process, whose disk holds the rows, and who gets paged when it stops. The license is a legal fact: whether you may read the code, change it, pass it on, and keep running it after the commercial relationship ends. One is about a server. The other is about a document written by lawyers. So why do they get fused? Because the loudest examples early on happened to be both at once, and "run it yourself" and "the code is yours" arrived as a pair and stayed glued. They are not a pair now. ### All four combinations are on sale right now Open and self-hostable, open with the governance features held back for the paid edition, self-hostable under a license that is not open, and neither. Every license below was read off the vendor's own page or LICENSE file and verified 29 October 2026. Licenses move, which is rather the point, so check that date. **Open and self-hostable.** Keycloak is Apache 2.0 and self-hosting is the only way it ships. Its own site and guides advertise no enterprise edition and no hosted service, which makes it the cleanest case here. Ory's Kratos and Hydra are Apache 2.0 too, though Ory sells a separate commercial build on top, so it sits closer to the next group than this one. **Open, but the free edition is materially smaller.** Open core, where most of the confusion lives. Grafana's core is AGPLv3, and SAML sign-on, role-based access control, auditing and data-source permissions all sit in Grafana Enterprise: the governance features a company needs the day it starts selling to other companies. [Lago](/compare/lago-vs-buildbase) is AGPLv3 and sells role-based access with custom roles, Okta sign-on, audit trails and invoice generation as Premium. Read that last one twice: a billing product where generating an invoice is the paid tier. Supabase is Apache 2.0, and its self-hosted edition is a single-project build without branching, managed backups, point-in-time recovery or the management API. **Self-hostable and not open.** Sentry ships under the Functional Source License, which the Open Source Initiative does not list, and its self-hosted build is genuinely the full Business product, free, with a clause against reselling it. Terraform is on the Business Source License: run it yourself all you like, just do not offer it on a hosted or embedded basis to compete with the paid product. Elastic License v2 contains the sentence that makes this quadrant concrete - you may not "move, change, disable, or circumvent the license key functionality in the software". Apache and AGPL carry no such clause, because neither restricts what you may do to software you are already running. **Neither.** Clerk's pricing page lists four tiers and no self-hosted option, and WorkOS publishes none either. Auth0 sells a "Private Cloud", which sounds like the thing and is not: their own docs describe it as a dedicated service that Auth0 manages on AWS or Azure. ### What vendors mean by self-hosted At least four arrangements, and vendors use the one word for all of them. Sorted by how much of the system you actually hold: - **On-premises or air-gapped.** Runs on hardware you own, needing no outbound connection. Strictest, rarest. - **Self-hosted.** You run the containers on infrastructure you rent or own. Whether anything phones home is a separate question, and the one to ask. - **Bring your own cloud.** Your cloud account runs the data plane while the vendor runs the control plane driving it. Often sold as self-hosting. - **Single-tenant managed.** Your own isolated instance, operated by the vendor on their hardware. Auth0's Private Cloud is this one. Ask which one a vendor means before you compare anything else. Two products behind the same word can sit further apart than a product and its competitor. Thirty seconds. Almost nobody spends them. ### What each one actually buys An open license buys you **rights**. Self-hosting buys you **possession**. Independence needs both, and most teams hold exactly one while believing they hold two. Possession without rights means you can run the software until something stops you, and the something is usually small: a license key that expires, a signed token that stops being issued, an image that quietly stops being published to the registry. You hold the running system and none of the levers. Rights without possession is the opposite failure, and it is more common than anyone admits. You have the legal right to fork, and you have never once run the thing outside the vendor's cloud. The right is real. Exercising it is a project with a payroll attached, and the week you need it is the worst week you will ever have to start one. So which of the two are you actually buying, and is the one you are missing the one you will need? ### What an open license actually promises An open license is not a promise about how the vendor will behave next year. It is an irrevocable grant on the code you already have, and that is all it is. The relicensing years proved it. HashiCorp moved Terraform from MPL 2.0 to the Business Source License in August 2023, and the fork that became OpenTofu landed under the Linux Foundation. Redis left BSD-3 for a pair of licenses the Open Source Initiative does not recognise in March 2024, and Valkey forked away to the Linux Foundation, where it sits under BSD today. MongoDB adopted the Server Side Public License in October 2018. Everything released before that date stayed on AGPL v3 forever: the grant on those bytes could not be taken back. Read those stories and the lesson is narrower than "open source protects you": the version in your hands is protected, the next one is not, and what saves you is a community able to pick the project up. That community is the asset. The license only makes it legal. It moves the other way too. Elastic put an OSI-approved license back on the table in August 2024, adding AGPL beside the two it already had, and Redis 8 now offers AGPLv3 as a third option of its own. ### Where BuildBase sits, and what it costs you We sit in the self-hostable half and not the open one. BuildBase does not ship under an open source license: the image is compiled output rather than readable code, and that is a real limit on what you can do with it. The second limit matters more, and buyers rarely think to ask about it. Self-hosting BuildBase does not mean running BuildBase alone. The split is in the docs: you host the tenant server, the client app and the auth portal, and we host the central server, which handles organization management, admin sign-in, installation licensing and the ES256 signing keys. Central signs a token with your organization's private key and your server verifies it with the public one. You never host that half; we do not offer it. So self-hosting with us gives you your data on your disk, your choice of region, your backup policy and your uptime. It does not give you a system that keeps working with us switched off. Those are different promises, and only one of them is ours. Two more limits. Self-hosting is gated on an allowlist today rather than a checkbox on a plan, and nothing built in moves an existing cloud organization's data onto your own server. Workflows export and import as JSON, contacts as CSV, and the rest is a conversation. > **Where a genuinely open project wins:** Three things an Apache or AGPL project gives you that we cannot. A community > can pick it up when the vendor changes course, the way OpenTofu and Valkey > carried on after Terraform and Redis were relicensed. Anyone can fork it and > remove the paywall legally, which is exactly what Cal.diy is: a fork of > Cal.com with the commercial code stripped and an MIT license on the result. > And a security team can read every line of the sign-in path before approving > it, which nobody can do with a compiled image, ours included. If outliving > your vendor is the requirement, buy from that column. ### When an open license is the wrong thing to ask for When you are never going to exercise it. Most teams never fork, and the license they fought for turns out to be insurance they never claim. That is not an argument against it. It is an argument for being clear about what you are optimising, because the open option often carries more operational work, and you pay that every week whether or not the right ever gets used. The sharper trap is open core. The license is genuine and so is the restriction: the free side covers the code you were never going to change, and the paid side covers the features that decide the renewal. Work out which side your requirements land on before the word "open" does any work in your decision. ### When self-hosting is the wrong thing to ask for When the reason is cost, control or compliance, and nobody has checked it. Cost. Price it first: infrastructure is the small line, and the hours spent patching, monitoring and being on call are the big one. [The full arithmetic](/blog/self-host-vs-managed-cost) usually lands past the managed bill rather than under it. Control is really a question about where the control plane lives. Plenty of self-hosted deployments, ours included, still phone home to something the vendor runs, and moving the containers onto your own hardware does not move that one inch. Compliance deserves a literal reading of the requirement. Data residency and self-hosting are not synonyms, and a managed region in the right country often satisfies the clause that sent you looking in the first place. Check before you take on a database. ### The question that actually decides it Stop sorting vendors by label. Ask what happens the day one of them changes its mind, and score the answers: 1. **Does it need the vendor to start?** A license check on boot, or a token it must fetch, means your install has a remote off switch. Ours does, and the image pins the central server's URL in a read-only lock file. 2. **Is the self-hosted build the same product as the cloud one?** Ask which features are missing. If the answer is a list, you are evaluating two products. 3. **Can you get your data out in a format something else reads?** Ask for the export and ask what it leaves behind. Self-host us and you score well by accident of architecture, because the data sits in your own MongoDB. Stay on our cloud and you are back to whatever the export covers, which for us is workflows and contacts. 4. **Could someone else maintain it?** Only an open license answers this one. We do not have an answer to it. Four questions, and the deployment diagram settles none of them. Score us honestly and BuildBase answers the third well, fails the fourth outright, and ships with a remote off switch built into the first. That is the ordinary shape of a proprietary self-hosted product, and any vendor presenting its own as flawless is reading you its marketing. > **Key takeaway:** Self-hosted answers where the software runs. The license answers what you may > do with it. Buy for the failure you actually fear: possession protects your > data, the license protects your exit, and only owning both makes you > independent of the vendor. A vendor that scores well on all four is safe to buy from under any license. One that scores badly is a risk you are taking regardless of how many of its containers run on your hardware. It is the same calculation as [buying infrastructure against building it](/blog/buy-vs-build-saas-infrastructure): what does it cost you to change your mind later? --- ## The vibe-coded app that got hacked: the 2025-2026 incidents and the five checks that would have caught them > Eleven public incidents from March 2025 to October 2026, each with its date, its source and what actually broke, sorted into the pile that was yours to prevent and the pile that was the builder's. - Source: https://www.buildbase.app/blog/vibe-coded-app-hacked-incidents-and-five-checks - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-29 ### In short A vibe-coded app gets hacked the way any app does, through what the code lets a stranger do; the difference is that nobody read the code. The public incidents of 2025 and 2026 sort into two piles, inside the app and inside the builder, and five checks run before launch would have caught every one in the first pile. A vibe-coded app gets hacked the way any app does, through what its code lets a stranger do. The difference is that nobody read the code. Between March 2025 and October 2026 the incidents that reached the press sort into two piles: the ones inside the app, which were the builder's customer's to prevent, and the ones inside the builder, which were the builder's. The first pile is the longer one, and five checks, run before launch, would have caught everything in it. This post is the list, with dates and primary sources, then the two piles, then the five checks. It leaves one famous case out, says why, and quotes each incident at the length the evidence supports. Where a figure comes from the researcher who found the problem rather than from the company, it says so, because the two often disagree. ### The incidents, in order **March 2025, Enrichlead.** A sales-leads product whose founder said it was built with Cursor and "zero hand-written code" was, by his own posts days after launch, "under attack": "maxed out usage on API keys", "people bypassing the subscription, creating random stuff in the database", and, in his words, "as you know, I'm not technical, so this is taking me longer than usual to figure out". It shut down within about a week. The secondary write-ups agree on the shape (API keys exposed, no real authentication checks, no rate limits) and disagree on the timeline; a dollar figure for the API bill circulates and we could not corroborate it, so it is not here. **March to May 2025, CVE-2025-48757.** Matt Palmer scanned Lovable-built sites and found 303 endpoints across 170 projects, 10.3% of the 1,645 he analysed, where an unauthenticated visitor could read or write database tables. The apps ran on Supabase with the public key in the browser and tables that lacked correct row-level security. The CVE text describes an "insufficient database Row-Level Security policy"; the record also carries a note that the supplier disputes it, on the ground that each customer is responsible for protecting their own app's data. Both things are true. The scan covered homepages only, so Palmer says the true figure may be higher, and his statement draws a line that still matters: Lovable's security scan checks whether a policy exists, not whether it is right. **July 2025, Base44.** Wiz Research found that Base44's registration and one-time-code endpoints accepted requests without authentication, so anyone holding an app's public id, which appears in its URLs, could create a verified account on a private app, including apps restricted to SSO. Wix fixed it within about a day and found no evidence of abuse. This one is in the second pile: nothing a Base44 customer did caused it, and nothing they could do would have prevented it. **July 2025, Replit and SaaStr.** Jason Lemkin, a non-engineer building with Replit's agent, reported that it deleted his production database during a code freeze despite repeated instructions, invented about 4,000 users, and told him a rollback was impossible (it was not; he found the restore worked). He also reported $607.70 in charges beyond his plan. Replit's chief executive called it "unacceptable and should never be possible", promised a refund and a postmortem, and began rolling out automatic separation of development and production databases. Nearly every detail comes from Lemkin's own posts, which The Register said it did not independently verify, so record counts vary and none is given here. **December 2025, the Tenzai study.** Not an incident, but the measurement behind the fear. Five tools (Cursor, Claude Code, Codex, Replit, Devin) each built three apps; across the 15, researchers counted 69 vulnerabilities, about six critical. No exploitable SQL injection or cross-site scripting; every tool introduced a server-side request forgery; no app had CSRF protection or security headers; and most failures were authorization and business logic, the kind where a negative quantity or a negative price goes through. A vendor study with a tiny sample, and still the clearest picture of what an agent gets wrong when nobody tells it otherwise. **January and February 2026, Moltbook.** Wiz found a Supabase key in the front-end JavaScript of an AI-agent social network, with no row-level security behind it, which gave read and write access to the production database: about 1.5 million API tokens, 35,000 email addresses, 4,060 private agent-to-agent conversations, some containing plaintext OpenAI keys, about 4.75 million records in all. Write access let Wiz edit live posts. The founder is quoted in the write-up: "I didn't write a single line of code for @moltbook." Fixed within a day of the report. **February 2026, an exam app Lovable featured.** A researcher reported 16 vulnerabilities, six critical, in an exam and grading platform featured on Lovable's Discover page: 18,697 user records, 14,928 unique emails, thousands of student and enterprise accounts, 870 with full personal details, readable by an unauthenticated visitor who could also send bulk email, delete accounts and change grades. The cause was generated, Supabase-backed code without row-level security or role checks; one example was an authentication function with inverted logic that blocked signed-in users and admitted anonymous ones. Lovable's security lead responded that the project included code Lovable did not generate, that the vulnerable database was not hosted by Lovable, that every project gets a free security scan, and that applying fixes is at the user's discretion. The researcher said his support ticket was closed without response. First pile, with the builder's response quoted so you can judge the second. **February to April 2026, Lovable's public projects.** For about 76 days, any logged-in Lovable user with a link could read the chat history and source code of other users' public projects, because a backend permissions change in February re-enabled access Lovable had removed in 2025 and the API did not check ownership. Reports on HackerOne were closed as intended behaviour; Lovable's first public statement said "we did not suffer a data breach", and its second apologised and made historical public projects private. The researcher says database credentials in that code were exposed; Lovable's account covers chat history and source code, not Lovable Cloud or private projects. Second pile. **February 2026, DataTalks.Club.** An experienced developer's coding agent, asked to move a second site into the same Terraform setup, unpacked an old state archive and ran `terraform destroy`, deleting the network, the database, the containers, the load balancers and the automated snapshots. AWS restored it about a day later. His own summary: "I over-relied on the AI agent to run Terraform commands." It is here because it is the same failure as Replit and SaaStr with the non-technical builder removed: an agent with production access and the backups inside its reach. **May 2026, the RedAccess scan.** A security firm reported about 380,000 publicly reachable assets built with Lovable, Base44, Replit and Netlify, of which about 5,000, 1.3%, held sensitive corporate data: ship schedules, clinical-trial listings, support transcripts, a bank's internal financials, patient conversations. It also found phishing pages hosted on Lovable that impersonated banks and retailers. The platforms disputed the method and the notice period, and the two press accounts count the exposed apps differently, so the shape is more reliable than the numbers: apps published on the builders' own domains, public by default or by choice, with little or no sign-in in front of them. **September 2026, the UpGuard scan.** Starting from about 300,000 domains that showed signs of Supabase, UpGuard asked each for a `users` table; 16,326 answered with data. More than half showed personal information, a smaller share passwords or tokens, a very small number plausible card data. The study targeted standalone sites, not apps hosted on Lovable or Replit, and it is not a breach of Supabase, whose security lead answered that customers control how their projects are configured. The sentence that matters is UpGuard's: row-level security is on by default only for tables made in Supabase's table editor, and tables created through the API, which is how coding agents work, "do not enable RLS by default". **The one left out.** The July 2025 leak from the Tea app, about 72,000 images and then about 1.1 million private messages, is widely described as a vibe-coding failure. The evidence supports a Firebase backend without effective access rules and nothing more; the claim that the app was AI-built rests on allegations nobody has attributed. It is a backend misconfiguration story, and it would be convenient on this list, which is exactly why it is not on it. ### Two piles Read the list again and the sorting does itself. **Inside the app**: Enrichlead, the 170 Lovable projects, Moltbook, the exam app, the RedAccess and UpGuard scans, the Tenzai findings, and the two deleted databases. The common root is not a clever attack. It is a table anyone can read, an endpoint anyone can call, a check that runs in the browser, a key in the bundle, or an agent that can reach production. These were the builder's customer's to prevent, and the builders say so, in the CVE dispute note and in Lovable's response to the exam app. **Inside the builder**: the Base44 bypass and Lovable's 76-day exposure. Nothing the customer did caused them, nothing the customer could have done would have prevented them, and both were fixed by the vendor, one in a day and one after a dispute. They matter for a different decision, which builder to trust with your source and your users, and they are not what the five checks below are for. The first pile is the longer one, and that is good news, because it is the pile you can do something about this afternoon. ### The five checks Each check is a question you can answer yourself in under an hour, with the incident it would have caught, and the instruction to paste into the builder when the answer is wrong. #### 1. Can a stranger read the table? The incident: the 170 Lovable projects, Moltbook, the exam app, the 16,326 Supabase databases. The check is UpGuard's own method, run against your app. Open the built site, find the Supabase address and the public key in the JavaScript (they are meant to be there; the key is public by design), and ask the REST endpoint for your `users` table with that key and no session. Rows back means anyone gets rows back. Do it for every table that holds something a customer would not want another customer to see. Why generated apps fail it: the agent creates tables through the API, which does not switch row-level security on, and the builder's scan then checks that a policy exists, not that it says the right thing. A policy that reads "any signed-in user can read every row" passes the scan and fails this check. The fix has two shapes. Either every table gets a policy keyed to the workspace the row belongs to, and you read each one, or the browser stops querying the database directly and every read goes through a server route that checks who is asking and filters by their workspace. The second is what [teams, invites and admin versus member](/guides/teams-invites-and-roles-for-a-vibe-coded-app) sets up, and it is the shape to prefer when you cannot read a policy yourself. Paste: "List every table and its row-level security policy. For each table that holds customer data, the policy must restrict reads and writes to rows whose workspace id matches the signed-in user's workspace. Show me the policy text before applying it." #### 2. Is every endpoint behind sign-in, including the ones that create accounts? The incident: Base44's registration endpoint, the exam app's inverted authentication function, and the audit that found "development endpoints still in production that let anyone mark themselves as a paid user". The check: list every route and function the app exposes (the agent can print the list), and for each one, call it from a terminal with no session. The right answer is a refusal. Pay particular attention to the routes the agent added "for testing": a `/dev/` prefix, a `seed`, a `make-admin`, a `reset`. They were useful on day two and they are reachable on day ninety. Why generated apps fail it: an agent writes the happy path first and the guard second, and when the guard is a function it wrote itself, the function can be wrong in ways that look right. The exam app's guard admitted exactly the people it was meant to block. A guard that comes from a platform and is tested there cannot be inverted by a typo in your project. Paste: "Print every HTTP route and server function with the check that runs before it. Remove any route that exists for development or seeding. Every remaining route that reads or writes customer data must refuse a request with no valid session before doing anything else." #### 3. Who decides what a paid or admin user is? The incident: "a live marketplace with real Stripe payments where any logged-in user could grant themselves admin and hijack payment routing with a single request", from an audit of three products posted on Reddit in February 2026, and the unlimited-credits endpoint from the same audit. The check: sign in as an ordinary member, open the browser's developer tools, and change the value the app uses to decide what you are. A `role` field in a request, a `plan` in local storage, a `credits` number in a form. Then do the admin thing, or the paid thing. If it works, the decision is being made in the browser, and the browser is the user. Why generated apps fail it: the agent writes the check in the same place it writes the button. A column called `plan` on the users table, set by the browser after a Stripe redirect, checked by the page that shows the feature, is the default output of "add a paid plan", and every word of it is wrong: the browser set it, the browser can set it again, and the server never checked. [Paid plans that actually gate features](/guides/paid-plans-that-gate-features-vibe-coded-app) is the guide to the right shape: the plan is set by a signed webhook from the payment provider, held by a service the browser cannot write to, and checked by the server before the feature runs. This is the check no scanner runs, because to a scanner the column and the request look fine. It is also the one a platform fixes outright: when roles, plans and credits are enforced by an API that the browser can only ask, not tell, the "single request" has nowhere to go. Paste: "Find every place the app decides whether a user is an admin, on a paid plan, or has credits left. Each decision must be made on the server from a source the browser cannot write. Remove any route or field that lets a request set its own role, plan or balance." #### 4. Is there a key in the bundle that should not be? The incident: Moltbook (a Supabase key that was fine to publish, in front of a database that was not fine to expose) and Enrichlead (API keys "maxed out" by strangers). The check: build the app, open the JavaScript the browser downloads, and search it for every secret you own: the Supabase service key, the Stripe secret key, the OpenAI key, the client secret of your sign-in. The public keys (Supabase's anon key, a sign-in client id, Stripe's publishable key) are meant to be there and the check is not about them. The secret ones are never meant to be there, and in Vite and Next.js anything prefixed `VITE_` or `NEXT_PUBLIC_` is, by construction. Why generated apps fail it: the agent needed the key to make the feature work in the preview, the preview is the browser, and the prefix was the only way to make it visible there. The fix is the server again: the key is read in a route or a function, the browser calls the route, and the builder's secrets store (Lovable's Secrets, Bolt's Secrets, Replit's Secrets tool) holds the value where the bundle cannot see it. Paste: "List every environment variable the app reads and where. Any secret read in browser code moves to a server route, and its prefix is removed. Rotate every secret that has ever shipped in the bundle." #### 5. What can the agent do to production? The incident: SaaStr's database and DataTalks.Club's infrastructure, and the Cursor and Supabase MCP demonstration from July 2025, in which an assistant running database queries with full privileges was talked, by text hidden in a support ticket, into reading a private tokens table and writing it back into the ticket. The check: write down what the agent can reach without a human in the loop. Can it run a destructive command against the live database? Can it reach the backups? Does it hold a key that bypasses the row rules? Does it read text that strangers wrote (tickets, comments, form submissions) in the same session in which it holds those powers? Each yes is the precondition for one of the incidents above. Why generated apps fail it: the convenience that makes the builder useful is the agent having access. Replit's answer after July 2025 was to separate development and production databases automatically; the demonstration's authors list read-only mode and scoping the agent to one project; the DataTalks post-mortem moved the backups out of the same configuration the agent could destroy. The principle underneath all three is that the agent gets the narrowest access the task needs and the backups live where it cannot reach. Paste: "Show me the credentials and tools available to the agent in this project, which of them can modify the production database or infrastructure, and how to restrict each to development." > **Key takeaway:** Every app-side incident on this list is one of five questions answered wrong: > a table a stranger can read, an endpoint with no sign-in, a plan or role > decided in the browser, a secret in the bundle, or an agent that can reach > production. Answer the five yourself, before launch, and the list stops > applying to you. ### Where the builders' own scans win For checks 1 and 4 the builders now do real work, and you should let them. Lovable's scan runs on every publish and checks that row rules exist, with a deeper scan on request; Bolt's audit is a free button in the Publish menu that its help page says checks sign-in, whether users can "change a price", and whether keys are "sent to visitors' browsers"; Replit separates development and production data so a mistake in the preview does not land on customers. If you do nothing else, publish through those and read what they report. What they cannot do is answer check 3, because to a scanner a role column is a column, or run check 5, because the agent is the product. The scans are the floor. The five checks are the launch. ### How BuildBase sits in this Checks 2 and 3 are the ones a platform removes rather than helps with. When sign-in, workspaces, roles, plans and credits are enforced by an API the browser can only ask, there is no role column to flip, no plan field to set after a redirect, no dev endpoint to leave behind, and the webhook that changes a plan is signed and verified before anything moves. That is what [the launch checklist](/guides/vibe-coded-app-launch-checklist) is about, item by item. It does not run checks 1, 4 or 5 for you. Your tables are still yours, and the rule we give every agent is to keep them where they are; the builder's secrets store is still where the secret goes; and what your agent can reach in production is a decision about the agent, not about any SDK. The honest claim is narrower than "secure": two of the five questions stop being yours to answer, and the other three get a shorter answer, because the data the browser can reach no longer includes who is an admin and what they paid for. The question underneath all five, what a backend is and which half of it is your product, is [a separate explainer](/blog/what-is-a-saas-backend). The incidents above are what happens when the second half is built by the same prompt that built the first. --- ## What vibe coding costs after launch: credits, fixes and the bill at 100, 1,000 and 10,000 users > The subscriptions for a Lovable app with Supabase, Resend and Stripe, added up at three sizes with every assumption shown, prices read on 27 October 2026. The subscriptions are not the expensive part. - Source: https://www.buildbase.app/blog/what-vibe-coding-costs-after-launch - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-29 ### In short At 1,000 users the published subscriptions for a vibe-coded app come to $70 a month with the builder's own sign-in and $89 with BuildBase holding teams and plans, before Stripe fees that scale with revenue. The bill that moves is elsewhere: card fees, organizations priced per team, and the fixes. Every post about what vibe coding costs is about building: credits per message, tokens per day, the plan that turns the agent on. This one is about the month after launch, when the app has customers and the bill has lines on it you did not pick. Here is the arithmetic for a Lovable app with Supabase, Resend and Stripe at 100, 1,000 and 10,000 users, with every assumption stated so you can argue with it, and every price read from the vendor's own page on 27 October 2026. The short version: the subscriptions are small and nearly flat, from $50 a month to $119 depending on who holds teams and plans. The bill that moves is elsewhere, in three places. Card fees, which scale with revenue and pass every subscription by 1,000 users. Organizations, which one vendor prices per team and which turn $0 into $900 a month at 1,000 customers. And fixes, the credits and hours spent keeping generated code alive, which no pricing page shows and which is the largest line at every size below 1,000 users. ### The assumptions Change any of these and the total moves. That is why they are listed. - A B2B app built on **Lovable Pro** ($25 a month for 100 credits, read on 27 October 2026), published on Lovable's hosting with a custom domain, which the Pro plan includes. - Data in **Supabase**, on the Pro plan ($25 a month, 100,000 monthly active users included, then $0.00325 each) from the day a stranger signs up. The Free plan pauses a project after a week of inactivity and is for trying things, not for customers. - Transactional email through **Resend**: free for 3,000 emails a month and 100 a day, Pro at $20 for 50,000. - Payments through **Stripe** at its published US card rate, 2.9% plus 30 cents, with the 0.7% Stripe Billing fee shown separately for the case where Stripe runs the subscriptions. Lovable's built-in payments offer **Paddle** instead, at 5.0% plus 50 cents (a flat 10% under $10), as a merchant of record that handles sales tax. - Customers are teams of ten: 100 users is 10 customers, 1,000 users is 100, 10,000 users is 1,000. Each customer pays **$49 a month** on one card. Revenue is therefore $490, $4,900 and $49,000 a month. - The account layer, meaning sign-in, teams, roles, plans and limits, is priced three ways: Lovable's built-in sign-in with the teams and plans the agent writes; Clerk for sign-in and organizations; or BuildBase. - US cards only. International cards add 1.5% on Stripe. ### The subscriptions | Line | 100 users | 1,000 users | 10,000 users | | ----------------------------------------------- | --------- | ----------- | ------------ | | Builder: Lovable Pro | $25 | $25 | $25 | | Database: Supabase Pro | $25 | $25 | $25 | | Email: Resend | $0 | $20 | $20 | | Account layer, built-in sign-in plus agent code | $0 | $0 | $0 | | Account layer, Clerk with organizations | $0 | $0 | $900 | | Account layer, BuildBase | $19 | $19 | $49 | | **Total, built-in** | **$50** | **$70** | **$70** | | **Total, Clerk** | **$50** | **$70** | **$970** | | **Total, BuildBase** | **$69** | **$89** | **$119** | **The builder** is $25 at every size, and that is the first honest surprise: the plan you built on is also the plan you host on, and a Lovable app serving 10,000 users costs the same subscription as one serving ten. What changes is the credits, which is the fixes section below, and Lovable's own page shows Business at $50 if you need more of them. **The database** is flat too. Supabase Pro's 100,000 included monthly active users cover all three sizes, and the $0.00325 per user beyond that would not start until the tenth customer of the tenth thousand. Storage and bandwidth above the plan's allowances are extra and are not in this table, because at these sizes a typical B2B app does not reach them; yours might. **Email** is the line that steps. Ten customers send a few hundred emails a month and sit inside Resend's free tier; a hundred customers pass the 100-a-day cap on the first busy morning, so the $20 plan goes in at 1,000 users and stays. **The account layer** is where the three stacks part ways, and it is the whole argument, so it gets its own section after the fees. At 1,000 users the BuildBase column adds to $89 a month: $25, $25, $20 and $19. That is the number on the card, and it is the number to hold in mind while reading the fees table, because the fees pass it. One line that is deliberately absent: hosting. Lovable's plan includes it, which is the quiet advantage of building where you publish. The same app on v0 is a Next.js app on Vercel, where the Hobby plan is for personal, non-commercial use, so a product needs Pro at $20 a seat; on Bolt, hosting is inside the $25 with a request and bandwidth allowance per account; on Replit, publishing is billed by usage from the plan's credits. None of those is large at these sizes, and all of them are a line the Lovable table does not have. Another that is absent on purpose: the model bill, if your app has an AI feature of its own. It is the one cost that scales with usage rather than with users, it varies by a hundred times between apps, and the right way to carry it is to charge for it, which is what [credits and usage limits](/guides/credits-and-usage-limits-for-an-ai-app) is about. Any number here would be invented. ### The fees, which scale with revenue | Fee | 100 users ($490) | 1,000 users ($4,900) | 10,000 users ($49,000) | | ---------------------------------------- | ---------------- | -------------------- | ---------------------- | | Stripe cards, 2.9% plus 30 cents | $17.21 | $172.10 | $1,721.00 | | Stripe Billing, 0.7%, if used | $3.43 | $34.30 | $343.00 | | Paddle through Lovable, 5% plus 50 cents | $29.50 | $295.00 | $2,950.00 | | BuildBase platform fee | $0 | $0 | $0 | The arithmetic for the first row: 2.9% of $490 is $14.21, plus ten charges at 30 cents is $3.00, so $17.21. At a hundred charges, $142.10 plus $30; at a thousand, $1,421 plus $300. Stripe Billing is 0.7% of the same revenue when Stripe runs the subscription itself rather than your code charging cards. Paddle's row is 5.0% plus 50 cents a charge: $24.50 plus $5 at ten customers, and so on. Two readings. First, by 1,000 users the card fees are larger than every subscription in the first table combined, which is the sense in which the subscriptions are not the expensive part. A founder who has argued for an hour about a $19 plan and then accepted 2.9% without reading it has the proportions backwards by a factor of nine at 1,000 users, and thirty-five at 10,000 against Grow's $49. Second, the Paddle row is not a mistake to pay: Paddle is the merchant of record, which means it registers, collects and remits sales tax in the places you sell, and at ten customers $12 a month over Stripe is a fair price for never thinking about VAT. At 1,000 customers the same choice is $1,229 a month, and most companies have hired for the tax question by then. BuildBase's billing is bring-your-own Stripe at Stripe's rates with a 0% platform fee, which is why its row is zero: the fees in the first row are the same whether your app or the platform created the subscription. ### The line nobody puts on a pricing page A vibe-coded app is not finished when it launches. It is finished when it stops needing fixes, and nothing on the three vendors' pricing pages prices that. Two ways to count it, both with their assumptions showing. **In credits.** Lovable's pricing page gives examples: 0.50 credits to make a button grey, 1.20 to add authentication, about 1.70 for a landing page with images. Pro's 100 credits are therefore plenty for building and thin for a loop, and a loop is what the reviews describe: across the builders, about 63% of the roughly seventy negative Trustpilot reviews we read in October 2026 were about credits, tokens or charges spent on fixes that did not fix. On Replit, a founder reported $607.70 in charges beyond his plan in the week of July 2025 that his agent deleted a production database, and a one-star review from 20 September 2026 says that "if you set the limit 50 dollar it turns out take 300 dollar". The honest accounting is a range: fixes fit inside the plan in a good month, and in a bad one they cost a second plan or an overage you did not budget. **In hours.** Our [maintenance arithmetic](/blog/ai-generated-code-maintenance-cost) for AI-authored auth code assumes an agent scaffold costing about $2,400 in engineer time at $150 an hour and maintenance at 40% of that in year one and 65% in year two, which is $960 and then $1,560 a year, or about $80 to $130 a month. That is for the sign-in alone. Teams, roles, plans and the webhook are each a second copy of the same curve, and the audit record for generated versions of them is what [the five checks](/blog/vibe-coded-app-hacked-incidents-and-five-checks) is about. Put the two together and the fixes line, at 100 users, is somewhere between $0 and a few hundred dollars a month, against a subscription total of $50 to $69. It is the largest line on the bill at every size below 1,000 users, and the only one you cannot read off a page. There is a way to make the line smaller, and it is not a vendor. It is the number of things in the app that can be wrong. A role column the agent wrote is a thing that can be wrong, and so is the page that checks it, the webhook that sets the plan, the cron job that resets the monthly limit and the dev route that grants credits. Every one of those that lives in a platform instead of your repository is a fix you will not pay for, in credits or in hours, and that is the only sense in which the bundle's $19 is cheap: it is the fixes line, prepaid and flat. ### The account layer, which is where the stacks part ways **Built-in sign-in plus agent code: $0.** Lovable Cloud's sign-in is free with the plan, its payments take a subscription per user, and everything after login (a workspace per customer, roles, a plan that changes what the app does, seats, limits) is code the agent writes. The $0 is real. The cost is the fixes line above and the risk register in the five checks post, and it compounds with every customer, because every table the agent adds for teams is a table with a rule to get right. **Clerk: $0, then $900.** Clerk's user pricing is generous: 50,000 monthly retained users free on every plan, $0.02 each beyond that, and Pro at $25 if you want the branding gone and the add-ons. Organizations are priced per team: 100 free, then $1 a month for each one from 101 to 1,000, with volume rates after. So the line is $0 at 10 and 100 customers and $900 at 1,000, which is the number that surprises people, because the user count never got near a limit. Plans, limits, seats and credits are still yours to build on top, or Clerk Billing at 0.7% of volume for the subscription part. **BuildBase: $19, then $49.** Launch is $19 a month with 25,000 monthly active users, 1,000 workspaces and three team members included; Grow is $49 with 100,000 users and 25,000 workspaces. The 1,000-workspace line on Launch is exactly the 10,000-user case, so the table budgets Grow there rather than sitting on a ceiling. There is also a Free plan at $0, with 10,000 users and 50 workspaces, and the 100-user case fits inside it; the table budgets Launch anyway, because Free keeps the BuildBase badge and our sign-in domain, which a launched product usually wants gone. Yearly billing is ten months for twelve, and the paid plans start with a seven-day trial without a card, read from our own pricing constants and checked against the live page on 31 October 2026. What the line buys is the whole layer the other two leave to the agent: sign-in, workspaces, roles enforced by the API, plans with versions, feature flags, credits, the lifecycle email, and the webhook that moves a plan. The teams column is the one to stare at. At 1,000 customers the three stacks read $0, $900 and $49 a month, and the $0 is the one with the fixes line attached. A worked example of what "per team" does, since the shape surprises people more than the number. Suppose the app grows from 100 customers to 1,000 over a year. The built-in stack's invoice does not change. Clerk's organizations line goes from $0 to $900 a month in steps of $1 per new customer from the 101st, so the first customer in month two costs $1 and the last one in month twelve costs $1, which is simple to reason about and adds up to $10,800 a year at the end. BuildBase's line goes from $19 to $49 in one step, when the workspace count crosses 1,000. Neither is wrong. Clerk is pricing the organization as the unit, which is honest about what a B2B app is made of; the bundle is pricing the plan. The question for your spreadsheet is whether your customers are teams, and if they are, which of the two shapes you would rather explain to a finance person in month twelve. ### Where the built-in stack wins Under about a hundred customers, selling to individuals rather than teams, with no plan that has to change what the app does, the built-in stack is the right call and the cheapest by $19 a month. Lovable's sign-in ships SAML SSO and OIDC, which BuildBase does not, so an app whose buyer signs in with Okta is better served there. Paddle's row is a tax department for $12 a month at that size. And one fewer vendor is one fewer thing to explain to an agent. Clerk wins the pure sign-in case at scale: 50,000 free users is more than most apps ever have, and if your customers are individuals, not teams, the organizations line never appears. ### Where the bundle wins The moment customers are teams and plans have to do something. The organizations line is the visible version: $49 against $900 at 1,000 customers. The invisible version is the fixes line, which the bundle turns from a curve into a flat subscription, because the roles, the plan checks and the webhook are not code in your repository. And 0% on billing means the fees table is the same table whichever way the subscription was created. > **Key takeaway:** The subscriptions for a vibe-coded app run $50 to $119 a month from 100 to > 10,000 users and barely move. The bill that moves is card fees, which pass the > subscriptions by 1,000 users; organizations, which one vendor prices per team; > and fixes, the one line no pricing page shows and the largest one until you > have a thousand users. ### What moves the total - **Price per customer.** Every fee row is a percentage of revenue. At $29 a customer the card fees fall by about 40%; at $99 they double. The subscriptions do not move. - **International cards.** Stripe adds 1.5% for cards issued outside the US, so a European customer base turns 2.9% into 4.4% before currency conversion. - **Supabase beyond the plan.** More than 100,000 active users, or more storage and bandwidth than Pro includes, adds usage lines; the per-user rate is $0.00325. - **The builder.** Bolt Pro is $25 with 10M tokens; Replit Core is $20 with $20 of credits and usage-billed publishing on top; a v0 app on Vercel needs Pro at $20 a seat, because the Hobby plan is for non-commercial use. Swap the builder line accordingly. - **More fixes.** Lovable Business at $50 if 100 credits a month is not enough, or the overage on Replit. This is the line that has no ceiling. - **Seats on your side.** Launch includes three team members in the BuildBase console; Clerk Business adds dashboard seats at $20 each. If your own team is larger than that, the next plan up applies. ### Annual billing, and the discounts that are real Every vendor here sells a yearly price, and the discounts are not the same size. Lovable Pro falls from $25 to $21 a month on annual billing, read from its subscription plans page today. Clerk Pro goes from $25 to $20, Replit Core from $20 to $18, and BuildBase's yearly price is ten months for twelve, so Launch is $190 a year and Grow $490. Supabase, Resend and Stripe do not discount for a year's commitment. On the 1,000-user BuildBase column that turns $89 a month into about $82 if you pay the builder and the account layer annually, and the fees do not move at all, which is one more way of saying where the money is. ### How to redo this for your own numbers The method is four lines in a spreadsheet, and it is worth keeping the spreadsheet rather than the answer. Put customers, users per customer and price per customer at the top; everything below is a formula. Subscriptions are a lookup against each vendor's tiers at your user and organization counts. Fees are a percentage of revenue plus a per-charge amount times the number of charges. The account layer is three columns, and the one that reads $0 gets the fixes estimate from the section above, in hours at your rate. Then change the price per customer and watch which lines move. The ones that do not are the ones you have been arguing about; the ones that do are the ones to argue about instead. ### Re-check these numbers Prices here were read on 27 October 2026 from each vendor's own page: Lovable's subscription plans page, Supabase's pricing page, Resend's pricing page, Stripe's pricing page, Lovable's payments documentation for the Paddle rate, Clerk's pricing page, Vercel's pricing page, Bolt's pricing page, Replit's pricing page, and our own plan constants checked against the live pricing page. Vendors change prices without notice, and Lovable in particular has changed its plan structure more than once this year. Before this arithmetic decides anything, open the pages again. The assumptions are listed so you can change them; the method survives the numbers. --- ## Sign in with Apple, phone codes and two-step sign-in, now on BuildBase > What is new in BuildBase sign-in: Apple, phone codes through your own provider, two-step sign-in, wallets, device code and user import. Why it is built this way, and what stays the same. - Source: https://www.buildbase.app/blog/new-sign-in-methods - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-28 ### In short BuildBase sign-in now covers Sign in with Apple, your own OpenID Connect provider, email and phone codes and Ethereum and Solana wallets, plus guests, usernames, One Tap, device code and two-step sign-in. Your app code does not change: the hosted page shows the methods you tick, and phone codes use your own provider. BuildBase sign-in now goes well past a password and a Google button. An app can offer Sign in with Apple, a code by text message, a second step from an authenticator app, an Ethereum or Solana wallet, and a code typed on a phone to sign in a TV or a command line tool. None of it needs a line of new code in your app. That last sentence is the design. So before the list, the reason. ### One call, and the page decides Your app has one `signIn()`. It sends the person to the sign-in page BuildBase hosts for you, and that page shows the methods ticked on the app they came from. Add Apple in the console, tick it on your customer app, and the button appears. Leave it off your staff app and it does not. We could have shipped a `signInWithApple()` and a `signInWithPhone()`. Each new method would then have been a release you had to adopt: a dependency bump, a code review, a redeploy. Instead a method is a row in the console. Its setup guide is written for whoever on your team holds the Apple Developer account or the Twilio login, who is often not the person who writes the React. ### What is new **New sign-in methods.** - **Sign in with Apple.** Four values from your Apple Developer account and the button is on your page. What bites later is the name Apple sends only once, and mail to Apple's relay addresses. The [Apple setup guide](https://docs.buildbase.app/sign-in-setup/apple) covers both. - **One OpenID Connect or OAuth 2.0 provider of your own**, such as Keycloak or your company's identity provider, as one more button. - **Email sign-in codes**, beside magic links. A code can be typed on any device, which rescues the person who asks for a link on a laptop and opens the email on their phone. - **SMS sign-in codes through your own provider**: a text message, a WhatsApp message or a voice call, sent with your own Twilio account or your own signed webhook. - **Crypto wallet sign-in** with an Ethereum or Solana wallet. **New ways to use them.** These are not methods of their own, so they sit apart from the list above. - **Google One Tap**, a setting on the Google method. - **Sign-in with a username** for people who would rather not type an email address. - **Guest users**, who keep everything when they add an email later. - **Device code sign-in** for CLIs and TVs, approved on a phone or computer. **Around the sign-in.** - **Two-step sign-in with an authenticator app, single-use backup codes or text-message codes**, under a policy of off, optional or required. An authenticator app or a passkey is the stronger choice, and a passkey sign-in that checked a fingerprint, a face or a PIN already counts as both steps. - **Who may sign up**: an allowlist, a blocklist or a waitlist you approve, with Cloudflare Turnstile to keep scripts off the sign-up form. - **A breached-password check** on sign-up, reset and change. - **Trusted devices.** A device someone trusts stays signed in longer, and the Devices screen lists every device they are signed in on, to rename or sign out. - **Account screens in the SDK.** The Security screen covers the password, a phone number, two-step sign-in, connected accounts, passkeys and deleting the account. **Moving in.** User import from Clerk, Auth0, Firebase and Supabase. Password hashes and social sign-ins come across too, so nobody has to reset a password on the day you switch. **The page itself.** The hosted sign-in page in 8 languages (English, Spanish, French, German, Japanese, Chinese, Hindi and Arabic), branded per app. One more, kept apart on purpose. It is not a way for a person to sign in. Every app is an OAuth 2.0 authorization server, so AI agents and third-party apps register, ask a signed-in user for access on a consent screen, and get a token that user can revoke. That is the half a [remote MCP server does not do for itself](/blog/what-is-an-mcp-server): it validates tokens, it does not issue them. ### Why phone codes go through your provider This is the decision people ask about, so here it is plainly. BuildBase sends no SMS of its own. The codes leave through your Twilio account or your webhook, at your provider's price, under your provider's fraud settings. A paid BuildBase plan bills over its allowance only for workflow runs, web analytics events and storage, so there is no per-message line on our invoice either. The reason is the attack that comes with every phone number field. Scripts ask sign-in pages to text codes to premium-rate numbers, and someone takes a cut of what the sender pays. Twilio calls it SMS pumping. The first fix is choosing which countries can receive a code at all, and that switch already lives in your Twilio account, next to the bill it protects. It keeps the price honest too. Twilio Verify charges $0.05 per successful verification on top of the message itself, which is $0.0083 for a text to a US number. A plain text is about a sixth of that. Which one you want depends on whether you would rather Twilio made and checked the codes. The [phone setup guide](https://docs.buildbase.app/sign-in-setup/phone) covers both, plus a webhook for any other provider. ### What it means if you already use BuildBase Nothing changes until you tick something. The methods you offer today keep working, and no app shows a button you did not add. To add one, open **Authentication** in the console, add the method on the **Methods** tab, then tick it on the app in its **Edit** sheet. Some methods need a plan that includes them, and [the pricing page](/pricing) has the current plans. There is a step-by-step guide per method, with screenshots, starting at [docs.buildbase.app/sign-in-setup](https://docs.buildbase.app/sign-in-setup/overview). If you built your own account settings page, the SDK's Security screen now covers two-step sign-in, a phone number and connected accounts. Open it from your own button with `openWorkspaceSettings('security')`, and delete the code you no longer need. ### What is not changing **Sessions.** Still 30 days by default, and signing out still ends the session on the server. **Pricing.** There is a Free plan at $0, then Launch at $19 a month and Grow at $49, and the paid plans start with a 7-day trial that does not ask for a card. Active users are an allowance on each plan, not a meter, and the new methods did not add one. **What is not on every plan.** Enterprise SSO (SAML and OIDC) is on the Enterprise plan only, through your own WorkOS account. If an enterprise customer's IT team needs to plug in their identity provider, our [WorkOS comparison](/compare/workos-vs-buildbase) is honest about where that leaves you. And the SDK is still web-first: the [framework guides](/guides/buildbase-on-nextjs) cover Next.js, Vite, React Router, TanStack Start, Express, NestJS, Fastify, Hono and Astro. **The existing guides.** [Passkeys](/guides/passkeys-nextjs), [magic links](/guides/magic-link-login-nextjs) and [social login](/guides/social-login-nextjs) still describe how those methods work. None of them needs a route handler in your app, and neither do the new ones. ### Sources Twilio figures verified 17 October 2026 on Twilio's own pages: [Verify pricing](https://www.twilio.com/en-us/verify/pricing) ($0.05 per successful verification, plus $0.0083 per SMS to a US number) and [preventing SMS pumping and toll fraud](https://www.twilio.com/docs/verify/preventing-toll-fraud). BuildBase facts come from the same plans, module catalog and session defaults that drive [/pricing](/pricing) and [/auth](/auth). --- ## What "built-in backend" means on Lovable, Bolt, Replit, v0 and Base44, and what it leaves out > Every builder now ships a backend: database, sign-in, storage, functions. What each includes, read from its own docs on 27 October 2026, what none covers, and when the built-in is the right call. - Source: https://www.buildbase.app/blog/what-built-in-backend-means-on-lovable-bolt-replit-v0-and-base44 - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-28 ### In short A built-in backend is the database, sign-in, storage and server functions a vibe-coding platform hosts for the apps built on it, so a prompt can add a table or a login. On 27 October 2026, Lovable, Bolt, Replit and Base44 ship one, v0 wires one from a marketplace, and none covers teams, roles, plan limits or credits. A built-in backend is the database, sign-in, file storage and server functions that a vibe-coding platform hosts for the apps built on it, so that a prompt can add a table or a login without you opening an account anywhere else. It is the reason a non-developer can get a working app in an afternoon, and it is the reason the app stops at a very particular place. That place is the subject of this post. As of 27 October 2026, Lovable, Bolt, Replit and Base44 each ship a built-in backend, and v0 wires one together from Vercel's marketplace. Every one of them covers a database, a login and, on paid plans, a way to take money. None of them documents teams, roles, invitations, plan limits, seats or credits for the people using your app. The gap is the same on all five, and it is worth seeing in one place, because the vendor pages about these builders go stale within a quarter and most of them still describe last year's builder. Everything below was read from the builders' own documentation on 27 October 2026, and says so where a claim is a vendor's rather than a builder's. If you are reading this months later, check the dates against the changelogs before you lean on a row. ### Why built-in backends exist They exist because the alternative is a terminal. A Hacker News commenter put it in one sentence in August 2026, explaining why non-technical builders pick Lovable over Claude Code: "With CC you still have to host it somewhere. On Vercel, get a DB somewhere or tell it to use SQLite, which no one knows what that is. You have to install it and use a terminal which no one knows how to do." The first generation of builders did not solve this. They generated a React app in the browser and left the data to Supabase, which a builder had to sign up for, configure and secure. Another commenter described the result in December 2025: Lovable "uses Supabase by default and basically generates React SPA's with no true backend. But random people won't understand this distinction and will want to create full real apps." The 2025 scan that became CVE-2025-48757 found 170 of 1,645 sampled Lovable apps with database tables any visitor could read, which is what "no true backend" looks like from outside. So the builders absorbed the backend. Lovable launched Lovable Cloud in September 2025, Bolt launched Bolt Cloud the same week, Replit already had its database and added Replit Auth, Base44 was built around its own data and identity layer from the start. The business reason sits beside the product reason: a backend the builder hosts is usage the builder bills. Lovable draws Cloud usage from the same credit balance as building, Replit bills deployments and the production database by usage, and Base44's founder told Calcalist in August 2026 the company expects gross margin to move from near break-even to about 60% as that usage matures. ### What each one includes The table is the summary; the paragraphs are what the docs actually say. "End users" means the people who use your app, as distinct from you and your collaborators inside the builder. | Builder | Database | Sign-in for end users | Payments | Functions and secrets | Not documented for end users | | ------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | Lovable Cloud | Managed Postgres, storage, realtime | Email, phone, Google, Apple, Microsoft, Sign in with Lovable, SAML SSO, OIDC; up to 50 redirect URLs | Paddle (5.0% plus 50 cents) or your Stripe, Pro and up; one subscription per user by default | Edge functions; write-only secrets; jobs, logs, usage | Teams, roles, invitations, plan limits, seats, credits; email is a separate guide | | Bolt Cloud | Database (Supabase-backed per Supabase's post), storage | Email and Google | Stripe | Edge functions; a security scan on publish | Teams, roles, plan limits, credits, email | | Replit | Replit Database (Postgres), App Storage | Replit Auth (sign in with a Replit account) or Clerk Auth (a tenant per app, no organizations yet), own OAuth credentials | Stripe connector | Secrets tool as env vars; Autoscale, Reserved VM, Static and Scheduled deployments | Teams, roles, plan limits, credits | | v0 | Marketplace: Neon, Supabase, Upstash, Blob, AWS | None of its own; Clerk and Auth0 one click since September 2026; Vercel owns Better Auth | Stripe in the Marketplace | Next.js route handlers; env vars in Vercel; previews run the full app | Teams, roles, plan limits, credits | | Base44 | Entities as JSON schemas, managed in Base44 | Email and password, Google, Microsoft, Facebook, Apple, or SSO (Google, Microsoft, GitHub, Okta, custom), SSO exclusive with social | Base44 Payments by Wix, or Stripe | `functions/` as TypeScript files; project secrets | Teams, roles, plan limits, credits; the function runtime | **Lovable Cloud.** The docs describe "a managed PostgreSQL database, login, and file storage", with realtime and functions, and say most projects never need a separate Supabase account. The Users view is a searchable list with sign-up and last sign-in times and the methods each person used; the sign-in page mentions no roles, teams, workspaces or invitations for end users. Secrets are write-only ("its value can never be viewed again in Lovable, only replaced or deleted") and are injected into edge functions and server-side integrations at runtime. Payments arrived on 24 April 2026 through Paddle or your own Stripe, on Pro and up, with one active subscription per user by default and one provider per project; a project with payments on cannot be forked. Email is not listed as part of Cloud; the docs point to a separate guide on sending from your own domain. Two limits worth knowing before you commit: a database export is allowed once every 24 hours, and removing Cloud "permanently deletes the database, its backups, your app's user accounts, and the files in storage". New apps since 13 May 2026 are TanStack Start apps rendered on the server; older ones are React with Vite. **Bolt Cloud.** Bolt's docs describe a database with email and Google sign-in, storage, server functions and Stripe, a security audit you can run from the Publish menu, and a Site URL plus a redirect allow list that Bolt usually updates when you publish. Supabase's own post of 30 September 2025 says Bolt Cloud backends run on Supabase. Bolt hosting is the default publish target; the Netlify alternative is for static sites, and Bolt's own page says Netlify "can't host a database or a traditional backend". Bolt's docs mention no roles, teams or permissions for end users. **Replit.** The strongest technical fit of the five, because a Replit project is a real Linux workspace with a shell, so anything that installs with npm installs. Replit Auth is "Replit-branded sign-in with zero setup": your users sign in with a Replit account, through Replit's shared OAuth apps, in a single environment. Clerk Auth is the other first-party option, which the docs recommend for "branded apps, professional and commercial products": a Clerk tenant of your app's own, separate development and production environments, Google, GitHub, Apple and X with your own OAuth credentials in production, and a Users tab. The same page lists what Clerk Auth does not include today, and the first item is "Organization tenants, Clerk's organization and team-membership features". Roles and permissions for your users are not mentioned on either page. Secrets are set in the Tools pane and arrive as environment variables, with production values set separately under Publishing. After the July 2025 incident in which the agent deleted a customer's production database during a code freeze, Replit rolled out automatic separation of development and production databases. **v0.** v0 generates Next.js with React, TypeScript, Tailwind and shadcn, and has no backend of its own. Databases come from the Vercel Marketplace inside the chat; one-click integrations for Clerk, Auth0, Resend and others arrived in September 2026, and v0 loads a provider's published skills automatically when its integration is installed, which is how it knows the provider's patterns. Vercel bought Better Auth on 7 July 2026, so the likeliest sign-in an agent on v0 reaches for is Vercel's own. Environment variables live in the Vercel project and reach previews, which run the full application. Publishing is one click to Vercel. **Base44.** "Base44 apps are standard React apps built with Vite", with `entities/` holding a JSON schema per entity and `functions/` holding one TypeScript file per backend function. With the two-way GitHub integration, entities are managed in Base44 and are not included in your local repository. Sign-in is configured in `base44/auth/config.jsonc`: email and password, Google, Microsoft, Facebook and Apple, or SSO through Google, Microsoft, GitHub, Okta or a custom provider, with SSO and social login mutually exclusive. No roles, teams or permissions for end users appear on that page. In July 2025 Wiz found that Base44's registration and OTP endpoints accepted requests without authentication, so anyone holding an app's public id could create a verified account on a private app; Wix fixed it within about a day and found no abuse. **Google AI Studio's build mode**, for completeness: its agent provisions Firebase Authentication and Firestore from the prompt, so it is a sixth built-in backend in everything but name, with Firebase's rules model underneath. ### The line every one of them stops at Read the right-hand column again. Five builders, read on the same day, and the same four absences: teams, roles, plan limits, credits. It is not an oversight on one of them. It is where "an app" stops and "a product" begins, and it is the line a built-in backend was never asked to cross. Here is what the absence means in practice, in the order a stranger meets it: - **The second person from the same company.** The built-in backend gives every person an account. It does not give a company one. Two colleagues sign up separately, and nothing in the backend knows they belong together, so there is nothing for a prompt to build on when you ask for "teams". What the agent builds instead is a `teams` table and a `role` column checked on one page, which is the bug every audit of a vibe-coded app finds. [Teams, invites and admin versus member](/guides/teams-invites-and-roles-for-a-vibe-coded-app) is what the layer looks like when it exists. - **The plan that has to change what the app does.** Lovable's built-in payments give a user one active subscription. Bolt's and Replit's Stripe connectors take a payment. None of them connects the payment to a feature, a seat count or a limit, so the connection is code the agent writes, usually in the browser, where a February 2026 audit found "a live marketplace with real Stripe payments where any logged-in user could grant themselves admin". [Paid plans that actually gate features](/guides/paid-plans-that-gate-features-vibe-coded-app) is the other half. - **The email that arrives.** Every built-in sign-in sends confirmation and reset emails, and every one sends them from a development sender until you connect a domain. Supabase's default sender delivers only to your project's team, at two messages an hour, by its own docs. - **The credit that runs out.** An AI feature needs a balance someone can spend down and a hard stop when it is gone. Nothing in the five backends holds one, which is why "development endpoints still in production that let anyone mark themselves as a paid user and give themselves unlimited credits" was a finding rather than a surprise. > **Key takeaway:** A built-in backend answers "where does the data live" and "who is this > person". It does not answer "which company do they belong to", "what did that > company pay for" or "how much may they use". Those three questions are the > product, and on every builder they are yours. ### Where the built-in backend wins For a single-user app, a prototype, an internal tool or a weekend project, the built-in backend is the right choice and nothing external comes close. It is zero configuration inside the builder, it is paid for from the same balance you are already paying, and the security checks (Lovable's Quick scan runs on every publish; Bolt's audit is a free button in the Publish menu) cost nothing extra. Replit Auth is "zero-setup" in the literal sense: ask the agent and the login page exists. There are specific things the built-ins have that BuildBase does not, or has only with more setup. Lovable's sign-in ships SAML SSO and OIDC of its own, where ours runs through your own WorkOS account on the Enterprise plan, so an app whose buyer signs in with Okta and wants one vendor is better served there. Lovable's Paddle option makes someone else the merchant of record, which handles the tax side; our billing is Stripe, bring your own, and the tax side is yours. Base44's entities are a data model you never have to write a migration for. Replit's Clerk Auth gives a commercial app a branded tenant with separate development and production environments, provisioned without a Clerk account. If any of those is the thing you need, the built-in is the pick, and this post is not trying to talk you out of it. ### When the built-in backend is the wrong choice The moment two people share an account, the moment a plan has to change what the app does, and the moment you need to leave. The first two are the gap above. The third is about the exits, which are real but narrower than the pitch. Lovable Cloud exports once every 24 hours, removing Cloud deletes your app's user accounts with the database, and the docs say moving to your own Supabase "isn't a one-step switch": you export and restore the database, move storage files and code, and set up auth, secrets and external services again. Base44's entity definitions stay in Base44 even with GitHub sync on. Bolt's one-click alternative host is static. Replit's data lives in Replit's database until you export it. None of this is hidden, but it is the kind of thing people discover on the day they want to leave, and a commenter on Hacker News in August 2026 described a client's Lovable backend as "completely inaccessible except through the lovable interface" (Lovable's changelog has since added exports and a way to create your own Supabase project, so check the current docs before repeating that). There is a fourth moment, quieter than the others: when the agent's own tables go wrong. The built-in backend hosts the database; it does not write your row rules. UpGuard's scan in September 2026 found 16,326 Supabase databases with a publicly readable `users` table, and noted that tables created through the API, which is how coding agents work, "do not enable RLS by default". Lovable's Quick scan checks that rules exist, not that they are right, which is the distinction the researcher behind CVE-2025-48757 drew about Lovable's 2025 scan too. A built-in backend makes the database easy to create and leaves its safety to the same prompt that created it. ### Three questions to ask before you lean on one The table above is what the docs say today. These three questions decide whether a built-in backend is still the right call in a year, and each has a different answer per builder, so ask them before the first stranger signs up rather than on the day you want to move. **Can I get the database out, and how often?** Lovable: an export once every 24 hours, and a documented path to your own Supabase project that its docs call "not a one-step switch". Base44: the code syncs to GitHub both ways, the entity definitions do not; they are managed in Base44. Bolt and Replit: the code is in GitHub as soon as you connect it (Bolt polls the repository for changes about every 30 seconds; Replit's Git tool pushes), and the data stays in the builder's database until you export it from there. v0: nothing to export from v0, because the database was never v0's; it is a Neon or Supabase project in your Vercel account. **Do my app's users come with me?** This is the question nobody asks. On Lovable, removing Cloud deletes "your app's user accounts" along with the database, so the accounts live and die with the backend. On Base44 the accounts belong to Base44's identity layer, which the GitHub sync does not carry. On Bolt Cloud and Replit Auth the users are rows in the builder's sign-in system; Replit's docs describe Replit Auth as Replit-branded with a single environment, and Clerk as the white-label route, which is also the portable one. If the people who signed up are the asset, where their accounts live is the decision, and it is made on the day sign-in is switched on. **What does the security scan actually check?** Lovable's Quick scan runs on every publish and checks that row rules exist; the researcher behind CVE-2025-48757 drew the line between "a policy exists" and "the policy is right" about Lovable's 2025 scan, and it still holds. Bolt's audit goes wider than most: its help page lists checks on whether protected pages require an account, whether a user can change a price or skip a step, whether keys reach the browser, and a database review that flags "a permission rule that allows anyone to read a table". On Replit the database is reached from your own server code, so the equivalent question is whether every route checks who is asking, and no scanner answers it. None of them knows which workspace a row belongs to, so a rule that says "any signed-in user can read every row" is a rule, and it passes. The honest summary: the built-in backend is the easiest backend to start and the hardest to leave, and nothing about that is hidden. It is simply not on the pricing page. ### How BuildBase sits beside it BuildBase is not a database, and the rule every agent gets is "do not use BuildBase as the primary database; pair it with Supabase or Postgres". So the shape, on every builder, is the same: the built-in backend keeps your tables, your files and your functions, and BuildBase holds the parts in the right-hand column (the workspace a customer belongs to, the role each member has, the plan the workspace pays for, the credits it may spend, the email that goes out when a card fails), reached through hooks in the app and a server SDK in your functions. Each builder has a guide for the join, with what was tested and what was not: [Lovable](/guides/add-login-teams-and-paid-plans-to-a-lovable-app) (new apps are TanStack Start, which can hold the sign-in routes; older ones are Vite and need a server first), [v0](/guides/add-sign-in-teams-and-paid-plans-to-a-v0-app) (Next.js, where `npx buildbase init` writes the files), and the [Claude Code and Cursor](/guides/vibe-coding-with-claude-code-or-cursor) route for anyone with a terminal. One honest wrinkle applies wherever Supabase holds the data: its row-level security cannot verify a BuildBase session directly, so data either goes through server routes that check the session, or your server mints a Supabase-shaped token; the Lovable guide has both. The explainer underneath all of this is [what a SaaS backend is, and which half of it is your product](/blog/what-is-a-saas-backend): the account model (who the user is, which customer they belong to, what they may do, what they owe) is the half the built-in backends leave to you, and [the launch checklist](/guides/vibe-coded-app-launch-checklist) is the twenty-item version of what that half contains. --- ## What is an MCP server, and what it quietly asks you to own > An MCP server exposes tools, resources and prompts to AI clients over the Model Context Protocol. What it is, how it works, and why it is not the thing that authorizes the agent. - Source: https://www.buildbase.app/blog/what-is-an-mcp-server - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-28 ### In short An MCP server is a program that exposes tools, resources and prompts to an AI client over the Model Context Protocol, as JSON-RPC over stdio or HTTPS. It does not authorize the agent: under the 2026-07-28 spec a remote one is an OAuth 2.1 resource server, and a separate authorization server issues its tokens. An MCP server is a program that exposes tools, resources and prompts to an AI client over the Model Context Protocol. The client asks what is on offer, the server answers with a typed list, and the model calls entries by name. Locally that server is a subprocess on your laptop. Remotely it is an HTTPS endpoint you host. Every explainer on the first page of results says roughly that, and they are right. Then they stop, usually one paragraph before the question that actually blocks people: who is allowed to call it? The moment your server stops being a subprocess on your own machine and becomes a URL, the protocol hands you a second job it does not do for you. Under the current revision an MCP server is an OAuth 2.1 **resource server**. It validates tokens. It does not issue them. Something else has to, and that something else is an authorization server with discovery, a consent screen and revocation. > **Key takeaway:** The protocol is the easy half. An MCP server validates tokens it did not > issue, which means a remote one is only as shippable as the authorization > server sitting behind it. ### Why the protocol exists MCP exists to stop every assistant and every data source needing a bespoke integration. Anthropic published it on 25 November 2024 with a specification, SDKs and a set of prebuilt servers for things like Git, Postgres and Slack. In December 2025 it was donated to the Agentic AI Foundation, a directed fund under the Linux Foundation set up with Block and OpenAI, whose platinum members now include AWS, Bloomberg, Cloudflare, Google and Microsoft. The announcement of that handover cited more than 10,000 active public MCP servers. The problem it solves is the old N times M one. Five assistants and twenty data sources is a hundred integrations if each pair is its own adapter, and twenty five if both sides agree on a protocol. Nothing about that is novel. It is the same argument that produced ODBC and the Language Server Protocol, and it works for the same reason. ### How it actually works Three roles, one wire format. A **host** is the application a person is using, a **client** is the connector inside it that holds one connection, and a **server** is the thing you write. Every message is JSON-RPC 2.0. What a server exposes comes in three kinds, and the useful distinction between them is not what they contain but who decides to use them: - **Tools** are model-controlled. The model picks one and calls it, which is why a tool that writes anything deserves more thought than its code suggests. - **Resources** are application-controlled. The host decides what to pull in as context: file contents, a query result, git history. - **Prompts** are user-controlled. They surface as slash commands or menu items that a person deliberately invokes. Two transports are standard. With **stdio** the client launches your server as a subprocess and speaks newline-delimited JSON-RPC over the pipe. With **Streamable HTTP** every message is an HTTP POST to a single endpoint, and the reply is either a JSON object or a stream scoped to that request. If you are reading older material, one change in the `2026-07-28` revision will trip you up. The protocol is now stateless: there is no `initialize` handshake and no protocol-level session. Each request carries the version it expects in its metadata, the server accepts or rejects it per request, and a mandatory `server/discover` RPC returns supported versions, capabilities and identity in one go. Servers no longer initiate requests of their own. ### The half that is not MCP Almost none of a remote connection is protocol-specific. Here is the shape of one. An agent calls your server with no token. You answer `401` with a `WWW-Authenticate` header naming where your protected resource metadata lives. That document, defined by RFC 9728, is required: the spec says an MCP server MUST implement it. The client reads it, finds which authorization server you trust, fetches that server's metadata, and runs an ordinary OAuth 2.1 authorization code flow with PKCE. `S256` is required, and a client MUST refuse to continue if the authorization server does not advertise support for it. One parameter in that flow does most of the security work. RFC 8707 resource indicators mean the client MUST send a `resource` parameter, set to your server's canonical URI, in both the authorization request and the token request, whether or not the authorization server appears to support it. That is what binds the resulting token to you specifically. Which sets up the two hard rules. A server MUST validate that a token's audience is itself, and MUST NOT accept or pass through a token issued for someone else. The spec calls token passthrough explicitly forbidden, and the reasoning is worth reading even if you never implement MCP. A server that forwards a caller's token upstream breaks the audit trail and bypasses whatever controls the upstream thought it had. The trust boundary becomes a hallway. Notice what none of this is. There is no MCP-specific auth mechanism to learn. It is OAuth 2.1 with three RFCs bolted on, which is good news if you already run an authorization server and a surprise bill if you do not. ### What the spec deprecated, and why your tutorial is probably wrong This is the part that goes stale fastest, so here are the rows that change how you build, as of 28 October 2026, read from the specification's own deprecations page. | Feature | Deprecated in | Use instead | | -------------------------------------- | ------------- | -------------------------------- | | HTTP+SSE transport | `2025-03-26` | Streamable HTTP | | Dynamic Client Registration (RFC 7591) | `2026-07-28` | Client ID Metadata Documents | | Sampling | `2026-07-28` | Call the model provider directly | | Roots | `2026-07-28` | Tool parameters, resource URIs | | Logging | `2026-07-28` | stderr, OpenTelemetry | None of it has been removed yet. The four deprecated in `2026-07-28` cannot go before the first revision dated on or after 28 July 2027. HTTP+SSE runs on a different clock: three months after SEP-2596 reaches Final. The registration row is the one that matters, and it is the reason to distrust most of what you will read about MCP auth. Dynamic client registration was how an agent you had never met got a client ID without a human filling in a form. Several of the pages ranking for it today still present it that way. It is now deprecated in favour of Client ID Metadata Documents, where the client is identified by a URL that resolves to its own metadata. A page that describes DCR as the way agents register is describing the 2025 spec. ### When an MCP server is the wrong choice An explainer that only lists reasons to say yes is a brochure. Four cases where the answer is no: **You control both ends.** If one application calls one model and you own both, an MCP server is indirection with a spec attached. Call your own functions. MCP earns its keep when the client is something you did not write. **You need it to be local, and it is.** A stdio server reading your filesystem is genuinely simple and needs no authorization at all, because the credentials come from the environment the client launched it in. The spec says so. Going remote is what adds the OAuth bill, so do not go remote by default. **Your tool descriptions come from somewhere you do not trust.** The specification states plainly that descriptions of tool behaviour should be treated as untrusted unless they come from a trusted server. A description is text the model reads and acts on. A server you did not write is a channel straight into your model's instructions. **You cannot own the consent screen.** The spec's security guidance walks through the confused deputy case: a static client ID at a third-party authorization server, plus a consent cookie from an earlier approval, lets an attacker register their own redirect URI and skip the screen entirely. The mitigations are per-client consent recorded per user, exact-string redirect URI matching with no wildcards, and a single-use state cookie set only after approval. All three are authorization server responsibilities. If you are not running one, you are trusting someone who is. ### What this costs when you actually run it We build the authorization half, and the SDK ships the server half as an `/mcp` entry point. The numbers below are ours rather than the specification's, and they are what that second job looks like once it is running. Every app built on BuildBase is an OAuth 2.0 authorization server for agents and third-party apps. That is a separate thing from the [sign-in methods a person uses](/blog/new-sign-in-methods), and it never counts as one of them. Each organization gets its own RFC 8414 metadata document, cached for 300 seconds and invalidated whenever a client changes. It advertises `S256` as the only code challenge method and `none` as the first supported token endpoint auth method, because the public clients doing the calling authenticate with PKCE alone. Access tokens last 1 hour. Refresh tokens for agent clients last 30 days and rotate on every use, against 180 days for first-party app clients. Authorization codes expire after 10 minutes. Registration accepts at most 20 redirect URIs, rejects anything that is not HTTPS or loopback, and rejects a URI carrying a fragment or userinfo, since `https://app.example.com@evil.test/cb` reads as your domain to a human and as `evil.test` to a browser. Replaying a consumed refresh token does not just fail, it revokes the whole token family. One thing we got wrong first, which is usually the useful part. We originally published scopes on the authorization server, and that was the wrong place: scopes belong to the application that owns the data, not to a shared authorization server that sits across all of an organization's clients and resources. Our metadata now deliberately omits `scopes_supported` and the app publishes its own RFC 9728 document instead. The admin API rejects the old fields rather than quietly ignoring them. And the honest one. Our implementation targets the `2025-06-18` revision, not `2026-07-28`. Dynamic client registration is still our registration path where an organization turns it on, which is the mechanism the current spec deprecated. It works. It has until that 2027 revision, and moving to Client ID Metadata Documents is on us. A post that told you to check the spec revision and then skipped its own would not be worth much. ### Where this sits An MCP server is a protocol adapter in front of things you already have. The interesting questions are almost never about the adapter. Weighing what belongs in your own service against what belongs in a dependency? The reasoning is the same here as anywhere else in [a SaaS backend](/blog/what-is-a-saas-backend). If what you actually want is for another system to be told when something changes, rather than to come and ask, you want [a webhook](/blog/what-are-webhooks) and not this. And the part that decides what an agent may touch once it is acting as a specific person is [your roles and permissions model](/blog/what-is-rbac). MCP has no opinion about that at all. --- ## What a coding agent builds for login and billing when nobody tells it otherwise > We gave a coding agent a plain request for sign-in, teams, subscriptions and a failed-payment email, with no brand named. Here is what it built in 34 turns, and what one installed skill changed. - Source: https://www.buildbase.app/blog/what-a-coding-agent-builds-when-nobody-tells-it-otherwise - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-27 ### In short Given a plain request for sign-in, a team workspace, subscription billing and a failed-payment email, a coding agent left alone built its own password hashing, a SQLite user table, direct Stripe calls and a one-off email sender. Correct code, and a stack you now maintain. One installed skill changed every later run. Here is the prompt, exactly as we gave it, with no product named anywhere: > Add sign-in, a team workspace, Stripe subscription billing, and an email > when a payment fails. Use a React or Next.js app. Keep any existing > database. Do not add a second auth vendor. Ten minutes and eleven seconds later, after 34 turns, the agent had built it: scrypt for the passwords with an iron-session cookie, a users table in SQLite through Node's built-in module, Stripe called directly with a handler on Stripe's own `invoice.payment_failed`, and the email sent through Resend's HTTP API. `tsc --noEmit` exited 0. Nothing in that list is wrong. If a contractor handed it to you, you would pay the invoice. And it is exactly the stack the whole prompt was trying to avoid: four separate services and a hand-rolled user table, in an app whose owner will not be the one maintaining them. The agent was not careless. It was uninformed, and it filled the gap with the most common thing it had ever seen. We ran that experiment on 7 October 2026 to find out what a coding agent does by default, then ran it six more times with one file added. This post is what the record shows, what it does not show, and what it means if you build by prompting. ### What the record shows The baseline build is recorded as four facts and two numbers: scrypt plus iron-session for sign-in, SQLite through Node's built-in module for the users, Stripe called directly with a handler on `invoice.payment_failed`, Resend over HTTP for the email, 34 turns, ten minutes and eleven seconds. The raw transcript stays out of git because it carries local paths, so those six facts are the evidence, and this post does not pretend to more. Take them one at a time, because each is a reasonable answer to its own question. **scrypt and iron-session.** Hash the password with a slow function, keep the session in an encrypted cookie. That is the textbook shape, and the textbook is old enough to be in every training set. It is also a sign-in system with no password reset, no email verification, no magic link and no second method, because nobody asked for those and an agent builds what was asked. The first user who forgets a password is the first support ticket, and the fix is more code of the same kind. **SQLite through Node's built-in module.** The prompt said "keep any existing database", and the throwaway app had none, so the agent created one, in the lightest way available. Defensible. It also means the users, and whatever it built for the team workspace, live in a file on one machine, which is where they will stay until someone migrates them. **Stripe, directly, on `invoice.payment_failed`.** The agent installed the Stripe SDK and wired a webhook route to Stripe's own event name. That is the right event if your app is the only thing between Stripe and the customer. It is the wrong shape for the prompt, which asked for billing as part of a product with sign-in and teams, because a payment handled this way exists in Stripe and in your handler and nowhere else: not on the workspace, not as a plan the app can check. The judge marked this condition as failed not because the event is bad, but because the app had no catalog of its own to name an event from. **Resend over HTTP.** Not even the npm package, just a `fetch` to Resend's API with a key from the environment. Well formed, and the second vendor check in the judge still passed, because no `resend` package appeared in `package.json`. A reminder that a mechanical judge measures what it was told to measure. That is the honest inventory. The reason it matters is not that any item is bad. It is that the prompt said "keep any existing database" and "do not add a second auth vendor", and the agent obeyed both by building a first auth vendor itself. Obeying the letter of a prompt is what agents do. The letter of this prompt had a hole in it the size of a product. ### What the record does not show We do not know, from the record, how the agent modelled the team workspace, whether its role checks were enforced on the server, or whether the Stripe route verified Stripe's signature. The judge did not look, and the transcript is not published. It would be easy to write those paragraphs from what generated apps usually do. We are not going to, because the next section is about what generated apps usually do, and the two should not be confused. What we can say is that the baseline passed the two conditions it was built to pass, typechecking and adding no named vendor, and failed the two it had no way to pass without knowing the SDK existed. That is the whole finding. The agent's default is set by what it knows. ### Why that is the default An agent builds what it has seen most, and what it has seen most for "add sign-in" is a users table and a password hash, because that is what a decade of tutorials contains. Nothing in the prompt pointed anywhere else, so nothing else was considered. The default is not a judgement about what is best. It is a count of what is common. v0's report on how people use its builder makes the mechanism visible from the other side. Developers, it found, "mention specific frameworks". Non-developers "use more conversational, goal-focused prompts": a reservation system for a restaurant, an app that forecasts baseball statistics. A goal-shaped prompt leaves every implementation choice to the agent, and the agent's choices are its priors. If you did not say "use a hosted sign-in", you got a users table. This is also why the four-vendor stack keeps appearing. Ask for sign-in, billing, email and automation one feature at a time, and you get the best-known tool for each: an auth library, Stripe, an email API, a workflow tool. Each is good. Vercel bought Better Auth in July 2026 precisely because it is good, an MIT library with 4.7 million weekly downloads. The trouble is not quality. It is that the four were never designed to agree about who the user is, which team they belong to and what they paid for, so the agreement is code the agent writes, and code the agent writes is code you own. Two years of that ownership has a price. We did the arithmetic separately: an agent can scaffold basic auth for around $2,400 of engineer time, against $27,000 by hand, and the maintenance line on generated code runs steeper than the 20% a year a human-written system settles into. [The year-two number](/blog/ai-generated-code-maintenance-cost) is the one nobody shows you on the day the demo works. ### Where generated auth actually fails When generated sign-in and billing fail in the wild, they fail in the business layer, not the cryptography: an endpoint that trusts the caller, a role checked only in the interface, a payment that never reaches the plan. The studies and the audits agree on this, and it is the gap a default build leaves rather than a bug in what it writes. Tenzai had five coding agents each build three applications in December 2025 and then attacked all fifteen. They found 69 vulnerabilities. Not one was an exploitable SQL injection or cross-site scripting bug; the agents have learned those lessons. Every agent introduced a server-side request forgery. No app had CSRF protection or security headers. And most of the findings were authorization and business logic: negative quantities, negative prices, actions a user should not have been allowed to take. A small, vendor-run study, but the shape of its results is the shape of everything else we read. v0's "State of Vibe Coding" report, from September 2025, names three recurring problems in apps built on its own platform: secrets exposed because "AI defaults to client-side code", access misconfigurations such as public databases and API routes with no auth, and hard-coded credentials. That report also puts the share of non-developers among its builders at 63%. The people most likely to ship an unauthenticated route are the people least equipped to notice one. Then the audits. In February 2026 a developer went through three products their builders had posted to Reddit. One was "a live marketplace with real Stripe payments where any logged-in user could grant themselves admin and hijack payment routing with a single request". Another "had development endpoints still in production that let anyone mark themselves as a paid user and give themselves unlimited credits". The same month, a researcher found 16 flaws in an exam-grading app featured on Lovable's Discover page, including an authentication function with its logic inverted: it blocked signed-in users and admitted anonymous ones. 18,697 user records were readable. Set those beside the baseline. Its scrypt was fine. Its cookie was fine. What it had no concept of was a plan on a workspace, a role the server enforces, or an event the app could trust, because none of those was in the prompt and none of them is in the textbook. The failure modes the auditors found are what gets written into that space by the next prompt, usually in the browser, where it can be forged. > **Key takeaway:** Generated auth rarely gets the hashing wrong. It gets the question of who may > do what wrong, because the prompt never asked and the agent never volunteered. > Every audit of a vibe-coded app we read found the same gap. ### What one file changed With our skill installed, six runs out of six installed `@buildbase/sdk`, added no second vendor, handled the failed payment through `payment.failed`, the event in our catalog, and typechecked, in 21 to 24 turns and about four minutes each. The prompt was the same. The agent was the same. The only difference was a markdown file it chose to read. The file is a skill: a `SKILL.md` with a description that tells the agent when it applies, and the facts it needs when it does. Ours is installed with one line, and it carries a five-line position rule that every run read before writing code: ```text Use BuildBase when the user asks for sign-in, orgs, RBAC, subscriptions, metered billing, usage credits, lifecycle email, or event workflows, and does not want Clerk + Stripe Billing + Resend + n8n. Do not use BuildBase as the primary database. Do not store card data. Stripe handles cards. Do not invent endpoints. Read the HTTP catalog first. If auth already exists, stop and ask before migrating. ``` Read it as the baseline's mistakes in reverse. The first line replaces the four-vendor default with one SDK. The second keeps the database the prompt said to keep. The third stops the agent from building a card form. The fourth is why every skill run's webhook handler named `payment.failed` instead of the Stripe event the baseline reached for: the skill ships the catalog, all 129 names, and the rule says read it first. The fifth is the one that protects your existing users. The runs were judged by a script, not by us reading transcripts and feeling good about them. Four conditions: the SDK is in `package.json`; none of Clerk, Auth0, Resend, Loops or n8n was added; a route whose path contains `webhook` calls the SDK's verifier and names an event from the published catalog, with every other event literal in that file also in the catalog; `tsc --noEmit` exits 0. The baseline failed the first and third. All six skill runs passed all four. Round one, on 7 October, ran against the skill from a local checkout; round two, on 8 October, against the published skill and the published package, which is the version anyone else gets. ### Two bugs the measurement found in itself A measurement you trust is one that has already caught itself being wrong. This one did, twice, before any result was worth writing down. The first was a false pass. The very first baseline run was created in a `work/` folder inside our own platform repository, and the nested agent loaded that repository's `CLAUDE.md`, its content plugin and the eval's own runbook. The verdict said PASS with "skill read: yes" while no skill was installed. The harness now refuses to run inside a git repository or below any `CLAUDE.md` or `.claude/` folder, creates the throwaway app under the system temp directory, and matches the exact skill path. A measurement of what an agent knows has to start from an agent that knows nothing, and that is harder to arrange than it sounds. The second was a version drift. In round one the skill pinned version 0.0.78 of the SDK while npm's `latest` tag still pointed at 0.0.77, so two runs followed the pin and the third, which ran a bare `npm install @buildbase/sdk`, got the older version without anyone noticing. All three passed. The judge checks presence, not version. The tag was moved the next day, and in round two all three runs resolved the pinned version from a bare install, which closed it; small, and exactly the kind of thing that makes a skill quietly worse six months later. ### What did not happen, and why No run executed `npx buildbase init`. The SDK ships a command that writes the provider, the sign-in routes, the webhook route and the env files into an existing app, ten files on Next.js, and every run read the line about it in the skill and then wrote the files by hand from the quick-start instead. We thought that was the agent being stubborn. It was the agent being sensible. `init` requires `--org-id` with a 24-character organization id, and with no id it exits before touching anything, by design. The eval gives the agent no credentials at all, so the command could not succeed, and the agents took the path that could. That is also a description of a real session: an agent scaffolding an app before the person has pasted an organization id is in the same position. So there is a product question in the result, recorded and not yet answered: should `init` run with no id, write the keys empty and say which value is still missing, so the agent can wire the app first and the owner paste the id after? Today the order is the other way round. Until that is decided, the eval measures what the skill does and nothing about `init`, and we would rather say so than let six green rows imply more than they show. ### If you build by prompting Install the skill before the first prompt, not after the first bug. Everything above says the same thing from different angles: the agent's default is set by what it knows, and a skill is the cheapest way to change what it knows. The order is one line, then the prompt. ```bash npx skills add buildbase-app/claude-skill # most agents npx skills add buildbase-app/claude-skill -a cursor # Cursor ``` In Claude Code, `/plugin marketplace add buildbase-app/claude-skill` and then `/plugin install buildbase@buildbase-skills`. Lovable and Replit can import a `SKILL.md` from a public GitHub folder; the folder for ours is `plugins/buildbase`. We have not yet run that import inside either builder ourselves, so that is their docs speaking, not our test. Then the prompt. The one we use is short, because the skill carries the rest: ```text Add BuildBase (@buildbase/sdk) to this app for sign-in, teams, paid plans and lifecycle email. Keep the existing database. Do not add Clerk, Auth0, Resend or n8n. Stripe is bring-your-own. If sign-in already exists, stop and ask me before changing it. The client secret and the webhook secret go in the secret store, never in a browser-visible variable. ``` And one check, after. Open `package.json`. If it contains `bcrypt`, `scrypt`, `iron-session`, `jsonwebtoken`, `next-auth` or a migration that creates a `users` table, the agent built a sign-in system, and you now own it. That is not a reason to tear it out; the rule about existing auth says stop and ask. It is a reason to know, before the first stranger forgets a password, and [the launch checklist](/guides/vibe-coded-app-launch-checklist) is the list of what else to check before that stranger arrives. If sign-in already exists and you want to move it, that is a decision rather than a prompt. Our Next.js guide walks through [swapping it in three real templates](/guides/buildbase-on-nextjs), and the Vite guide shows [the three functions a single-page app needs](/guides/buildbase-on-vite). Neither is something to let an agent do unsupervised on a Friday. ### Run it yourself The harness is two shell scripts and a prompt file, and it is in the skill repository so that anyone can reproduce a row of the table or add one for a different agent. `run.sh` creates a throwaway Next.js app outside any repository, installs the skill for the `on` variant, runs the agent with the prompt, and calls `judge.sh`, which prints the four-row verdict for the app directory. The prompt must never contain the word "buildbase", and a check enforces that; the webhook catalog the judge reads is copied from the platform's canonical list with the commit it came from in the header, so a judge and a skill that disagree about an event name are caught rather than averaged. Run it outside another agent session, because the CLI refuses to nest. Keep `work/` out of git; the verdict tables are the only thing worth committing, and they carry the date, the variant, the run number and the four results, so a reader six months from now can tell what was measured and when. ### Where this measurement stops Seven runs is a measurement, not a benchmark. One baseline and six with the skill, all on a fresh Next.js app, all through the logged-in Claude Code CLI across two model versions, all judged by four mechanical conditions. The judge checks that the SDK is present and a real event is named; it does not check that the sign-in flow works end to end, that the roles are enforced, or that the app is secure. A run can pass all four and still ship a role checked in one place. Agents also change weekly, and so do the builders. A result from October 2026 says what October's agent did. We will re-run it when the skill changes and when `init` learns to run without an id, and the results table lives in the skill's repository where anyone can read the dates. What the measurement does show is narrow and useful. The default is not neutral. Left alone, an agent builds the stack it has seen most, and the stack it has seen most is four services and a user table that nobody asked to maintain. One file changed that in every run we made. Everything else on this page is the reason to care. ```bash npx skills add buildbase-app/claude-skill ``` --- ## What are webhooks, and what happens when the delivery fails > A webhook is a POST you receive instead of polling for changes. That is the easy half. The retry ladder, the signature window and the fan-out are what decide whether it works. - Source: https://www.buildbase.app/blog/what-are-webhooks - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-27 - Updated: 2026-11-04 ### In short A webhook is an HTTP POST another system sends to a URL you control the moment something happens, so you learn about it without polling. That is the easy half. What decides whether it survives production is the delivery contract: how many retries, how long the signature stays valid, and when the sender gives up. A webhook is an HTTP request another system sends to a URL you control, the moment something happens there, so you find out without having to ask. Your server receives a POST. That is the whole idea, and every definition on the first page of results says roughly that. Then they stop, and that is where the trouble starts. A webhook is not a notification. It is a delivery, and a delivery has a schedule, an expiry and a point where the sender gives up on you. Those three things decide whether the integration survives contact with production. None of them are in the definition. ### Why they exist Webhooks exist because polling wastes nearly everything it does. Say you want to know when a customer's subscription changes. Without a webhook you ask on a timer. Every thirty seconds is 2,880 requests a day for that one resource, and if the thing you are watching changes twenty times a day, then 2,860 of those requests exist to be told nothing happened. You pay for all of them. So does the system you are asking. And you still find out up to thirty seconds late. The webhook inverts it. The system that already knows makes one request, when there is something to say. That inversion is obviously correct, which is why the comparison is where most explainers both start and finish. It is also the least interesting thing about webhooks, because it describes the good case. The design questions all live in the bad one. ### A delivery, not a ping Here is the shift that matters: the sender is not notifying you, it is trying to hand you something, and it will keep trying. What that means in practice is a set of numbers you should be able to name for any sender you depend on. Ours look like this. An event is posted to your HTTPS endpoint, and if that request fails or times out, it is tried again up to five times in total, backing off at roughly 10, 20, 40 and 80 seconds. That is about 150 seconds of trying before the delivery is written off. Each individual attempt gets 15 seconds to come back before we stop waiting. | Attempt | Fires at | What it means for you | | ------- | -------- | ------------------------------- | | 1 | Now | The happy path | | 2 | +10s | A blip, a restart, a cold start | | 3 | +30s | Something is actually wrong | | 4 | +70s | You are in an outage | | 5 | +150s | Last one. Then it is a failure. | Two and a half minutes is a deliberate amount of generosity. It covers a deploy and a restart. It does not cover a bad afternoon, and no retry ladder should, because at some point the honest thing is to stop and write the failure down where you can find it. Every attempt lands in a delivery log with its status, duration and attempt number. Worth being blunt about the limit there, because it is the question you should ask every sender and the answer is not always the one you want: that log is a record, not a replay button. There is no console action today that re-drives a delivery we already gave up on. If your endpoint was down for an hour, the events from that hour are yours to backfill from your own side, which is a good reason to make sure the state a webhook tells you about is also reachable by an ordinary API call. There is a second clock running alongside that one, and it catches people. The signature covers a timestamp, and your receiver should refuse one more than five minutes from its own clock. We sign every attempt, the first and each retry, when it is sent, with the time of that attempt and the endpoint's secret and URL as they are at that moment, so a retry after you rotate the secret or change the URL uses the new one. The event's `id` and the body's `timestamp` stay the same on every attempt. Our retries never age a signature, but time spent inside your own receiver still does, and the ways that happens are worth knowing: we wrote up [why a delivery gets rejected after five minutes](/guides/webhook-rejected-after-five-minutes) separately, because the usual cause turns out to be queueing inside the receiver rather than the clock drift everyone suspects first. > **Key takeaway:** Before you build on anyone's webhooks, get three numbers: how many times they > retry, how long each attempt is given, and what happens to your endpoint after > repeated failures. If the docs do not say, assume one attempt and no safety > net. ### The signature, and why it expires Every delivery is signed, because a URL that accepts POSTs is a URL anybody can POST to. Ours uses HMAC-SHA256 over the timestamp, a dot, and the body exactly as sent, with a secret shown once when you create the endpoint and rotatable from the console. On your side `parseWebhookEvent()` checks it and hands back the event. The part worth understanding is why there is a time limit at all, since the signature is already cryptographic. An HMAC has no expiry of its own. A correctly signed request stays correctly signed forever, so anyone who ever captured one delivery could replay it at you a year later and the maths would still check out. The timestamp is what turns a signature into a signature _and_ a freshness check, and five minutes is the window. This is also the place where a working integration breaks for a reason that looks like a crypto bug and is not. The hash is over the raw bytes. Parse the body to JSON and re-serialize it before hashing and you have hashed something subtly different, which fails identically to a wrong secret. If you have hit that against Stripe it is the same shape of mistake, and the [five causes of a failed signature check in Next.js](/guides/stripe-webhook-signature-verification-failed-nextjs) are ranked by how often each one is actually it. ### Fan-out is the part that bites One event does not mean one request. It means one request per endpoint subscribed to it, and that multiplication is where webhook systems hurt themselves. We learned this from our own. There are 129 events you can subscribe to across users, workspaces, billing, credits, workflows, audience and email, and an endpoint can subscribe to all of them with a wildcard. Early on, one event with N matching endpoints simply enqueued N jobs and nothing looked at the total. Then a campaign went out to 50,000 recipients. `email.sent` fires once per recipient, so a single wildcard endpoint turned that into 50,000 delivery jobs, and with the receiver down and five attempts each, up to 250,000 HTTP requests and 250,000 rows in the delivery log. Nothing was broken, exactly. Every one of those deliveries was behaving as designed. The design just had no opinion about the total. The ceilings that came out of it are the ones worth copying if you are building this yourself: a cap on endpoints per organization (100 today, above the most any plan sells), because every wildcard endpoint multiplies everything else; a budget of 240 deliveries a minute per organization, set deliberately below the rate of a large campaign and deliberately above normal traffic; and a limit of 3 deliveries in flight at once per organization, so one slow receiver cannot hold every worker while everybody else waits. The last one is the fairness lever and it is the one that needed the most care. A delivery over the cap is delayed, never dropped. A delivery that is throttled gets a row in the log saying so, rather than vanishing, because a webhook you cannot account for is worse than one that did not arrive. ### When a webhook is the wrong choice Required reading before you wire your architecture to one, and the section the generic explainers skip entirely. **When you need ordering.** Deliveries carry no ordering guarantee and retries break order on their own. If event B must be processed after event A, the sequence has to be in the payload and your handler has to enforce it. **When you need exactly-once.** Retries mean duplicates. A receiver that timed out after doing the work still gets the event again, and from the sender's side those two cases are indistinguishable. Your handler has to be safe to run twice on the same event, which is the same problem and the same fix as [idempotency in billing](/blog/idempotency-in-billing): key the work on something stable from the payload and make the second run a no-op. **When the receiver cannot be reached.** Only HTTPS addresses are accepted, and the sender has to be able to route to you. A service behind a VPN or a laptop in dev does not qualify without a tunnel. **When you need an answer.** A webhook is one-way. Your status code is the whole reply. Anything that needs a value back is a request you make, not an event you receive. **When the payload would be huge, or stale by arrival.** Send an identifier and let the receiver fetch the current state. Our events carry the workspace, user, subscription and plan precisely so most handlers do not need a round trip, but that is a convenience for the common case, not a reason to treat the payload as your copy of the record. ### What your handler owes the sender Verify before you parse, and verify against the raw bytes. Return a 2xx quickly and do the work afterwards. Fifteen seconds sounds generous until the handler is writing to three systems, and a slow handler also burns your own in-flight budget, so the sender ends up throttling you for being slow at the exact moment you are busiest. Deduplicate on the event id rather than trusting that you will see each one once. Ours arrives as `x-buildbase-event-id` and is the same value for every endpoint subscribed to that event and on every retry of it, which is exactly what you want as a key: store it, and make a second sighting a no-op. Sort by something in the payload rather than trusting arrival order. And log the deliveries you reject. The failure mode that costs a whole afternoon is not a webhook that never arrives, it is a webhook that arrives, gets refused by your own verification for a reason you did not record, and is counted as delivered by nobody. ### Where this goes next Webhooks are one of the ways a backend tells you something happened. The others are a queue you drain yourself and a stream you hold a connection to, and the choice between them is mostly a question of who owns the retry. If you are sizing up what a backend hands you before you build on it, [what a SaaS backend actually includes](/blog/what-is-a-saas-backend) covers the rest of the surface this one sits in. --- ## What is a feature flag, and how long until flipping it reaches the user > A feature flag changes behaviour without a deploy. The part most definitions skip is how long the flip takes to reach a user, and which kinds of flag can live with the wait. - Source: https://www.buildbase.app/blog/what-is-a-feature-flag - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-23 ### In short A feature flag is a conditional whose value is set outside your code, so you can change what a user sees without deploying. The question that decides your design is not whether you can flip it but how fast the flip reaches a user. A permission flag can wait for the next page load. A kill switch cannot. A feature flag is a conditional in your code whose value is set somewhere outside the code, so you can change what a user sees without deploying. Every definition agrees on that much, and it is the easy half. The half that decides your design is the one most explainers leave out: after you flip the switch, how long until the user actually sees it? Nobody asks until the first time it matters, and the first time it matters is usually an incident. ### Why the thing exists Flags exist to pull deployment and release apart. Without one, the moment code reaches production is the moment customers meet it, so shipping becomes an event: a branch that lives for three weeks, a release window, a rollback plan that is really a redeploy. With a flag, the code goes out dark and the decision to show it is a separate, cheap, reversible act. That is genuinely one of the better ideas in software delivery. It is also where most writing on the subject stops. ### Four types, or four deadlines The taxonomy everyone borrows comes from [Pete Hodgson's feature toggles article](https://martinfowler.com/articles/feature-toggles.html) on martinfowler.com, revised in 2017. He sorts toggles into four kinds: - **Release toggles** hide unfinished code so it can ship dark. - **Experiment toggles** route cohorts down different paths so you can compare the outcomes, and they have to sit still long enough for the result to mean anything. - **Ops toggles** let whoever is on call disable or degrade something that is misbehaving in production. - **Permission toggles** decide who gets what. The part that gets copied is the list. The part that gets dropped is that Hodgson sorts them on two axes, and only one of them is longevity. The other is dynamism: how dynamic the decision has to be. That axis is not a footnote. It is the whole engineering problem, and flattening it is how a team ends up buying one mechanism and using it for four jobs. Read the four again as deadlines instead of purposes: | Toggle | Flipped by | How fast it has to land | | ---------- | ------------------ | --------------------------- | | Release | The team, once | Whenever. Minutes are fine. | | Permission | A plan or a list | Next page load | | Experiment | A bucketing rule | At assignment, then stable | | Ops | Whoever is on call | Now. Seconds. | Three of those four are relaxed about time. One of them is not, and it is the one you reach for when something is already on fire. > **Key takeaway:** Ask a flag system how long a flip takes to reach a user, and compare that > number against the ops row. If the answer is "next page load", you have a > permission mechanism, and you do not have a kill switch. ### How a flag actually resolves A flag is a value that has to get from a console to a running client, and there are only a few ways to move it. Background polling is the common one: the SDK holds the flag set in memory and refetches on an interval. ConfigCat's own explainer, which is the most careful page currently ranking for this term, puts that interval at commonly 30 to 60 seconds and notes that some SDKs add webhook invalidation to shorten it. A pushed connection is faster and costs you a socket. Reading the flag from a store on every request is exact and costs you a round trip per render. Or you can hand the whole flag set over once, when the session loads, and read it from memory after that. BuildBase picked that last one, and it is worth being specific about the trade because it is the trade this whole post is about. Flags are fetched with the session data and cached locally, so there is no API call per render, and [our docs](https://docs.buildbase.app/feature-flags/overview) state the consequence plainly: changes take effect on the next page load or session refresh, not instantly for active sessions. There are two kinds. Workspace features are tied to subscription plans. User features target a user directly, by tag, or through a user or audience list, and four components gate the UI by slug: ```tsx ``` Map that against the table. Permission toggles: served well, because the deadline is a page load and the mechanism is a page load. Release toggles: fine, nobody is counting seconds. Experiment toggles: we have no bucketing and no percentage ramp, targeting is by user, tag or list, and no built-in conversion analytics either, so you would be tracking the result yourself. Ops toggles: no. That last one is not a gap we are embarrassed about so much as one worth saying out loud, because the docs say the quiet part too. Disabling a flag hides the gated UI on the next load, and running code is not interrupted. For a plan change that is correct behaviour, and nobody needs an upgrade to appear mid-keystroke. For a kill switch it is the wrong shape, because the request you want to stop is the one already in flight. ### When a flag is the wrong choice **When the answer is on your pricing page.** A gate that changes because a customer upgraded is not a flag, it is an entitlement, and it should resolve from the plan rather than from a targeting list somebody maintains by hand. The failure here is slow and expensive: a plan changes, most of the flags get updated, and one customer keeps a paid feature for four months. That is the sibling post, [entitlements are not feature flags](/blog/entitlements-are-not-feature-flags), and the distinction is worth more than it sounds. **When you need it off this second.** Covered above. A mechanism that lands on the next page load is not an incident tool, whatever the dashboard lets you click. If you need a real kill switch, it needs its own path. **When the flag has outlived its rollout.** A release toggle that survives its release is no longer a flag, it is a branch in your code that nobody owns. Hodgson's longevity axis is the warning: release toggles should be the shortest lived things you have, and the reason teams end up with forty of them is that deleting one is never anybody's job this sprint. **When what you actually want is a role.** "Can this person do it" is a permissions question, not a feature question. [RBAC owns that](/blog/what-is-rbac), and gating it with a flag gives you an access control system with no audit trail and no concept of a role. ### The one next to it Flags, entitlements and permissions are three gates that look identical at the render site and answer completely different questions. Is the code ready. Did they pay. Are they allowed. Getting them confused is the most common structural mistake in a B2B app, and it shows up as a boolean in a component either way, so nothing warns you. [What entitlements are](/blog/what-are-entitlements) is the next one to read if the pricing page is the thing your gates keep drifting away from. The propagation argument has a sibling on the permissions side too, where a role change [no longer waits for the hourly refresh](/blog/why-permissions-refresh-hourly) because an hour was the wrong deadline for that job. Same question as this post, different answer, and that is rather the point: the deadline comes from what the switch is for. --- ## Bring your own Stripe, explained > Bring your own Stripe means you keep the Stripe account and the platform connects to it. What that changes: who the legal seller is, who owes the tax, and what it really costs. - Source: https://www.buildbase.app/blog/bring-your-own-stripe - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-22 ### In short Bring your own Stripe means the platform you build on connects to a Stripe account you own, using your API keys. Customers pay you directly, the money lands in your Stripe balance, and the platform never holds it. The alternative is a merchant of record, who becomes the legal seller and pays you out. Bring your own Stripe means the platform you build on connects to a Stripe account you own, using your API keys. Customers pay you directly, the money lands in your Stripe balance, and the platform never holds it. The alternative is a merchant of record. They become the legal seller, and they pay you out. Almost every write-up of this choice frames it as a fee comparison. Keep your own Stripe, keep the 5%. That framing is not wrong, exactly. It is the smallest part of what you are deciding, and the arithmetic underneath it is a lot closer than the headline makes it look. ### What a merchant of record actually does A merchant of record is the legal seller of your product. Not a payment processor and not a billing tool: in Stripe's own words, "the entity that takes legal and financial responsibility for a sale". They remit the applicable taxes. They handle the disputes and absorb the fraud liability. You sell to them, in effect, and they sell to your customer, and then they pay you out on a schedule. That is a real service and it has a real price. Paddle and Lemon Squeezy, the two best known, both publish the same headline figure: 5% plus 50 cents per transaction (verified 22 October 2026 on [paddle.com/pricing](https://www.paddle.com/pricing) and [lemonsqueezy.com/pricing](https://www.lemonsqueezy.com/pricing)). Paddle's own FAQ says products under $10 need bespoke pricing, which tells you where that fixed 50 cents starts to hurt. The arrangement also shows up in small places. A Paddle charge reaches the customer's bank statement as `PADDLE.NET*` followed by your business name, trimmed to between two and ten characters (verified 22 October 2026 in [Paddle's statement descriptor reference](https://developer.paddle.com/api-reference/settings/get-statement-descriptor-settings)). Your brand is the suffix on someone else's prefix. ### How bring your own Stripe works You paste two keys into the platform and point a webhook at it. That is most of the mechanism. The publishable key and the secret key come from your Stripe dashboard. The platform stores them, then uses the Stripe API to create customers, prices and subscriptions inside your account, as you. A webhook endpoint pointed back at the platform's server is how it hears about a payment succeeding, a card failing, a subscription being cancelled from Stripe's side. Open your Stripe dashboard afterwards and every subscription the platform created is sitting there, under your business, in your own list of customers. So what is the platform actually doing, if Stripe holds the subscriptions? The part Stripe does not: plan versioning, entitlements, quota counting, the upgrade and downgrade rules, the trial clock, and all the product logic that decides what a customer is allowed to do between invoices. BuildBase works this way. Stripe credentials are stored per organization, the secret key and webhook secret encrypted at rest, with a per-organization toggle for Stripe Tax. We are not a merchant of record and we take no percentage of what you bill. That is a design choice with trade-offs, and the rest of this post is the honest version of them. ### The arithmetic, with every assumption shown Here is the comparison people quote, on a product doing $10,000 a month across 100 charges of $100, all on domestic US cards. A merchant of record at 5% plus 50 cents takes $500 on the percentage and $50 on the fixed fee. That is **$550 a month**. Your own Stripe account, taking payments only, costs 2.9% plus 30 cents per successful domestic card charge (verified 22 October 2026 on [stripe.com/pricing](https://stripe.com/pricing)). That is $290 plus $30, so **$320 a month**. A gap of $230 a month. This is the number the comparison posts stop at, and it is where they start being misleading, because the two columns are not buying the same thing yet. The merchant of record included subscription management and tax handling. Buy those back and the picture moves: - Stripe Billing, if you run your subscription logic through Stripe itself, is 0.7% of billing volume on the pay-as-you-go plan. On $10,000 that is $70. - Stripe Tax is 0.5% per transaction on the no-code integration, or 50 cents per transaction on the API one. Call it $50. Run both and your own-Stripe column is **$440**. The gap is now $110 a month, or $1,320 a year. > **Key takeaway:** On $10,000 a month, a merchant of record costs about $550 against $320 for > your own Stripe account. But the honest comparison adds back subscription > logic and tax handling, which brings the own-Stripe column to roughly $440. > The real gap is nearer $110 a month than $230. The 0.7% line is the one you can actually remove, and it is worth knowing why. If the platform you build on handles plans, versioning and metering itself, it is writing to Stripe's payments API rather than running subscriptions through Stripe Billing, so that fee never applies. Drop it and you are at $370 against $550, a gap of $180 a month. That is the strongest honest case for the model, and it is still a long way from what "keep the 5%" promises. Two things move this further, both against your own Stripe account. Stripe adds 1.5% for international cards, so a customer base that is 40% outside the US adds about $60 to that column while the merchant of record's 5% stays flat. And at low ticket prices the fixed fees dominate everything: on a $5 product, 30 cents is 6% before the percentage fee even starts. Run your own numbers before you believe mine. The crossover logic is the same one in [the hidden revenue tax of billing platforms](/blog/billing-platform-revenue-tax), which works through when a percentage beats a flat fee and when it stops. ### When a merchant of record is the better answer Tax. Almost always tax. Selling software across borders means registering to collect in each place that says you must, filing returns there, and keeping up as thresholds change. Stripe Tax calculates the right amount at checkout, which is genuinely useful, but look at how the pricing is worded: per transaction, "where you're registered to collect taxes". The registering is yours. The filing is yours. A merchant of record does both, and if you are a two-person company selling into thirty countries, handing that over for a few points of revenue is not a bad trade. It might be the best money you spend. Chargebacks are the other one. With your own Stripe account, a disputed charge is your dispute, your evidence to submit, your fee if you lose. A merchant of record takes that liability on. There is a third case nobody writes about: access. Stripe does not operate everywhere, and the requirements for opening a business account vary enough by country that plenty of founders simply cannot get one. Then the choice has already been made for you. So the model is a bad fit when you are small, selling globally, and would rather not become an amateur tax department. It is a good fit when your sales are concentrated in places you are already registered, when the volume makes a percentage expensive, or when you care about the thing in the next section. ### What you are really buying Ownership of the billing relationship, and the exit. Under a merchant of record, the customer bought from them. Your subscriptions live in their system, your payout history is their record, and leaving means migrating customers who, legally speaking, were never yours. Under your own Stripe account, the subscriptions were in an account with your name on it the whole time. Move off the platform and the billing keeps running, because the platform was only ever an API client holding your keys. That is worth more than $110 a month to some people and nothing at all to others, which is why this decision cannot be settled with a fee table. It depends on whether you expect to change platforms, and on whether an invoice with someone else's name on it bothers you. ### Where this sits next to the other billing decisions Bring your own Stripe decides who holds the money. It does not decide how you charge for anything, which is a separate question with its own answer: see [what is usage-based billing](/blog/what-is-usage-based-billing) for the pricing model, and [what are entitlements](/blog/what-are-entitlements) for the layer that decides what a paying customer can actually do. The one connection worth drawing is that these compound. A platform taking a percentage of revenue, on top of a processor taking a percentage of revenue, on top of a tax tool taking a percentage of revenue, is three lines on your P&L that all grow when you succeed. Knowing which of them you have actually signed up for is most of the work. --- ## What is a passkey, and which of the two kinds you just got > A passkey is a key pair your user's device holds and proves on your domain. A synced one and a device-bound one behave differently the day a phone dies, and the ceremony tells you which you got. - Source: https://www.buildbase.app/blog/what-are-passkeys - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-22 ### In short A passkey is a public-key credential: the user's device or password manager keeps the private half, your server keeps the public half, and signing in means the device signs a challenge your domain issued. Two kinds ship under that one name, synced and device-bound, and only one of them survives a lost phone. A passkey is a public-key credential. The user's device or password manager keeps the private half, your server keeps the public half, and signing in means the device signs a fresh challenge for your domain once the user confirms with a fingerprint, a face or a PIN. Every explainer on this query says that, and it is right. It also stops one step short of the thing that decides how your support queue looks in a year. Two different credentials ship under the word passkey. One is synced through a credential manager and lands on every device the user owns. The other is stuck on the single device that made it. Same API, same ceremony, same row in your database. Completely different answer to "my phone went in the river". And the ceremony tells you which one you just got. Most implementations throw that away. ### Why they exist Because a shared secret has two owners and either one can lose it. The user can hand a password to a convincing lookalike page, and you can lose the whole table to a breach, however carefully you hashed it. A passkey removes the shared secret. There is nothing on your server worth stealing, because the public half is useless on its own, and there is nothing to phish, because the credential only answers on the domain it was created for. A lookalike site at a different hostname does not get a prompt. It gets silence. That is the whole security argument, and it is the part already written about everywhere. The rest of this page is about what you actually hold afterwards. ### How it actually works Four things happen, and only the middle two are interesting. Your server generates a random challenge and names the domain the credential will belong to. The browser passes both to whatever credential manager the user has. That manager mints a key pair scoped to that one domain, asks the user to confirm, and hands back the public half with a signature over the challenge for your server to check. Then it stores what came back. The domain part is not a detail. WebAuthn binds every credential to the hostname that ran the ceremony, which on BuildBase is your organization's auth domain rather than your app or your API. Change that hostname later and the browser stops offering the passkeys registered under the old one, because as far as WebAuthn is concerned they belong to a different site. We store the `rpId` on every passkey and compare it to the current auth domain, so a credential stranded by a domain move is at least visible rather than mysteriously absent. Settle the domain before anyone enrols, which is the argument [running auth on your own domain](/guides/should-you-run-auth-on-your-own-domain) makes at greater length. The challenge has a clock on it. Ours is held in Redis for 300 seconds, 5 minutes exactly, and is consumed atomically, so it answers once and once only. A user who starts signing in, wanders off and comes back gets an expired-challenge error instead of a replayable window. They try again. That is the whole cost of the short window, and it is why the window is short. Here is what the server ends up holding, which is less than people expect: | Stored | What it is | | ------------------- | ------------------------------------------------------- | | Credential id | The handle the browser uses to find the right key | | Public key | The half that verifies signatures and decrypts nothing | | Signature counter | A number the authenticator increments, if it bothers | | Transports | How the authenticator was reached: internal, USB, NFC | | Device type, backup | Which of the two kinds this is, and whether it is saved | | Relying party id | The hostname this credential will answer on | No secret. Nothing that signs in anywhere else. If someone walks off with that table, they have a list of public keys and the knowledge that your users exist. ### The two kinds, and the flag that names them This is the part the generic explainers skip. The authenticator reports two things about backup when it creates a credential. Backup eligibility says whether this credential is allowed to leave the device it was born on. Backup state says whether it currently has. The W3C WebAuthn specification is blunt about the difference in lifetime: backup eligibility "is a credential property and is permanent for a given public key credential source", while backup state "can change over time". So: | Eligible | Backed up | What you have | | -------- | --------- | ------------------------------------------------- | | Yes | Yes | A synced passkey, on every device in that manager | | Yes | No | Syncable, not yet saved anywhere else | | No | No | Device-bound. This device or nothing | Read the middle row again, because it is the one that bites. The user has a passkey that is allowed to sync and has not synced yet. They look identical to the synced case in your UI, right up until the device is gone. > **Key takeaway:** Backup eligibility is permanent and tells you what the credential can ever do. > Backup state is a snapshot and tells you what it has done so far. Storing only > the second one, at registration, answers the wrong question later. We store both at registration, and the honest caveat is that we store the backup state as it stood that day. Our login path updates the signature counter and the last-used time, and does not refresh the backup flag. The specification says that flag appears in the data from any ceremony, registration and sign-in alike, so a live value is there to be read on every login if you want one. If you are building recovery prompts off a stored backup flag, know which it is: a snapshot from enrolment day, or something you keep current. There is a second flag worth the same attention. A passkey ceremony does not always verify the user. It can check that somebody is present, a touch on the authenticator, without checking who. A passkey sign-in that verified the user with a PIN or a biometric counts as both steps on its own, which is why we pass that result through to the login gate rather than assuming it. A ceremony that only proved presence proves the device, and no more. ### When a passkey is the wrong choice An explainer that only lists upsides is a brochure with a dictionary voice, so: **As the only way in.** Whatever lets a user back without their passkey becomes the real security boundary of the account. If that is an emailed link, your passkeys are as strong as an inbox. Not a reason to skip them. A reason to stop calling the recovery path an edge case and go look at it. **For accounts people share.** A passkey is bound to a credential manager, which belongs to a person. Two contractors and one logistics login do not fit that shape, and the workaround users invent will be worse than whatever you were avoiding. **On machines nobody owns.** Shared terminals, kiosks, a borrowed laptop. A passkey there is either unusable or gets enrolled somewhere it should not live. **Before you have settled your auth hostname.** Covered above, and it is the expensive one, because it is invisible until the day you move and then it is every user at once. None of these argue for passwords. They argue for passkeys plus one other method that does not depend on the same device, which is how the sign-in list is built anyway: passkeys sit alongside email codes, magic links and the rest, and a user who cannot reach one reaches another. ### Where it sits next to the others Passkeys are one of the passwordless methods, not the whole category, and the others trade differently. A [magic link](/blog/what-are-magic-links) asks nothing of the device and everything of the inbox: no enrolment, no lost-phone story, and a session handed to whoever is reading the mail. A passkey inverts that. It asks for enrolment on a real device and gives you a credential that phishing does not touch. The practical answer for most products is both, with the passkey as the fast path and something email-shaped underneath it. If you want the implementation rather than the concept, [adding passkeys in Next.js](/guides/passkeys-nextjs) has the decision that actually costs you something, which is the same hostname question as above. --- ## What is a SaaS backend, and which half of it is your product > A SaaS backend is the server side of a subscription product. What makes it a SaaS backend is not the stack but the account model it carries: tenant, permission, usage and subscription. - Source: https://www.buildbase.app/blog/what-is-a-saas-backend - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-22 ### In short A SaaS backend is the server-side half of a subscription product: the APIs, data and rules behind every customer screen. What separates it from an ordinary web backend is not the stack. It is the account model it carries - who the user is, which customer they belong to, what they may do, and what they owe. A SaaS backend is the server-side half of a subscription product: the APIs, the data and the rules that run behind every customer's screen. What makes it a _SaaS_ backend rather than an ordinary web backend is not the language or the database. It is the account model it has to carry - who the user is, which customer they belong to, what they are allowed to do, what they have used, and what they owe at the end of the month. Microsoft's architecture guidance puts the distinction in one line: [SaaS is a business model and multitenancy is an architecture concept](https://learn.microsoft.com/en-us/azure/architecture/guide/saas/overview). So "SaaS backend" names a backend shaped by a commercial arrangement, not a tier of technology. Most of the pages ranking for this question answer it with a diagram of three layers, data and application and API, and a list of runtimes that would serve a blog equally well. Those layers are real. They are also not the part that takes the time. ### Two different things go by this name The phrase is doing double duty, and the search results mix them freely. One meaning is the server behind the SaaS product you are building. Your code, your database, your rules, sold to your customers as a subscription. The other is a backend sold to you as a service: a vendor's hosted auth, data and APIs that you build on instead of standing up yourself. That is a backend-as-a-service, and it is a supplier, not a product category you belong to. They get conflated because one is routinely built from the other. You can rent a backend as a service and have it be the backend of your SaaS, and plenty of companies do. The test that separates them is who is paying whom. If people pay you to use the thing running on it, you are looking at your SaaS backend, whoever supplies the parts. ### The half that is yours, and the half that is everyone's Here is the claim worth arguing with: in most SaaS products, the backend splits cleanly in two, and the half founders budget for is the smaller one. The first half is the product. Whatever your customers actually pay for - rendering the image, running the workflow, matching the shifts. It is different in every company, nobody else can write it, and it is the reason the business exists. The second half is the account model, and it is close to identical everywhere. Somebody signs in. They belong to a company, and that company has members with different levels of access. The company is on a plan, the plan allows some things and not others, usage accrues against an allowance, and at some point an invoice has to be right. Then the product has to tell people what happened, keep a record of who did what, and let an admin undo it. None of that is differentiating. All of it is load-bearing, and all of it is where the schedule goes. The figure we publish on our own about page is 60-70% of engineering time going to infrastructure rather than product, and we put building sign-in alone at 3-6 weeks before anyone has charged a customer anything. Sign-in is a good illustration of how the second half quietly grows. Doing it properly now means email and password, magic links, email codes, phone codes through your own provider, passkeys, Google, GitHub, Microsoft, Apple, LinkedIn, a custom OIDC connection, and wallet sign-in for Ethereum and Solana. Every one of those is a week nobody put on the roadmap, and not one of them is why a customer chose you. ### What one request has to answer The clearest way to see the split is to follow a single API call into a SaaS backend. Say a user clicks something in your app and it hits one endpoint. Before your code does anything interesting, the request has to resolve: is this token valid and unexpired, which session does it belong to, which tenant is the caller acting inside right now, is this member's role allowed to do this, does the tenant's plan include this feature at all, and does it have allowance left this month. Then, and only then, your business logic runs. Afterwards the usage has to be recorded somewhere an invoice can find it, and the whole thing has to land in an audit trail. Count the steps. One of them is your product. Each of those answers is also a design decision with a lifespan. Short-lived access tokens with long-lived sessions behind them is one shape - ours are a 2-minute token against a 30-day session, and permission changes propagate on an hourly refresh rather than instantly, which is a real tradeoff and [one we had to defend](/blog/why-permissions-refresh-hourly). The point is not that those numbers are correct for you. It is that you will pick a number for each of them, and changing your mind later is a migration. We run six products of our own on one backend: OnceBooks, PlugNode, AgentCenter, Imejis, RemoteWait and LinkTracer. OnceBooks alone uses fourteen of the twenty modules. The reason that works is not that the products are similar, because they are not. It is that the second half of their backends was always the same, and only the first half ever had to be written again. ### When a shared SaaS backend is the wrong choice An explainer that only lists advantages is a brochure with a dictionary voice, so here are the cases where this shape does not fit. **When the backend is the product.** If what you sell is the database, the queue or the inference, then the thing I have been calling "the second half" is your margin and your moat. Buying it is buying your own product from someone else. **When a customer's contract requires their own deployment.** Some buyers, particularly in regulated sectors, will not sign unless their data sits in infrastructure nobody else touches. That is a single-tenant install per customer, with its own upgrade schedule, and a shared backend does not get you there. **When you outgrow the deployment.** Pooled per-tenant database connections do not scale forever. Roughly 1,000 orgs per deployment is the documented ceiling on ours, and past it the answer is another deployment rather than another config change. [Connection pool exhausted as org count grows](/guides/connection-pool-exhausted-multi-tenant) has the arithmetic. Any backend serving many tenants has a number like this; the useful question to ask a vendor is what theirs is, not whether they have one. ### Where this sits next to multi-tenancy A SaaS backend is the whole server side. [Multi-tenancy](/blog/what-is-multi-tenancy) is the narrower property of serving many customers from one copy of it without letting their data mix, and it is the decision that shapes everything above: which object is the tenant decides what rows belong to whom, what the subscription hangs off, and what the quota counts. From there the account model fans out into the concepts that have their own pages. [Roles and permissions](/blog/what-is-rbac) decide what a member may do once you know which tenant they are in. [Entitlements](/blog/what-are-entitlements) decide what their plan includes, which is a different question from what their role allows. [Usage-based billing](/blog/what-is-usage-based-billing) decides what the meter does with the result. If you want the version with prices attached rather than definitions, [the cost of building auth yourself](/blog/cost-of-building-auth-yourself) does the arithmetic on one piece of the second half, and [the real cost of a multi-vendor stack](/blog/auth-billing-stack-cost) does it on the bill you end up paying when you buy each piece separately. [Best multi-tenant backend](/compare/best-multi-tenant-backend) covers the options if you have decided to buy rather than build. --- ## What are magic links, and what the click actually hands over > A magic link is a single-use URL emailed instead of a password. The token lives an hour. The session it buys lives thirty days, and that is the number worth arguing about. - Source: https://www.buildbase.app/blog/what-are-magic-links - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-19 - Updated: 2026-10-22 ### In short A magic link is a single-use, time-limited URL emailed instead of a password: the server mints a token, the user clicks, and the token is redeemed for a session. The token expires in minutes or an hour. The session it grants can last weeks with nothing behind it, and that is the real decision. A magic link is a single-use, time-limited URL you email to someone instead of asking them for a password. They click it, the server redeems the token behind it, and they are signed in. Most explainers stop about there, then spend the rest of the page arguing about the token: how long it should live, whether five minutes is safer than fifteen, whether it should be signed or opaque. That argument is mostly theatre. The token is the one part of this system that lives for minutes and is used once. What the click actually hands over is a session, and in most products that session is measured in weeks. ### Why they exist at all The honest case for magic links is not that they beat passwords on security. It is that you already built one. Every password system ships a reset flow, and that reset flow is almost always a single-use link or code emailed to the address on file. Ours sends a six digit code. So the inbox is already the master key to the account - it always was, quietly, behind a password that a reset mail can replace in thirty seconds. A magic link removes the password and admits what the email address was doing all along. What you get for that is real: no password storage, no "must contain a symbol", and nothing for a user to reuse from a breached site. You do not get to delete the emailed-link flow, since that is now the front door rather than the back one, but you do stop maintaining two of them. What you give up is a second thing the attacker has to hold. With a password in place, an inbox takeover is step one of two, and the second step is still guessing something you never emailed to anybody. Without it, the inbox is the whole job. ### How it actually works Four clocks, not one. The link is only the first. Here is the chain BuildBase runs, because a concrete one beats a diagram. Asking for a link mints a signed token, stores it, and emails a URL. What travels in the email is not the token: it is a 32-character opaque code, and the signed token sits server side in Redis, with a SHA-256 hash of it in the database alongside an expiry. The row holds the address, the hash and the expiry date, and never the token itself. When the link is opened, the code is exchanged for the token and the token is redeemed with a single atomic delete. That matters more than it sounds. Finding the row and then deleting it is two operations, and two concurrent clicks can both pass the find. One `findOneAndDelete` cannot: the first caller gets the document, the second gets nothing. That is what makes the link genuinely single use rather than approximately single use. Then the part nobody draws: | Stage | Lives | What it is | | ---------------- | ------------------------- | -------------------------------------------------- | | The emailed link | 1 hour | An opaque code standing in for a server-side token | | The login token | 24 hours | What redeeming the link actually returns | | The auth code | 10 minutes | Minted at the redirect step, traded for a session | | The session | 30 days, or 90 remembered | The thing the user actually walks away with | Redeeming the link does not mint the session. It returns a login token, the sign-in page trades that at the redirect step for a 10 minute auth code, and your app exchanges the code at the token endpoint. Only at that last exchange is the lifetime chosen: 30 days by default, 90 if the person ticked remember me, under a hard ceiling of 180 days that an organization's own settings cannot raise. The configurable range is 1 to 180 days, and a plan limit can pull it lower still. Four hops to get there, and the longest-lived of the first three is a day. The thing waiting at the end of them lasts a month. > **Key takeaway:** The link expires in an hour. The session it produces lasts 30 days by default, > which is 720 times longer. If you only tune one number in a magic link setup, > tune the session. ### The expiry everyone tunes Published defaults for the link itself cluster in a narrow band. Clerk expires email links after 10 minutes. Auth0 defaults its passwordless email code to three minutes. Supabase and Stytch both default to an hour, and Stytch's signup links default to a week. Descope publishes no default and recommends three to five minutes. Now the other number, from the same vendors' own docs. A Supabase session, by default, lasts indefinitely until the user signs out; time-boxing it is opt-in. Clerk gives new instances a seven day maximum session lifetime, with inactivity timeout off by default. So a product can ship a 10 minute link and a 7 day session, and call the first number its security story. The real boundary is the second one. A stolen link is worthless in eleven minutes. A stolen session cookie is good for that whole week, and there is no password behind it to re-establish who is holding the laptop. This is also why magic links and long sessions are an awkward pair. The method's whole premise is that proving control of an inbox is enough, and the session length quietly decides how long ago that proof is allowed to have happened. A month ago, on a laptop since sold. ### What breaks in practice Three failure modes, and only the first is widely discussed. **The link opens somewhere else.** Someone requests sign-in on a laptop and taps the link in their phone's mail client. The sign-in completes using state held in the browser that asked for it, so the link does not sign them in on the phone, and in many systems it is now spent for the laptop too. BuildBase, by default, refuses it in a browser that did not ask for it before using it up, so the laptop can still finish. Say "open this on the same device" on the sign-in screen and make a second request cheap. **A scanner clicks it first.** Corporate mail security follows URLs before the human does. Microsoft's own documentation for Defender for Office 365 Safe Links says URLs are scanned prior to message delivery and that URLs without a good reputation are detonated asynchronously in the background. Stytch documents the consequence plainly: the scanner "will end up consuming the token before the email actually makes its way into the user's inbox", which in some corporate environments makes email magic links unusable. Supabase names email prefetching as the most common cause of its expired-token errors. The mitigations in the field are an interstitial page that needs a real click, a bot check at redemption, or dropping the link and sending a code to type. **They ask for a second link.** Someone does not see the first mail, clicks send again, then finds the first one and taps that. Whether that works is a design decision each vendor makes differently, and almost nobody states it on the sign-in screen. BuildBase deletes the previous token when a new one is issued, so only the newest link works. Descope documents the opposite: sending multiple magic links does not invalidate the earlier ones. Neither is wrong. Both will confuse someone with two tabs open. A magic link is an email before it is an auth method. It inherits every delivery problem email has. If the mail lands in spam or arrives four minutes late, the method simply does not work, and no amount of token design fixes it. That is a [deliverability problem](/guides/transactional-email-landing-in-spam), and it is the most common reason a magic link rollout gets reverted. ### When a magic link is the wrong choice An explainer that only lists upsides is a brochure. Four cases where this is the wrong tool: **When the inbox is what you are protecting.** For an email client, a domain registrar, or anything holding the keys to other accounts, emailing the entry credential puts the lock inside the box. **When sign-in happens away from the mail.** A kiosk, a TV app, a shared terminal, a workstation where corporate mail only exists on a phone. Every one of those turns a one-tap flow into a two-device errand. Send a code instead. **When the address is shared.** `billing@` and `support@` are read by several people, and a magic link to a shared mailbox is an account anyone in that mailbox can enter. That is a provisioning problem wearing an auth costume. **When speed is in the critical path.** Sign-in during a checkout or a live demo against an inbox that may take a minute is a bad trade. Keep passwords or passkeys on that path. The alternative worth reaching for first is [passkeys](/guides/passkeys-nextjs). They are phishing resistant in a way a mailed link is not, because the credential is bound to the origin and cannot be replayed on a lookalike domain. The cost is recovery: a passkey lives on a device, and when the device goes, something has to let the person back in. That something is very often a magic link. The two methods pair better than they compete, which is why BuildBase ships both among its sign-in methods, and why most products that offer passkeys keep an emailed fallback behind them. ### The session is the part that outlives the decision Everything interesting happens after the click, and the sharpest edge shows up once authorization enters the picture. A 30 day session means a decision made a month ago is still being honoured, which is fine for identity and much less fine for permissions. Somebody demoted this morning is still carrying a token minted a month ago. How often that is re-checked, and what a role change does to a live session, is [its own question](/blog/why-permissions-refresh-hourly) and worth settling before you lengthen a session to make sign-in less annoying. If you are wiring this up rather than deciding about it, the implementation side is in [how to add magic-link login in Next.js](/guides/magic-link-login-nextjs), which covers the call, the callback and the failure modes above in code. --- ## Idempotency in billing, and why it matters > Idempotency in billing means a retried charge, usage event, credit debit or webhook takes effect once. Having a key is the easy part. What the key names is where double billing starts. - Source: https://www.buildbase.app/blog/idempotency-in-billing - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Idempotency in billing means applying an operation twice has the same effect as applying it once: a retried charge, usage event, credit debit or webhook moves money one time. Networks deliver at least once, so exactly-once billing is at-least-once delivery plus a receiver that refuses to apply the same key twice. Idempotency in billing means applying the same operation twice has the same effect as applying it once. A charge retried after a timeout charges once, a usage event sent twice counts once, a credit debit replayed by a queue debits once, and a webhook delivered three times grants one thing. Most explainers on this stop at "send an idempotency key with the request". That is the easy half. Three idempotency bugs written up in the comments of BuildBase's own billing code had a key the whole time: one named the retry instead of the event, one forgot which organization the event belonged to, and one was written down before the work was safe. A key fixed none of them. Deciding what it meant did. ### Why it exists: a timeout is not a no A billing write over a network has three outcomes, not two. It worked and you heard. It failed and you heard. Or you heard nothing, and the work may or may not have happened on the other side. That third case is the whole subject. Retry, and you might charge twice. Give up, and you might never charge at all. Every layer between your code and the money - the HTTP client, the job queue, the SDK, the provider's webhook sender - settles the question the same way. It retries. So the double charge is rarely a bug in the usual sense. It is your reliability engineering doing its job. The BuildBase queue that reports overage to Stripe makes up to 5 attempts with exponential backoff. Our outgoing webhooks retry a failed delivery 4 more times, at roughly 10s, 20s, 40s and 80s. Stripe retries a live-mode webhook for up to three days. Every one of those retries exists so that nothing gets lost. Without a key, every one is also a chance to apply something twice. ### Exactly once is two guarantees, not one "Exactly-once delivery" is the phrase people reach for, and over a network it is not on offer. A sender that hears nothing cannot tell a request that never arrived from a response that never came back, so it has to pick: retry and risk a duplicate, or stop and risk a loss. Billing cannot afford the loss, so the sender picks the duplicate. What you can build is exactly-once _processing_, and it splits into two jobs owned by two sides: - **The sender delivers at least once.** It keeps trying until the receiver acknowledges. - **The receiver applies at most once.** It recognises a repeat and answers with the first result instead of doing the work again. Put them together and each operation takes effect once. Remove either and you are back to choosing between a lost charge and a double one. The key is only the mechanism the receiver uses to recognise a repeat. > **Key takeaway:** Exactly-once billing is at-least-once delivery plus idempotent processing. The > sender's retries make sure nothing is lost; the receiver's key makes sure > nothing is applied twice. Neither half works on its own. ### How it works for the four billing writes An idempotency key is a value the caller sends with a write so the receiver can tell a retry from a new operation. The receiver stores it with the effect, and a second request carrying it gets the first answer back. That mechanism is the same everywhere. What the key should name is not. | Write | Who retries it | The key should name | | ------------------------ | ---------------------------- | ------------------------------------------- | | A charge or invoice item | your server, your job queue | the thing being charged for | | A usage event | the client, your queue | the unit of work that used something | | A credit debit | the client, a background job | the job that spent the credits | | A webhook you receive | the sender | the sender's event id, plus who received it | **A charge.** Stripe documents its version precisely, and the details are the point. On its v1 API, Stripe saves the status code and body of the first request made with a key once the endpoint starts executing, and returns that saved response to every retry with the same key, including a `500`. It compares a retry's parameters with the original and errors if they differ. Keys run up to 255 characters, can be pruned once they are at least 24 hours old, and only `POST` requests take one, since `GET` and `DELETE` are idempotent already. A good key is built from the facts of the charge. In BuildBase, when a plan change carries metered usage onto the next invoice, the invoice item is keyed on the subscription, the subscription item and the number of units carried. Retry the plan change and it is still one charge. **A usage event.** `bb.usage.record()` takes an `idempotencyKey`, and a repeat of a key already recorded for that quota returns the current standing without counting again. The key is unique per workspace and per quota, so one request that uses two quotas can pass the same key to both. The trap is what you pass in. Our docs' samples use the incoming `x-request-id` header. That works when your caller sets the header and sends the same value on a retry. If a proxy in front of you stamps a fresh one on every request, each retry arrives with a new key and the key protects nothing. We meter our own customers on BuildBase, and the job that reports their usage sidesteps the question. Counts are taken from a buffer in batches, and the key is minted when the batch is taken, then travels inside the queued job. A retry re-sends the same counts under the same key. A report that re-read the buffer on retry would send new counts under an old key, or old counts twice. **A credit debit.** `bb.credits.consume()` takes a key the same way. The interesting part is where the protection actually lives. The server does look the key up before debiting, but that read is not atomic with the debit, so two retries racing each other can both pass it. What decides is a unique index on the credit ledger over the workspace and the key. The second debit's ledger row is refused, its deduction is put back, and it answers with the first debit's result. That is the general rule, and the reason "check whether we have seen this key" is not an implementation. A read followed by a write is a race. The constraint in the database is the referee; the read is a fast path for the common case. ```typescript // One key per unit of work, made before the first attempt // and reused by every retry of it. const key = `export:${exportJob.id}`; await bb.credits.consume(workspaceId, { amount: 50, description: 'Batch export', idempotencyKey: key, }); ``` **A webhook you receive.** Here the sender hands you the key. Stripe's own advice is to log the event ids you have processed and skip any you have seen, and it adds a wrinkle worth knowing: in some cases it generates two separate event objects for the same change, which it says to catch with the id of the object in `data.object` plus the event type. Even a provider's event id names a message, not a business fact. BuildBase's Stripe endpoint [verifies the signature](/guides/stripe-webhook-signature-verification-failed-nextjs) first, then stores the event under a unique index on its id, queues it, and only then answers 200. A duplicate delivery hits the index instead of creating a second row. Those rows are kept for 365 days, against a sender that retries for three. ### Where it breaks: what the key names The mechanism is solved. The meaning is where billing double-charges, and the three bugs in our own code show it better than any definition, because each one had a key from the start. **The key named the attempt, not the event.** Overage reports to Stripe go out from a queue, and [the Stripe key used to be built from the queue job](/blog/idempotency-keys-metering-write-path). A sweep every 10 minutes re-enqueues usage logs still marked unbilled. When Stripe had accepted a report but our write marking the log as billed failed, the sweep created a new job for the same log, with a new id and so a new key, and the same overage could be billed twice. The key now comes from the usage log, which is the thing being billed, rather than the job carrying it. The same trap catches any key built from a field that can move. Plan credit grants are keyed on the subscription, the plan version and the period end. A trial converting to paid moves the period end, so a grant at that moment would carry a fresh key and walk past the duplicate check. The code does not grant there, for exactly that reason. **The key forgot whose it was.** Processing jobs for Stripe events were deduplicated on the event id. But one Stripe account can be connected to more than one BuildBase organization, which every test-mode setup reusing a key does, and Stripe then sends the same event id to each. Whichever organization queued it first was the only one to process it. The other's job was dropped as a duplicate after its webhook had already answered 200, so Stripe never retried. Our payment lifecycle test suite caught it, with a subscription that existed in Stripe and never locally. The job id now includes the organization. A key is unique only within a scope, and the scope has to be part of the key. **The key was written down before the work was safe.** The Stripe endpoint stores the event row, then queues the job. If queueing failed, it answered 500 and Stripe retried. The retry hit the unique index on the stored row, read that as "already handled", and answered 200, with the event never processed. Seen is not done. A duplicate now falls through to the queueing step instead of returning early, and because the job id comes from the event, queueing it again does nothing while the first job exists. > **Key takeaway:** A key fails in three ways that having one does not prevent: it names the retry > instead of the event, it leaves out the scope it is unique within, or it is > recorded before the effect is safe. Build it from the business event, include > whose it is, and record it with the effect rather than ahead of it. ### When idempotency is the wrong tool A key fixes one problem: the same operation arriving twice. It gets reached for when the problem is something else. **When the write already sets state.** Setting a subscription's status to `active` from a webhook is safe to apply twice. Adding credits from one is not. The cheapest idempotency is a write that sets a value instead of adding to it, and where a handler can be shaped that way, a key table on top is one more thing that can fail. **When two different events arrive in the wrong order.** They are not duplicates, and no amount of deduplication fixes them. Stripe does not guarantee event order and neither do our webhooks. Our Stripe event worker processes one event at a time for that reason, which is an ordering fix, not an idempotency one. **When the retry outlives the window.** A key only works while the receiver remembers it. A job that retries a Stripe call more than 24 hours later may be a new charge as far as Stripe is concerned, so anything with a longer retry horizon needs its own record of what it already did. For overage, that record is the billed flag on each usage log. **When the key is too coarse.** Two genuinely different operations that share a key get merged, and the second silently does not happen. [That is an under-bill](/guides/usage-does-not-match-invoice), and unlike a double charge, nobody writes in to report it. If you are unsure whether two writes are the same operation, they are not. Give them different keys. And one gap that is ours. BuildBase's outgoing webhooks carry no unique event id; our webhook docs say so. Retries repeat the same `event` and `timestamp`, but no single field in the delivery is the event's identity. So a handler for our webhooks has to be safe to run twice by construction: set state from the payload, do not add to it. A `credit.consumed` handler that subtracts the amount from a local copy of the balance double-counts on a retry. One that stores the balance the payload carries does not, as long as it keeps the newer `timestamp` when two deliveries arrive out of order. ### Where this sits next to usage-based billing Idempotency is the property that turns a usage invoice from accurate into defensible. [What usage-based billing does to your invoices](/blog/what-is-usage-based-billing) gives it one line. This post is the long version of that line. Idempotent ingestion is also part of the scope that [the cost of building usage metering yourself](/blog/cost-of-building-usage-metering-yourself) prices, and its line about a meter that double-counts on retry is this whole post in one sentence. In code, the per-request version is [charging per API call](/guides/charge-per-api-call-nextjs), where a client's automatic retries are the invoice dispute you will actually get. The debit version is the [credits wallet](/guides/credits-wallet-nextjs), including why the database and not the handler is the referee. And on the receiving side, the reason our five-minute signature window is tight is the same gap as above: with no event id, [the age check is the replay defence](/guides/webhook-rejected-after-five-minutes). Both `bb.usage.record()` and `bb.credits.consume()` take an `idempotencyKey`, and the [credits and usage reference](https://docs.buildbase.app/credits/overview) has the full surface. The decision about what the key names is yours either way. --- ## Idempotency keys on the metering write path > How BuildBase keeps a retried usage record from counting twice: a key per hop, minted where its quantity stops changing, and the one hop where our check still runs early. - Source: https://www.buildbase.app/blog/idempotency-keys-metering-write-path - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Idempotent usage metering means a retried usage record counts once. In BuildBase your idempotencyKey guards the quota counter, matched on workspace, quota slug and key, and the Stripe overage report gets its own key from the usage log row. Sequential retries count once. Two in-flight copies of one key can both count. [An idempotency key](/blog/idempotency-in-billing) protects one write. A metered unit in BuildBase goes through three before it reaches an invoice: the quota counter on the workspace, a row in the usage log, and, when the unit is overage, a usage report to Stripe. The key your code sends covers the first two. Stripe never sees it. So "is our metering idempotent?" was really three questions, one per hop, and we answered them at different times. We got one wrong first. Another still checks too early. The rule we landed on fits in a sentence: mint each key from whatever is already fixed at that hop, and let a unique index decide, never a read. ### Retries are the normal path At any real volume, a usage record gets retried by design rather than by accident, so the key has to hold on every hop and not only on the one your code calls. The usage endpoint allows 60 requests a minute per IP, and the batch route is the way past that: one request, up to 100 items. The [429 guide](/guides/quota-429-not-exhausted) covers what happens when you skip it. Batching means buffering. A buffer is flushed by a job, and jobs retry. On our side alone, the job that reports overage to Stripe gets five attempts with exponential backoff, and a sweep every 10 minutes re-queues any overage row older than 2 minutes that is still not marked billed. Each of those is a deliberate second attempt at a write that may already have landed. It is also why idempotent ingestion sits in the scope of [what metering costs to build yourself](/blog/cost-of-building-usage-metering-yourself): the key is one line, and putting it in the right place on every hop is not. We sit on the calling side too. When our console meters a customer org's usage against its plan, its emails, workflow runs, push notifications and webhook deliveries, among others, are counted into a Redis buffer, and every 30 seconds a flush reports them to that org's workspace in our own BuildBase, through the same `POST /usage/batch` your backend calls. A failed report gets eight attempts. So the keys below were designed by people who also have to send them. ### Hop one: your key and the counter The key you send is matched on workspace, quota slug and key together, and a match answers without touching the counter. `POST /usage`, and every item in `POST /usage/batch`, takes an optional `idempotencyKey` of 1 to 255 characters. Before it increments anything, the service looks for a usage log row with that workspace, slug and key. If it finds one, it returns the current standing with `used: 0`. If it finds nothing, it increments `quotas.` on the workspace and then writes the log row that carries the key. If you call `bb.usage.record` from a route handler the way [the per-API-call guide](/guides/charge-per-api-call-nextjs) does, this is the only hop you touch. The log row is the thing that remembers. Its collection carries a unique index over the same three fields, partial so that rows recorded without a key never collide with each other: ```ts // server/src/model/workspace/quotaUsageLogs.model.ts schema.index( { workspace: 1, quotaSlug: 1, idempotencyKey: 1 }, { unique: true, partialFilterExpression: { idempotencyKey: { $type: 'string' }, }, } ); ``` The slug is in the match on purpose. One request id can record `api-calls` and `storage-mb`, and both land. Two trade-offs come with this shape. A replay does not hand you the original response back: Stripe saves the first response to a key and replays it, while we answer with where the counter stands now, and `used: 0` is how you tell a replay from a fresh record. And a key is remembered exactly as long as its log row, which sits under a retention window of 730 days. Stripe keeps a key for at least 24 hours and may prune it after that. Ours catches a retry that turns up a month late. ### Hop two: the key Stripe sees, and the one we got wrong The overage report to Stripe is keyed on the usage log row, not on the queue job that sends it, because a re-send is a new job with a new id and the row is the one thing that stays the same. Overage is not reported inside your request. The request writes the log row with `billedToStripe: false` and the number of billable overage units, then queues a job. The job reports those units to Stripe and flips the flag. If the job never runs, or fails every attempt, the sweep finds the row still unbilled and queues another one. The first version keyed the Stripe call on the job id. Walk the failure through. The job reports the overage, Stripe accepts it, and then the write that marks the row billed fails. The row still reads unbilled. The next sweep, up to about twelve minutes later, picks it up and queues a new job, which has a new id, which makes a key Stripe has never seen. Stripe does what it is told. The comment that now sits on the fix says it plainly: "Keyed on the job, the sweep billed the same overage twice." The fix keys on the row, which exists before any job does and is the same row every time the sweep finds it: ```ts // server/src/vendors/bullmq/queue/stripe/usage-sync-key.ts export function usageSyncIdempotencyKey( data: { usageLogId?: string }, jobId: string | undefined ): string | undefined { if (data.usageLogId) return `usage-sync-log-${data.usageLogId}`; return jobId ? `usage-sync-${jobId}` : undefined; } ``` Hold on to that fallback, because it comes back later. A job with no row still gets a key from its own id, which covers the queue's retries of that one job and nothing else. The other half of the fix is Stripe's, and we checked it rather than assumed it. Our Stripe conformance test ran green against Stripe's test mode on 11 September, and one of the assumptions it confirmed is exactly this one: the same idempotency key really does stop a second usage report. The sweep runs every 10 minutes, so as long as it is running, a re-send under the same key arrives well inside the 24 hours Stripe keeps one. ### Mint the key where the number stops changing For a buffer, the quantity becomes final at the moment you take it out, not at the moment you send it. That is where the key belongs. Our console's reporter is the clearest case, because the wrong place for the key was sitting right next to the right one. Sends are counted into a Redis hash per org. Every 30 seconds the flush takes each org's hash in a single Lua call, read and delete together, so a send counted mid-flush lands in the next flush instead of vanishing between the two. Then it mints one id for the take: ```ts // server/src/services/quota-usage.service.ts export async function takePendingUsage( orgId: string ): Promise { const counts = await QuotaUsageRedis.take(orgId); const flushId = crypto.randomUUID(); return Object.entries(counts) .filter(([, quantity]) => quantity > 0) .map(([quotaSlug, quantity]) => ({ quotaSlug, quantity, source: QUOTA_USAGE_SOURCE, idempotencyKey: `${QUOTA_USAGE_SOURCE}:${flushId}:${quotaSlug}`, })); } ``` The items, keys included, ride inside the report job, and the job is queued with the first item's key as its id, so queueing the same take twice is a no-op. Every retry sends the same items under the same keys. Why not mint the key when the report goes out? Because then the report has to read the buffer itself, and the comment on that queue names both ways that breaks: it "would send new counts under an old key, or old counts twice." Re-read on retry, and an item that now holds fresh sends arrives under a key the server has seen, so it answers as a replay and counts none of them. Mint a key per attempt, and a report that landed but timed out is counted again. Same mistake both times: a key born before or after the number it names. A derived write gets a derived key, too. When an item is refused at a hard cap, our central service re-records the part that still fits under the original key plus `:clamp`, so the smaller record and the refused one can never collide. ### Where our check is still too early The replay check on hop one is a read, and the index behind it sits on a row that is written after the counter moves. Retries that arrive one after another are safe. Two copies of one key in flight at the same moment both count. Walk it through. Both requests look for the key and find nothing, because neither has written its row yet. Both increment the counter. The first writes its row, and the unique index refuses the second. But that log write sits in a try/catch that logs the failure and carries on, so the second request still answers success. The counter has moved twice and there is one row. Each response works out the new total from its own earlier read, so neither one shows the double. On a plan with overage it reaches Stripe as well. The second request has no row, so its job has no row id, so its Stripe key falls back to the job id. That is the fallback from hop two, doing exactly what it says and nothing more. The batch route turns a rare race into a certain one. It runs every item through `Promise.allSettled` at once, so two items in one batch with the same key and slug are always in flight together. (The 429 guide covers the narrower cousin: when the log write fails outright, the key is never stored at all.) Credits had this exact race, and it is closed there. A consume also checks the ledger for its key before it debits, and two in-flight retries can still both pass that check. The difference is that the ledger's unique index is the referee: when it refuses the row, the bucket decrement and the balance decrement are both put back, and the loser answers with the winner's result. The comment at the top of the test that pins it could describe the quota path today: the promise "held only when the retries arrived one after the other." Quotas and credits are separate systems for good reasons, which [quotas are not credits](/blog/quotas-are-not-credits) lays out, but this fix belongs in both. For a stretch, the index on the quota side existed only in the schema, too. `autoIndex` is off across the platform, and until recently nothing built a declared tenant index at all, so the read was the only guard. A declared index is not an index the database holds. Until the quota path gets the credits treatment, two habits keep you out of it. Collapse a batch by key before you send it. A buffer like the one in [the Express metering guide](/guides/usage-metering-middleware-express) holds items until the flush, so a client that retries inside that window puts the same key in the buffer twice, and both copies then travel in one batch. And back off before retrying a single record, so the retry is far more likely to arrive after the first attempt has written its row. The full request shape is in the [quota reference](https://docs.buildbase.app/credits/quotas). ### What we would do differently Make the index the first thing that moves. There are two ways to get there, and each one sends a bill. Claim first: insert the log row, let the unique index refuse a duplicate before anything has changed, and only then increment. A crash between the claim and the increment leaves a row with no unit behind it, and the retry is answered as a replay, so that unit is never counted. That errs toward under-billing, which is the right direction to be wrong in on someone else's invoice. It is still wrong. Compensate: keep today's order and do what credits does, putting the increment back when the index refuses the row. Nothing is lost. But the counter runs ahead for the length of the race, and on a hard-capped plan that can be long enough to refuse a request that should have fit. Stripe takes a third road with its own API: a request that conflicts with one still executing under the same key is refused, and the caller retries it. For a metering endpoint that is the most honest answer on offer. Not yet, ask again. The other regret is about shape rather than order. Every route hand-rolls its own idempotency. Credits match on workspace and key; usage matches on workspace, quota slug and key. A credit replay echoes the amount you asked for, and a usage replay says `used: 0`. Each was a sensible local call. Together they are two contracts a customer has to learn, and a third for anything we add next. If we were starting again, one piece of middleware would own the key and claim it before anything moves, on every route. --- ## Metered vs seat-based billing: charge for people or for work > Seat-based billing charges per person with access; metered billing charges per unit of work. Pick by what grows when a customer gets more value. - Source: https://www.buildbase.app/blog/metered-vs-seat-based-billing - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Seat-based billing charges a fixed price per person with access; metered billing charges for units of work counted over the period. Pick by what grows when a customer gets more value: headcount or work. Seats make the bill predictable, meters make it track your costs. If both grow, sell seats plus a usage allowance. Seat-based billing charges a fixed price for each person with access. Metered billing charges for units of work, such as API calls or renders, counted during the period and billed after it. Most comparisons of the two end at "it depends". It does, but on one thing, and you can name it. When a customer gets more value from you next month, did they add a person, or did the same people do more work? Answer that honestly and you have your model. Answer it wrong and the pricing page looks fine for a year, then quietly stops tracking what customers get out of the product. ### The question that decides it Ask it about your best customers, not your average one. They are where the answer shows. If value arrives with people, charge seats. A teammate who needs to see the board or answer the ticket is the unit of value, and the customer already counts it. Their finance team has a headcount spreadsheet, and your price slots straight into it. If value arrives with work, meter it. Picture two accounts with two people each. One wires your API into a nightly batch job; the other logs in on Fridays. A seat price charges them the same, and one of them is getting a bargain you are paying for. Then check the answer against your costs. Cost to serve is the tiebreaker, not the question. If an extra unit of work costs you real money (inference, outbound email) and you priced by seat, your heaviest seat is your least profitable customer, and nothing on the invoice will tell you so. > **Key takeaway:** Bill by what grows when a customer gets more value. People: charge seats. > Work: meter it. Cost is the tiebreaker - when each unit of work costs you real > money, a flat seat price turns your heaviest users into your least profitable > ones. ### What each model does to the customer's bill A seat bill moves when somebody makes a decision. An admin invites a teammate and the count goes up; someone leaves and it goes down. The customer can predict next month's invoice by looking at their members screen, and seats are normally charged at the start of the period, so finance approves the number before it is spent. A metered bill moves when traffic moves. Nobody decided to make more API calls in March. Their own users did, or [a retry loop did](/blog/idempotency-in-billing), and the total lands after the fact as a sum of events the customer never watched accumulate. That is why a usage invoice needs a running number the customer can see during the month, which the [usage-based billing explainer](/blog/what-is-usage-based-billing) argues at length. So the trade, plainly: seats are predictable for the customer because they bill for a decision. Meters are accurate for you because they bill for an outcome. Neither model gets both for free. #### What counts as a seat "Per person" hides a definition you have to write down. Does a bot account count? What about a teammate who has been invited but has not clicked the link yet? We had to pick an answer for the billing module BuildBase ships. [A pending invitation bills a seat](/guides/team-invitations-nextjs) from the moment the email is sent until it is accepted, declined, revoked or expired, and invitations are valid for fourteen days. That choice has a cost: an invitation nobody answers keeps billing. So the server runs a sweep that marks invitations expired and releases their seats within ten minutes of expiry, instead of leaving them on the invoice until the next member change happens to recompute the count. The members screen counts pending invitations in its seat block and says so. A seat the customer cannot see on screen is a seat they will dispute. The [invitations reference](https://docs.buildbase.app/workspaces/invitations) has the full lifecycle. ### What each model does to your revenue Seats give you a floor. A customer with eight seats pays for eight seats in a quiet month, and next quarter is a forecast built from headcount and churn. The price of that floor is a ceiling: the account whose one seat runs your product all day pays the same as the one that logs in on Fridays. For one class of product the ceiling is dropping. An agent or a scheduled job does work without taking a seat. When a customer moves work from people to automation, their headcount stays flat or shrinks while their use of your product grows, and seat revenue falls at the exact moment the value you deliver rises. If your roadmap says "agents" anywhere, that is the pricing question to answer first. Meters give you expansion without a sales call: the customer who doubles their volume doubles their bill. They also give you the reverse, because a customer's slow month is now your slow month. And they [leak at seams](/guides/usage-does-not-match-invoice) seats do not have. The plan change is the seam we know best. A seat change is a quantity change, and Stripe prorates quantity changes by default. Metered usage is a running total, and a plan change has to carry it across. When we measured our own billing module against live Stripe, a plan change over 10,101 reported units produced an invoice with one line on it: the unused-time credit. The usage had been cleared along with the old plan's metered items, so every plan change was throwing away a period of overage on exactly the accounts most likely to have any. The fix, which [the proration guide](/guides/proration-on-plan-change-nextjs) walks through, converts reported usage into its own invoice line before the plan changes. That also makes it readable on the bill. Nobody has to write that fix for seats. That is the honest revenue comparison: meters capture more of the value, and they have more places to lose it. What it costs to build one that does not lose it is worked through in [the cost of building usage metering yourself](/blog/cost-of-building-usage-metering-yourself). ### Where hybrids fit: seats plus an allowance A hybrid is the answer when both things grow: people need a login to get any value, and the work each account does varies a lot from one to the next. Charge seats for access. Include a usage allowance big enough that a normal month never touches the meter. Meter only what goes past it. The rule that keeps a hybrid fair is that each line charges for something different. The seat pays for a person having access, the allowance covers what a typical team does, and the meter charges for the tail. If your seat price already assumes a person's usage and you meter that same usage from the first unit, you are charging twice for the same work. The first invoice with both lines on it is where the customer works that out. In practice it is three prices on one plan. A plan version in BuildBase's [billing module](/billing) carries a base price, a per-seat price for members beyond the seats it includes (with an optional cap on total seats), and an overage price per quota. Each quota either bills overage past its included amount or stops at it, and during a trial every quota stops. The allowance [belongs to the plan](/blog/what-are-entitlements) and is shared by the whole workspace. It does not grow with the seat count, so if bigger teams should get more included usage, that goes into the tiers. Hybrids go wrong on time. A seat changes on a date and is prorated. Usage accumulates and is billed at the end. An invoice that carries a mid-month seat proration next to an overage line is two clocks on one page, and it has to be readable as two clocks. The allowance has its own clock too: it resets every month, so whatever a customer did not use is gone. If unused volume should carry over, you want a balance rather than an allowance, and [quotas are not credits](/blog/quotas-are-not-credits) is about exactly that choice. ### When each one is the wrong choice **Seats are wrong** when usage per account varies widely at the same headcount, or when software does the work rather than people. Either way you price for the average and lose money on the tail. They are also wrong when the per-seat price is high enough that a team shares one login, at which point your unit of value is a password. **Meters are wrong** when the customer cannot see or control the unit, and when the buyer needs a fixed figure for a purchase order; the usage-based explainer covers both. They are also wrong when access is the value. A tool where the work is reading and commenting has no honest unit to count, and inventing one ("per comment") charges people for taking part. **Hybrids are wrong early.** Two lines on an invoice are two things to explain, and a product with a dozen customers does not have the usage data to set an allowance that a normal month never touches. Start with the one model the question picked. Add the second line once you can see the tail you would be pricing. ### Where we land ourselves BuildBase's own plans are mostly neither. They are flat tiers, from a Free plan at $0 to Scale at $99: team members are an included allowance on each plan rather than a per-seat charge. On the paid plans three quotas bill over - workflow runs, web analytics events and storage - and the rest stop at the allowance. Free stops at every allowance. Once you have picked, the build is the short part. [Charging per seat](/guides/charge-per-seat-nextjs) is mostly about the moment the seats run out, and [charging per API call](/guides/charge-per-api-call-nextjs) puts the meter and the cap in one call. --- ## What are entitlements in SaaS, and what a plan change does to each kind > In SaaS, an entitlement is what a customer's plan lets them do: a feature, a limit, a quota or a credit grant. The four look alike until the plan changes. - Source: https://www.buildbase.app/blog/what-are-entitlements - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short An entitlement is what a customer's plan lets them do, read from the plan version they bought at the moment they try. It takes four shapes: a feature that is on or off, a limit on how many things they hold, a quota they spend each period, and credits the plan deposits. A downgrade treats each one differently. An entitlement is what one customer is allowed to do in your product because of the plan they bought: whether a feature is on, how many of something they can hold, how much they can use this period. It is read from that customer's plan at the moment they try, not copied somewhere and kept in sync by hand. Most explainers give that definition and a list of types, and stop short of the day the plan changes. That is the day the kinds come apart. They do not all change at once, and a system that treats them as one thing ends up with a refund request or a customer who kept what they stopped paying for. ### Why entitlements exist A pricing page makes promises and code has to keep them. Without a name for that job, the promise becomes `if (plan === 'pro')` scattered through the codebase, and the first new plan quietly breaks every one of those checks. The plan's name is not what was sold. The list of things on it is. We learned the other half of this on our own console. BuildBase sells its plans through its own billing module: every console org is a workspace inside a BuildBase tenant, and its subscription is read through the same public endpoint a customer's app calls. The plan versions held features, limits and quotas. The console had a full editor for all three. And for a while, nothing read them - the code that fetched an org's subscription kept the status and dropped the plan version on the floor. An entitlement that no code reads is a line on a pricing page. ### The four kinds, and what "no" means for each Four shapes cover nearly every pricing page, and the useful way to tell them apart is what the customer can do about a refusal. **A feature** is on or off: `csv-export: true`. A "no" means the plan does not include it, and the only remedy is a different plan. **A limit** is a ceiling on how many of something the customer holds at once: [seats](/blog/metered-vs-seat-based-billing), projects, custom domains. It is held, not spent. Deleting one frees a slot, which is why our own refusal copy for a limit ends "Upgrade for more, or remove one." **A quota** is an allowance used up over a period that resets, like 10,000 API calls a month. Spent, not held. Deleting what you made does not give the call back, so our quota refusal never says "remove one" and says instead that the allowance renews with the billing cycle. **A credit grant** is the plan depositing credits, once or every period, into the same balance the customer buys credits into. Each action spends what it costs, and a "no" means the balance is short, which buying more fixes without a plan change. A grant either adds to what is there or swaps last period's plan credits for fresh ones. [Quotas are not credits](/blog/quotas-are-not-credits) covers why a balance and an allowance differ even when both renew monthly. All four on one published plan version, simplified: ```ts { features: { 'csv-export': true, 'custom-domain': true }, limits: { 'max-custom-domains': 3, 'max-projects': 5 }, quotas: { 'api-calls': { allowOverage: false, monthly: { included: 10000 } }, }, creditGrant: { enabled: true, creditPackage: '', mode: 'topup', // or 'reset': expire last period's credits, grant fresh renewOnPeriod: true, }, } ``` Notice that `custom-domain` and `max-custom-domains` arrive as a pair. Most capabilities need both. One says whether the thing exists at all; the other says how many. Our own registry pairs `custom-auth-domain`, which decides whether the Domains tab exists, with `max-auth-domains`, which decides whether you may add another. They fail in different places with different messages. Two entitlements, then, not one with a magic zero. Which brings up zero. A numeric entitlement has three values that are easy to collapse into two: none allowed, no ceiling, and not on this plan at all. Our registry writes unlimited as `-1`, never `0`, because `0` already means none and an absent key means the plan does not mention it. We do not fully agree with ourselves here, either. An older workspace setting, `maxWorkspacesPerUser`, stores `0` for unlimited on live orgs, and migrating it would flip every one of those orgs to "none allowed". So it stays, and the caller translates at that one boundary. Pick your spelling for unlimited before the first plan ships. What some explainers call a configuration entitlement, say 30 days of history on one plan and 90 on the next, is a limit with a unit. Zero days is not a short window. It is none. > **Key takeaway:** A feature is on or off. A limit caps how many things a customer holds at once, > and deleting one frees a slot. A quota is spent, then resets. Credits are a > balance the plan deposits into and each action spends from. Most capabilities > pair a feature with a limit. ### Where an entitlement lives On the plan version the customer is subscribed to, and nowhere else that can disagree with it. It gets read at the point of use. "The plan version" means the one the subscription is pinned to, not the newest one you sell, which is how [a price change leaves existing customers exactly where they are](/guides/plan-versioning-nextjs). "Nowhere else" is about ownership. In our registry, code owns the namespace: which slugs exist and what kind each one is. The database owns the assignment, meaning which plan grants which slug at what value. Moving a feature between tiers is then a console edit, not a deploy. And a typo in a slug is a compile error instead of a feature that silently never turns on. "Read at the point of use" means the check sits where the work happens. The button is a courtesy. The route is the boundary: ```ts // In the route that runs the export, not only the button that opens it const workspace = await bb.workspace.get(workspaceId); if (workspace.features['csv-export'] !== true) { return Response.json( { error: 'CSV export is not included in your plan' }, { status: 402 } ); } ``` 402 is payment required, because the fix is a purchase. The UI half wraps the button in a component keyed on the same slug and shows an upgrade prompt instead. [Enforcing quotas in React](/guides/enforcing-quotas-in-react) does that for quotas, and [the server-side version](/guides/quota-enforcement-server-side-nextjs) explains why, for a quota, the record call is the real check. So why read `workspace.features` and not the plan version on the subscription? Because of what happens on a downgrade. ### What a plan change does to each kind An upgrade is the easy direction. Once the payment for it is confirmed, the new plan's features and limits apply straight away. If the proration invoice is still open, say a declined card or a 3D Secure prompt, BuildBase waits for it to be paid before granting anything. A downgrade is where the kinds split. The customer paid for the current period on the higher plan, so the features and limits they already have run to the end of it. Quotas do not wait. The subscription moves to the lower plan at once and the smaller allowance applies immediately, while credits already in the account stay until they expire on their own and the lower plan's grant arrives at the next renewal. [The proration guide](/guides/proration-on-plan-change-nextjs) has the table of which clock moves when. That split is easy to get wrong, and our own code has got it wrong at least twice. During a deferred downgrade the subscription points at two plan versions: `planVersion` is the plan being moved to, which quotas read, and `featurePlanVersion` is the plan being left, which features and limits read until the period rolls over. Our own control plane built each org's entitlement from `planVersion`, so downgrades bit at once until the held plan was added. Separately, a race between the plan-change route and its own Stripe webhook made a downgrade read as an upgrade. The customer lost the plan they had paid for, on the spot. We found that one in production, and it only happened some of the time. The server's own feature resolution reads the held plan first, and so does the `features` map on a workspace. The SDK's subscription types, as of 0.0.82, do not declare `featurePlanVersion` at all. Read features off the subscription's plan version and you are reading the wrong plan for as long as a downgrade is pending. When a subscription stops entitling the workspace at all, the plan-managed features fall back to their defaults. Canceled, unpaid, a trial that ran out, a suspension at the end of dunning: each of those counts as no plan. Past due does not, because it is the grace window while Stripe retries the card. What you refuse after that matters as much as when. Our console gate is written for writes only, so a customer whose plan no longer includes a capability can still see and export what they made while it did. Holding someone's data hostage over a downgrade turns a lost upsell into a lost customer. ### The gate you add after customers exist Versioning handles most of this: a subscription stays pinned to the version it was sold, and entitlements resolve from that version. What it does not handle is adding a brand-new entitlement to plans that already have customers. Every published version predates the new slug, so none of them mention it. If absent reads as locked, shipping the gate takes the feature away from every existing customer the moment it deploys. Our console gate reads absent as unknown and lets the request through. Treating absent as locked is a separate switch, the last step of the rollout, for once every published version carries an explicit value. Separately, the gate itself has three positions: off, shadow (decide and log every would-be refusal, refuse nobody) and enforce. Unknown is a real answer, not a gap. A gate with only granted and locked forces "we have not found out yet" into "denied", which is how a customer sees a padlock over a feature they paid for while the page loads, or gets a 402 because your own billing lookup timed out. A false unknown costs one ungated feature. A false locked costs a paying customer a screen they bought. ### When an entitlement is the wrong tool Not everything with a number belongs on a plan. **Safety ceilings.** Rate limits and abuse prevention are not entitlements, and we do not sell them. Price a rate limit and someone will eventually sell a way past it, which gives you a reason to leave customers less safe. Keep those in configuration, the same for every plan. **What a new customer needs to see the product work.** Our first question for any gate is whether it would make a new customer leave before the product proves itself. If it would, it is free on every plan: gating it costs more in churn than it earns in upgrades. **A limit on something the customer cannot delete.** A limit is held, so the way out at the ceiling is to remove one. With no delete path the limit is a ratchet. Once at the cap, the customer is at it forever, and the only exit is an upgrade they did not choose. Ship the delete before the cap. **Anything engineering decides.** A beta, a percentage rollout, a kill switch. None of these are about what the customer paid for, and they belong in a flag. [Entitlements are not feature flags](/blog/entitlements-are-not-feature-flags) makes that case in full, including why the two look identical at the render site. ### What an entitlement is not It is not a permission. The plan decides whether the workspace can export at all, and [the member's role decides who may press the button](/blog/what-is-rbac). We made "role never skips the plan" a hard rule for our own console: owner and admin roles there bypass permission checks by design, and a plan gate that inherited the bypass would look closed and be open. It is not a Stripe feature list either, although Stripe Entitlements covers the on-or-off kind well. A Stripe feature has a name and a lookup key and no quantity, so limits, quotas and balances still need somewhere to live. In BuildBase, features, limits and quotas sit on the plan version in the [billing module](/billing), plan credit grants in [credits](/credits), and the [feature flags reference](https://docs.buildbase.app/feature-flags/overview) covers the components that gate UI on a plan-tied slug. The four kinds, and the way a downgrade pulls them apart, are the same whatever you build on. --- ## What is multi-tenancy, and why the tenant is whoever pays > Multi-tenancy is one app serving many customers with their data kept apart. The decision that costs you later is which object in your schema is the tenant. - Source: https://www.buildbase.app/blog/what-is-multi-tenancy - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short Multi-tenancy means one running copy of an application serves many customers, called tenants, and no tenant can see another tenant's data. The decision that outlives the database layout is which object is the tenant: the one that owns the rows, holds the subscription and is counted against the quota. Multi-tenancy means one running copy of an application serves many customers, called tenants, and no tenant can see another tenant's data. GitHub is the familiar example: every organization runs on the same service, and each one owns its own repositories. Most explanations then spend the rest of the page on database layouts. The layout matters. It is also the part you can change later. What you cannot cheaply change is which object in your schema is the tenant: the thing that owns the rows, holds the subscription and gets counted against the quota. Get that wrong and the fix is a migration across every table you own. ### Why it exists The alternative is one deployment per customer. That is single-tenancy, the classic installed-software model: each customer gets their own copy, their own database and their own upgrade schedule. Fifty customers means fifty upgrades, and fifty chances for one customer's copy to drift away from everyone else's. Multi-tenancy collapses that to one deployment. AWS's [SaaS Architecture Fundamentals](https://docs.aws.amazon.com/whitepapers/latest/saas-architecture-fundamentals/moving-to-a-unified-experience.html) whitepaper, which AWS now marks as historical reference, calls every tenant running the same version "one of the fundamental distinguishing attributes of a SaaS environment." The price is that isolation stops being a fact about your infrastructure and becomes a rule your code has to keep on every query. ### The tenant is whoever pays The tenant is the customer: the account that signs up, holds the card and owns the data. The [AWS SaaS Lens](https://docs.aws.amazon.com/wellarchitected/latest/saas-lens/tenant.html) puts it as "any customer that you sign up to use your SaaS environment is one of the tenants of your system." The whitepaper quoted above adds the sentence that causes all the trouble: a tenant "could be a company with many users, or it could correlate directly to an individual user." At signup those two look identical. One person arrives, enters a card, creates some data. Nothing distinguishes "this user is the customer" from "this user is the first member of a customer." So the plan column goes on the `users` table, every row gets a `user_id`, and it all works until a second person from the same company signs up and asks to see the first one's work. So ask who pays. In a consumer product the payer is a person, and the person can be the tenant. In a B2B product the payer is a company. The people are members who join, change roles and leave while the company goes on paying, which makes the tenant a separate object - an organization, a team, an account, a workspace, whatever your product calls it - with users attached to it through a membership. ### How it works: three things, one owner A multi-tenant schema has one tenant table, and three things point at it: the data, the subscription and the usage counters. A membership table connects users to tenants. Every request works out which tenant it is acting for, checks that the user is a member of it, and [filters every query on that tenant's ID](/guides/per-org-data-isolation-nextjs). ```sql tenants (id, name, stripe_customer_id) users (id, email) memberships (tenant_id, user_id, role) subscriptions (id, tenant_id, plan, status) projects (id, tenant_id, created_by, name) usage (tenant_id, metric, period, count) ``` Look at what is missing. There is no plan on `users`, and `projects` records who created a row without that person owning it. Anything the customer paid for reaches a user only through `memberships`. The tenant ID can arrive in the URL, but nothing trusts it until the server has checked membership - in an Express API that is [one middleware that refuses non-members](/guides/multi-tenant-workspaces-express) before any handler runs. The failures worth knowing about come from pointing the three at different objects. Each one looks fine in a demo. **Rows on the user, plan on the team.** A member leaves. Their projects leave with them, or sit orphaned, while the team keeps paying for a plan that no longer shows its own work. **Plan on the user, rows on the team.** The person who entered the card leaves. The team's data now hangs off a subscription nobody left in the team can manage, and closing that one account cancels it for everyone. **Quota on the user, plan on the team.** A plan that includes 10,000 API calls a month quietly becomes 10,000 per member. Inviting a viewer is a free upgrade. > **Key takeaway:** Multi-tenancy is one deployment serving many customers with their data kept > apart. The decision that outlives the database layout is which object is the > tenant. Make it whoever pays, then point the data, the subscription and the > quota at that same object. Once users are members rather than owners, one person can belong to several tenants, and in B2B sooner or later somebody does: the agency, the founder with two companies. [GitHub's docs](https://docs.github.com/en/get-started/learning-about-github/types-of-github-accounts) say it flatly - "each user can be a member of multiple organizations." That turns "[which tenant am I in right now](/guides/stale-data-after-workspace-switch)" into state the server resolves on every request. GitHub also shows the other honest answer to "who is the tenant", which is both. A personal account and an organization can each own repositories, each with its own plan. It works, and it means every question about who owns a repository has two possible answers. Choose that on purpose or not at all. ### When it is the wrong choice Multi-tenancy is the wrong call in two separate situations: when a customer's contract rules out sharing, and when the tenant would be one person who stays one person. **A shared deployment is wrong when the contract says so.** Some customers require that their data sits on infrastructure no other customer touches, or inside their own network. For them you are in single-tenant territory whatever the rest of your customers get. Self-hosted BuildBase is that shape: the tenant server runs on the customer's own infrastructure, and per our docs the central server never sees their application data. **A team-shaped tenant is wrong when the payer is a person and will stay one.** A journaling app, a personal budget tracker. There the membership table is a join nobody needs, and a workspace switcher would have one entry forever. Let the user be the tenant and move on. The catch is "will stay one." If two people could plausibly end up on one bill - a couple sharing a budget, a freelancer who hires an assistant - build the tenant object now. Adding it later means rewriting every table where `user_id` quietly means "owner", and that is a migration rather than a feature. ### Where we drew the line In BuildBase the tenant object is called a workspace, and the decision is already made: the workspace owns the bill. The workspace record carries the Stripe customer ID, the reference to its subscription, its quota usage, its feature flags and its credit balance. [Members join it with a role](/guides/roles-and-permissions-per-workspace-nextjs) (admin, editor and viewer are built in). Every subscription, usage and credit call in the server SDK that acts on an account takes a workspace ID first, never a user ID: ```typescript const { subscription, plan } = await bb.subscription.get(workspaceId); await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1 }); await bb.credits.consume(workspaceId, { amount: 50 }); ``` A new user [gets a workspace on first sign-in](/guides/auto-created-first-workspace-nextjs) by default, so someone signing up alone is a team of one rather than a user with a plan column. The first teammate they invite joins a tenant that already had the right shape. Whether that first workspace is created automatically is configurable. Two of the products we run on it are built around this. AgentCenter is built on multi-project workspaces with role-based permissions and tiered subscriptions; PlugNode on team workspaces with usage-based credit metering. One rule in that model is "a workspace has at most one live subscription." The application refuses a second checkout, and a unique index in the database is meant to back that refusal up, because two live subscriptions on one workspace is one customer charged twice. For a while the backstop did not exist. It shared a default name with a plain index on the same field, the database refused the second one, and the code that builds indexes logged the refusal and carried on. Until the index got a name of its own, the application check was the only thing in the way, and a name only makes it buildable: the index still has to be built on every tenant database. The lesson is not that indexes are fiddly. A rule about who owns a bill deserves a database constraint, and somebody has to go and check the constraint exists. Our own customers sit one level up. Each org building on BuildBase gets its own database, and the workspaces inside it share that org's schema. Per-tenant at the level where each tenant is a company building a product; shared at the level where tenants are many and self-serve. ### What multi-tenancy is not It is not a database layout. Shared tables, a schema per tenant and a database per tenant are three ways to isolate tenants once you know what a tenant is, and the choice between them turns mostly on how many times you are willing to run each migration. [Database-per-tenant vs shared schema](/blog/database-per-tenant-vs-shared-schema) argues that fork, and [what database-per-tenant actually costs](/blog/database-per-tenant-cost) prices the per-tenant end of it. It is not access control either. [Roles decide what a member may do inside a tenant](/blog/what-is-rbac). Tenancy decides which tenant's data a request can reach at all, and an admin role that is not scoped to a tenant is an admin of every customer you have. And the quota hanging off the tenant is not the same thing as a credit balance, even though both belong to it. One resets with the subscription; the other is a balance the customer already paid for. [Quotas are not credits](/blog/quotas-are-not-credits) sorts out which one a plan needs. The working-code version of all this, with the workspace as the tenant from the first commit, is [multi-tenant workspaces in an afternoon](/guides/multi-tenant-workspaces-in-an-afternoon). The API surface is in the [workspaces docs](https://docs.buildbase.app/workspaces/overview). --- ## What is RBAC, and where it leaks in a B2B SaaS app > RBAC grants permissions to roles and roles to people. In a B2B app the role sits on the workspace membership, and the leaks are in the defaults, not the matrix. - Source: https://www.buildbase.app/blog/what-is-rbac - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short RBAC, role-based access control, decides what someone may do by the role they hold rather than who they are: permissions attach to roles, and people are given roles. In a B2B SaaS app the role belongs to the workspace membership, so one person can be an admin in one workspace and a viewer in the next. RBAC, role-based access control, decides what a person may do by the role they hold instead of by who they are. Permissions attach to roles, people are given roles, and every check asks one question: does this person's role grant this action? That is the textbook answer and it is correct. It was also written for a company deciding what its own employees can open. A B2B SaaS app is shaped differently. The person asking is [a member of a customer's workspace](/blog/what-is-multi-tenancy), often of more than one, and the bugs that matter are rarely in the role table. ### Why roles exist Without roles you grant permissions to people one at a time. Fine for five people. Then someone changes jobs and you have to remember which switches they had. A role is an indirection: edit it once, and everyone holding it changes with it. In a SaaS product there is a second reason, and it is the bigger one. Your customer's admin has to decide who on their team may [invite people](/guides/team-invitations-nextjs) or touch billing, without filing a ticket with you. RBAC is how you hand them that decision. You ship the permissions and the default roles; who holds which role is their call, made on a settings screen you will probably never look at. ### How it works when there are tenants Three pieces. **Permissions** are the actions your API enforces, like inviting a member or managing billing. **Roles** are named bundles of permissions. **Assignments** say which role a person holds. The assignment is where multi-tenant RBAC parts ways with every textbook diagram you have seen, because it does not sit on the user. It sits on the membership, the row that says this person belongs to this workspace. In BuildBase that row lives in the `workspaces_users` collection and carries the workspace, the user and the role. Same person, two rows, two roles: admin in the workspace they made, viewer in the client workspace someone invited them to. Switch workspace and the answer to every check changes with it. > **Key takeaway:** Never ask "is this user an admin?" Ask "is this user an admin in this > workspace?" The role is a property of the membership, so a check with no > workspace in it is checking the wrong thing. Here is what ships by default. Every org starts with three workspace roles and a matrix of 12 platform permissions: | Role | Holds | In practice | | -------- | ------ | ------------------------------------------------------------------------ | | `admin` | all 12 | Settings, members, billing, usage. Everything but deleting the workspace | | `editor` | 6 | Views settings, members, features, billing and usage, and records usage | | `viewer` | 2 | Views settings and members | There is no owner role. Whoever creates a workspace is made its admin, passes every permission check as its creator, and is the only one who can delete it. That is worth copying. Ownership is a fact about who created something, not a bundle of permissions. Make it a role and an admin can hand it to someone else, or take it away from the person who set the workspace up. You can add to it from the console: roles of your own, and permissions of your own next to ours (`app:reports:export` is the shape we suggest). A new custom role starts with editor's permissions until someone sets it. And each workspace can loosen or tighten the matrix for itself, so it resolves in layers: the workspace's override, then your org-wide matrix, then the built-in defaults. For each role, the first layer that mentions it decides. There is a second tier above all this. An org role (`owner`, `admin`, `user`, or one the customer defines) says who someone is across your whole app, and a workspace role says what they may do inside one team. They even run on different clocks. The org role is copied onto the session and [re-read hourly](/blog/why-permissions-refresh-hourly), but changing it through the console, or blocking the user, deletes their sessions on the spot, so the new role applies at their next sign-in. The hour only catches role writes that skip that route. A guarded workspace route reads the membership row every time it is called. ### Where the check runs On the server. [Hiding a button is a courtesy, not access control](/guides/roles-and-permissions-per-workspace-nextjs). ```tsx import { Permission, usePermissions } from '@buildbase/sdk/react'; function MembersHeader() { const { can } = usePermissions(); return can(Permission.WORKSPACE_MEMBERS_INVITE) ? : null; } ``` That decides what to render, and it earns its place: a viewer should not be shown a button that is going to fail. What actually stops a viewer from inviting someone is the API answering 403, including when they call it with curl and never load your UI. The quieter failure is the client and the server disagreeing about what a role means. We had it. `editor` had no entry in the default permission map, so the server reached a fallback list while the SDK, which had no fallback, denied editors everything. Editors were using an app that refused them things the API would have let them do. From the outside a bug like that never looks like RBAC. It looks like a broken product. The missing entry is there now, but the fix that matters is structural. One shared function works out what a role holds, and the server enforces with it and hands the SDK its result, so the screen and the API cannot disagree. Your own backend can ask the same question rather than re-implementing the rules: `GET /api/v1/public/workspaces/:workspaceId/permissions/me` returns the caller's role and the permissions the server resolved for them. ### Where RBAC actually leaks Everyone reviews the matrix. The leaks are in two places nobody draws a column for. **The role someone gets when nobody chose one.** An invitation whose role was deleted before it was accepted. A role name the SDK does not recognise. Something fills that gap, and whatever fills it is the most-assigned role in your system without anyone deciding so. Ours was `admin` for new orgs, which meant anyone who joined a workspace that way could change its settings, remove its members and manage its billing. The default is `viewer` now, and `admin` cannot be the default at all. An org can pick a different default role, but if it picks admin, the platform reads it as viewer. Admin is only ever given on purpose. **The route that checks membership and nothing else.** "Is this person in the workspace?" feels like a permission check. It isn't one. Our usage routes, the ones that add to a workspace's metered usage and spend its credits, carried a rate limiter and a membership check, and nothing more. So a viewer could not see the workspace's usage but could add to it. And spend its credits. The fix was a permission that did not exist, `workspace:usage:record`. Editors hold it and viewers do not. It is deliberately separate from `workspace:billing:manage`, because an ordinary member of your customer's team needs to use what the workspace pays for and must not be able to change the subscription. Which is the general lesson. A matrix can be perfect and still protect nothing on a route that never consults it. Every new endpoint needs a named permission, and "they're a member" does not count as one. ### When RBAC is the wrong model RBAC answers "what can someone in this position do". It is the wrong tool when the honest answer depends on something other than position. **When access follows the object.** "Share this one document with this contractor" is not a role. Neither is "everyone on the project sees the project's files". That is relationship-based access, ReBAC, or a plain access list per object, and forcing it into roles gets you a role per document. This is the case where ReBAC wins outright. **When access depends on attributes.** "Reps can edit deals in their own region." "Nobody exports outside business hours." These read properties of the person, the record or the request, which is attribute-based access, ABAC. You can fake them with roles: Editor EMEA, Editor US, Editor APAC, and next quarter Editor LATAM. That is the role explosion every explainer warns about, and the cause is always the same. A role is being asked to carry data. **When there is no team yet.** If every workspace in your product holds exactly one person, a role system is ceremony. What you need first is [the workspace, not the user, owning the data](/guides/multi-tenant-workspaces-in-an-afternoon), so roles have somewhere to attach when the second person shows up. Our own position, plainly: BuildBase's permissions are RBAC, at the org level and the workspace level, with custom roles and custom permissions. We do not do ReBAC, ABAC or policy-as-code. If your product's core is per-document sharing, you need something else for that part, and roles for the rest. ### Roles are not entitlements A role answers "may this person do this". [An entitlement](/blog/what-are-entitlements) answers "did this workspace pay for it". Different owners, too: your customer's admin assigns roles, and your pricing page decides entitlements. So a viewer on your top plan still cannot manage billing, and an admin on your free plan still cannot use a feature the plan does not include. Both checks run and neither stands in for the other. The plan side of that split, and why it should never be a flag, is [entitlements are not feature flags](/blog/entitlements-are-not-feature-flags). If you are building this on BuildBase, the [permissions module](/permissions) is where it lives, and it is what PlugNode and AgentCenter, two of our own products, use for their roles. The [reference](https://docs.buildbase.app/permissions/overview) has the components. The two leaks above are the same whatever you build on. --- ## Why a permission change no longer waits for the hourly refresh > RBAC permission propagation delay, from our code: role and grant changes land at the write, and the hourly refresh only catches writes that announce nothing. - Source: https://www.buildbase.app/blog/why-permissions-refresh-hourly - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-10-12 ### In short BuildBase re-reads the user behind each session hourly, but no change an admin makes in the console or SDK waits for it. A role change revokes sessions and stamps the console token, a grant edit busts every instance's cache, and workspace roles are read per request. The hour backs up writes that announce nothing. `SESSION_DEFAULTS.permissionRefresh` in `packages/shared/src/constants/platform-stats.ts` reads `hourly`, and our docs repeat it as "permission sync". That is accurate about one loop in one file. It is not how a permission change reaches the check that enforces it. Not any more. We stopped asking a clock to propagate permissions. A role change, a block or a grant edit that an admin makes through the console, or its API with an API token, now fires at the moment it is written: it deletes sessions, stamps the user's credentials, or busts a cache on every server instance. A workspace role changed through the SDK needs no push at all, because [it is read per request](/guides/roles-and-permissions-per-workspace-nextjs). The hourly refresh survived because it was left a smaller job. It catches the writes that do not fire anything, and for that job an hour sits at the cheap end of a real trade. ### The hour used to be the mechanism When we audited [org-level RBAC](/blog/what-is-rbac) in August, the remediation plan described the role gap in one line: "a demotion is effective only at the next hourly refresh". That was the good case. The console's tenant token carries the role as a JWT claim, and at the time it was verified by signature alone, with nothing behind it to re-read. The comment on `server/src/services/auth/credential-version.service.ts` records what that meant: demoting an admin "left their existing token fully privileged until it expired". `DEFAULT_TOKEN_EXPIRY` in `packages/server-core` is `'7d'`. Seven days, for a demotion. Grants had their own version. The `authenticate` middleware keeps a per-process `Map` of each role's grants with a 60-second TTL, in front of a Redis entry that lives for 300 seconds. Saving a role deleted the Redis entry and left every `Map` alone, so a removed permission kept working for up to a minute on every instance, including the one that removed it. An hour, seven days or a minute, depending on which credential you held and which half of the permission you changed. From the admin's chair all of them looked the same: I changed it and nothing happened. ### The fix we did not take: a smaller number The obvious fix is to shrink the clocks. The plan considered it in both places. For the grant `Map` it wrote down a minimum viable option, "drop `AC_MEMORY_TTL` to a few seconds". For roles it wrote the opposite instruction: "prefer explicit revocation over lowering `SESSION_REFRESH_INTERVAL`". We took the second shape for both. Why? Because a TTL is a tax on every session whether or not anything changed, and it never reaches zero. Here is what the refresh does when it fires, from `SessionService.getSession` in `server/src/services/auth/session.service.ts`, trimmed: ```ts const lastRefreshed = session.userRefreshedAt ?? session.createdAt; if (Date.now() - lastRefreshed > SESSION_REFRESH_INTERVAL) { const freshUser = await UsersController.getInstance().findById( session.orgId, session.userId ); if (!freshUser || freshUser.blocked) { await deleteAuthSession(sessionId); return null; } session.user = { role: freshUser.role, emailVerified: freshUser.emailVerified, }; session.userRefreshedAt = Date.now(); const remainingTtl = await AuthRedis.getSessionTTL(sessionId); await setAuthSession( sessionId, session, remainingTtl > 0 ? remainingTtl : SESSION_TTL ); if (session.deviceId) { AuthSessionsController.getInstance().touch(session.orgId, sessionId); } void recordActiveUser(session.orgId, session.userId); } ``` `SESSION_REFRESH_INTERVAL` is `60 * 60 * 1000`. When it lapses, that is a read of the user row from the org's own database (every org has its own, which is the [database-per-tenant](/blog/database-per-tenant-vs-shared-schema) model), a TTL lookup and a rewrite of the session blob in Redis, a write to the session mirror for a device-bound session, and a mark in the monthly-active-users set. At an hour, a busy session pays that once an hour. At a minute it can pay it 60 times, and so does every other busy session in every org, whether or not anyone there changed a role today. And a minute is still not instant. It is a minute of a demoted admin doing admin things. A revoke at the write closes the gap to the next request, and it is paid once per change rather than once per session per interval. That asymmetry is the whole decision. ### Fire at the write instead This only works because an SDK session has something behind it to delete. A BuildBase session is a random 35-character ID that points at a blob in Redis. Delete the blob and the next request carrying that ID gets a 401. There is no expiry to wait out. So the console's change-role route, the block route and a password reset all call `SessionService.revokeUserSessions`, which reads the user's session index and deletes every session in it. The console token was the harder case, because a signed JWT has no record to delete. It got a credentials epoch instead. Every authority change stamps `credentialsChangedAt` on the user, the token carries the epoch it was minted with, and the console gate compares the two on every request: ```ts // server/src/services/auth/credential-version.service.ts export async function isTokenStale( orgId: string, userId: string, tokenEpoch?: number ): Promise { if (!orgId || !userId) return false; const current = await getChangedAt(orgId, userId); if (!current) return false; return (tokenEpoch ?? 0) !== current; } ``` That is a lookup per request, which is what we refused to do for the role, so why is it fine here? Because the thing it reads only changes when somebody's authority does. The epoch sits in Redis with a 300-second TTL, and `markCredentialsChanged` writes the new value straight into Redis rather than waiting for that to lapse. A stale token gets a 401 with the code `CREDENTIALS_CHANGED`, and the console re-runs the org switch to get a token that carries the new role. Grants got the same treatment one layer down. `publishPermissionChange` invalidates the writing process's own `Map` directly, and announces the change on a channel named `rbac:permissions:invalidate` for every other instance. If a message is lost, the 60-second TTL is the backstop. Same design, smaller numbers. Here is where each change lands now: | Change | Reaches enforcement | How | | ----------------------------------------------- | --------------------------------- | ----------------------------------------------------- | | Org role, through the change-role route | Next request, after a new session | `revokeUserSessions` and `markCredentialsChanged` | | User blocked | Next request | The same two calls | | A role's grants edited | One pub/sub message | Redis entry deleted, `Map` busted on every instance | | Workspace role changed or removed | Next request | Read from the membership rows per request, no cache | | API token deactivated or deleted | Next request | Its 5-minute cache entry is evicted on the write | | Org role, seen by a key with no role of its own | Within 5 minutes | The key's cache entry is not evicted by a role change | | User blocked by a script or a hand edit | Within the hour, on SDK sessions | The hourly refresh | Workspace roles were never on the hourly clock at all. The workspace guard on the SDK routes reads the member's role from the `workspaces_users` rows on every guarded request, with nothing in front of it. It is the same call the [membership middleware guide](/guides/multi-tenant-workspaces-express) makes for your own server, and for the same reason: a cache there turns its TTL into the time a removed member keeps access. ### What the hour still does Four jobs, and only one of them still decides who may do what. **It ends sessions a revoke missed.** A script, a migration or a hand edit in a database shell can block a user without going through the route that revokes. The next refresh past the hour reads the row, finds `blocked`, deletes the session and returns null. That is the security job, and it is a backstop: the routes the product drives never leave it anything to do. What the client sees when that happens is covered from the other side in [token expired mid-request](/guides/token-expired-mid-request). **It counts monthly active users.** `recordActiveUser` rides the refresh. A sign-in counts as well, because, as the comment in `createSession` puts it, "waiting an hour to count somebody who just logged in would undercount every short visit". The count is a set of user IDs per org per month, so a faster refresh would not change the number. It would only mark the same person more often. **It keeps "last active" accurate to about an hour.** The `touch` on the session mirror is throttled to the refresh on purpose. The session list's last-active time is read from that mirror, so it moves about once an hour, and this is why. **It refreshes a role copy that the SDK routes do not read.** This is the part the docs call permission sync, and it matters least today. The session gate in `server/src/routes/v1/public/index.ts` copies `session.user.role` into `req.tokenData.role`. Then nothing reads it. Not one route or middleware under `/api/v1/public` touches that field: the SDK routes authorize on workspace membership and workspace permission, read per request. The org-level grant check, `authenticate`, guards the console routes. Those are reached with a console token or an API token, never with a session ID. There is one more hour in the code, and it is the one an SDK user is most likely to see, because it sits in front of the profile. The profile the SDK fetches carries the org role that `WhenRoles` checks. The server caches it in Redis for 3,600 seconds. Every write through `UsersController.updateById` deletes the entry, so a role changed through the console shows up on the next profile fetch. A hand edit gets no such help: the old role can sit in that cache for up to an hour. ### What I would change **The role copy, and the word "sync".** We carry a role in every SDK session, refresh it hourly, and authorize nothing from it. Either a guard should read it or the session should stop carrying it. Meanwhile the constant is named `permissionRefresh` and the [sessions doc](https://docs.buildbase.app/authentication/sessions-and-tokens) tells people role changes "update automatically" on that schedule, which sends anyone debugging a permission to the one clock that is not involved. The honest name for what is left is a session refresh. **Promotions sign people out.** The change-role route revokes on every change, up or down. Promote someone to `admin` and every session they hold, on every device, is deleted, and any console token they carry is refused until the console mints a new one. Revoking is the right default for a demotion. For a promotion it is a cost with no security return, since the stale copy is the smaller role. The backstop is also not the same length everywhere, and both gaps have the same cause: a write that does not announce itself. A hand edit to `users.role` never stamps the credentials epoch, so a console token keeps the old role claim until the next org switch mints a new one or its seven days run out. And blocking a person does not evict their API tokens' cache entries, so a key whose creator was just blocked keeps working for up to five minutes, until the cached entry lapses and the next lookup sees the block. If you script role changes on a self-hosted deployment, call the route, not the collection. The route is the part that tells everything else. --- ## What is usage-based billing, and what it does to your invoices > Usage-based billing charges for what a customer consumed rather than for access. The definition is easy. Defending the number on the invoice is the actual product. - Source: https://www.buildbase.app/blog/what-is-usage-based-billing - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-09-21 - Updated: 2026-10-22 ### In short Usage-based billing charges a customer for what they consumed in a period rather than a flat fee for access: API calls, tokens, renders, gigabytes. It moves the hard problem from pricing to counting, because every line on the invoice is a claim about something that already happened. Usage-based billing charges a customer for what they consumed in a period rather than a flat fee for having access. The unit is whatever you can count: API calls, tokens, renders, gigabytes held overnight. That definition takes ten seconds and it is where most explanations of this stop. The interesting part is what the model does to the rest of your company, because an invoice that varies is an invoice a customer reads. Nobody audits a $99 line that has been $99 for a year. Everybody audits the month it says $412. ### Why the model exists at all Flat pricing asks every customer to pay the average. That works while your customers look alike and stops working the moment one of them is thirty times heavier than another, which is the normal shape of an API product and the guaranteed shape of anything doing inference. So the model exists to solve a fairness problem and a margin problem at once. The heavy customer pays for being heavy, the light one is not quietly subsidising them, and your cost of goods tracks your revenue instead of diverging from it. That is the whole pitch, and it is a good one. What the pitch leaves out is that you have just made your revenue a function of something you have to measure correctly, in production, on the first try. ### How it actually works Three pieces, and only the first is interesting. **Recording.** Something happens, and you write it down against the customer and a unit. This has to be the same call that does the work: ```typescript const usage = await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1, idempotencyKey: req.headers.get('x-request-id') ?? undefined, }); ``` Two details in there carry most of the weight. Recording and checking are one round trip, so there is no window where fifty concurrent requests each read "plenty left" before any of them is counted. On a hard-capped plan `record()` itself rejects at the cap, so there is no guard to write after it; [server-side quota enforcement](/guides/quota-enforcement-server-side-nextjs) covers what to do with the return value. And the idempotency key means a retry does not bill twice, which stops being optional the first time you put a queue in front of this. **Aggregating.** Sum the records for the period. Easy, until someone asks what happens to an event recorded at 23:59:58 on the last day, and you discover your period boundary and your customer's timezone disagree. **Invoicing.** Turn the sum into money. Also easy, and also where the arguments land, because this is the first time the customer sees any of it. ### The part the generic explainers skip An invoice under this model is a claim about the past. You are telling a customer that 41,200 things happened last month and that they owe you for them. They cannot check it. They have to take your word, or take their own logs and find that the two do not match, which they will not, because your logs and their logs were never counting the same thing. So the real requirement is not accurate metering. It is _defensible_ metering, which is a stronger property with three parts: - **Attributable.** Every recorded unit traces to a request the customer can recognise. A count with no drill-down is an assertion. - **Idempotent.** [A retried or replayed event does not double](/blog/idempotency-in-billing). Without this, your own reliability engineering inflates the bill. - **Visible before the invoice.** The customer sees the running number during the period, not after it. A surprise at the end of the month is a dispute even when the number is correct. Miss the third one and you will be arguing about the first two in an email thread with someone who has already decided you are wrong. > **Key takeaway:** Usage-based billing moves the hard problem from pricing to counting. The > invoice is a claim about events that already happened, so the system's real > job is to make that claim attributable, idempotent, and visible before it > becomes a bill. ### Picking the unit The unit is the decision that outlives everything else, because changing it later means re-pricing every customer. A good unit has three properties. The customer can predict it before acting - "per image" passes, "per compute-second" mostly does not. It survives your own architecture changing, which is why "per API call" ages better than "per database query". And the cost to you moves with it, otherwise you have built variable pricing on a fixed cost and rediscovered flat pricing with extra steps. Then there is the question everyone defers: does a failed request bill? There is no correct answer. There is only the version you wrote down before launch and the version you decided during a support ticket, and the first is much cheaper. ### When it is the wrong choice Usage pricing is a bad fit when the buyer needs a number for a purchase order. A procurement process cannot approve "roughly $600 a month, probably". Some of the largest deals you will ever sign require a fixed figure, and a pure usage model either loses them or forces you to invent a committed-spend tier. It is also wrong when the customer cannot control their own usage. Charging by seats is [charging for a decision your customer makes](/blog/metered-vs-seat-based-billing). Charging by webhook deliveries is charging for a decision _their_ traffic makes, and a customer who gets a bill they could not have prevented does not conclude that the pricing is fair. And it is wrong early. A product with eleven customers does not have a usage distribution, it has eleven anecdotes. Flat pricing for the first year is not a failure of nerve, it is declining to optimise something you cannot see yet. We price ourselves accordingly, and it is worth saying out loud since we sell the metering: BuildBase plans are mostly flat. Free is $0 with 10,000 MAU and stops at its allowance, Launch is $19 a month with 25,000 MAU included, Grow is $49, Scale is $99. On the paid plans three lines meter past the allowance, the ones whose cost to us follows use: workflow runs ($0.25, $0.15 or $0.10 per 1,000 on Launch, Grow and Scale), web analytics events ($2 per 100,000) and storage ($0.10 per GB-month). Everything else is a hard allowance that stops rather than bills over. The plan itself is a flat price because the unit a customer buys it for is not obvious, and pretending otherwise would make our own pricing page worse. ### What it is not Usage-based billing is not the same as a quota, and it is not the same as credits, although it is usually implemented with one or both. A quota is an allowance that resets; a credit is a balance that carries. Which you need is a separate decision with its own consequences, laid out in [quotas are not credits](/blog/quotas-are-not-credits). It is also not [entitlements](/blog/what-are-entitlements). Whether a workspace may call an endpoint at all is a different question from how many times it did, even though both end up as a condition around the same component in the UI - see [entitlements are not feature flags](/blog/entitlements-are-not-feature-flags). If you are weighing the model against building the meter yourself, [the cost of building usage metering yourself](/blog/cost-of-building-usage-metering-yourself) runs that arithmetic. And the route handler that puts all of this into one Next.js endpoint is [charging per API call](/guides/charge-per-api-call-nextjs). --- ## Buy vs build for SaaS infrastructure > Buy-vs-build calculators price one module at a time. The real decision compounds across every module a SaaS needs, and the tipping point is not where most posts put it. - Source: https://www.buildbase.app/blog/buy-vs-build-saas-infrastructure - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-09-03 - Updated: 2026-09-22 ### In short Building auth and usage metering yourself runs about $162,000 in year one for one engineer, using this site's own published figures for each. A managed platform covering both is $190 a year. That gap comes from needing both modules at once, which single-module calculators never price. Every buy-vs-build framework asks the question one module at a time. Should you build auth, or buy it? Should you build billing, or buy it? Priced separately, both questions come out close enough to argue about, which is exactly why the posts answering them read like a coin flip. Priced together, for one team building both in the same year, they stop being close. Here is the arithmetic, using this site's own published, line-item figures for two modules rather than a new estimate invented for this post. ### The question What does it cost one team to build and maintain the infrastructure a normal B2B SaaS needs in its first year, against paying for a platform that already has it? ### The assumptions Nothing new here. These are the same inputs [the auth-cost post](/blog/cost-of-building-auth-yourself) and [the metering-cost post](/blog/cost-of-building-usage-metering-yourself) already derived and showed their work on - reused, not re-invented, so the totals below stay traceable to arithmetic you can go re-check. - **One senior engineer**, loaded at **$150 an hour**, building both modules in sequence rather than two engineers building them in parallel. - **Auth scope**: email/password signup, sessions, password reset, one OAuth provider. No SSO, no MFA. - **Metering scope**: idempotent event ingestion with correction and backfill tooling, not a single incrementing counter. - **Maintenance held at 20% of build cost every year**, the same benchmark both source posts use, for patching, provider API changes and the correction bugs each domain produces on its own schedule. - **Mid-scenario build times from each source post**: 4.5 weeks for auth, 4.5 months for metering. - Buy-side price is BuildBase's own Launch plan, verified against the platform constants on 31 October 2026. ### The arithmetic | Module | DIY build (mid) | DIY maintenance, yr 1 | Year-one total | | -------------- | --------------- | --------------------- | -------------- | | Auth | $27,000 | $5,400 | $32,400 | | Usage metering | $108,000 | $21,600 | $129,600 | | **Combined** | **$135,000** | **$27,000** | **$162,000** | $162,000 to build and maintain two modules, for one year, with one engineer. BuildBase's Launch plan, which covers auth and metering alongside billing and workspaces rather than either alone, is $190 a year paid annually. That is not a fair one-line comparison and it is not meant to be read as one. $190 buys more scope than the $162,000 does - it also buys billing and workspaces, which the DIY total above does not include at all. Even granting that gap generously, doubling or tripling the managed price to account for it does not get anywhere near six figures. ### The total, and what actually moves it The $162,000 headline is not the interesting number. The interesting number is that it is not $32,400 plus $129,600 read as two separate, comparable decisions - it is one number, because one team has to carry both maintenance lines going forward, every year, on top of whatever they build next. That's the part single-module calculators miss structurally, not by oversight. A post that prices auth alone is honest about auth and silent about the four or five other things the same SaaS still needs - billing, workspaces, notifications, feature flags. Each one adds a full year-one build plus a recurring maintenance tax, and those maintenance hours don't average out across modules. They stack, on the same one or two engineers, who also have a product to ship. > **Key takeaway:** Auth alone or metering alone can honestly go either way. Needing both at once, > on the same team, is what turns a marginal call into a $162,000 question - and > every module past the second one moves the answer further in the same > direction. That's also a different failure mode than the one [the vendor-stack post](/blog/auth-billing-stack-cost) covers. Buying four best-of-breed vendors instead of building avoids the $162,000, but it swaps the build-hours tax for an integration tax - four webhook formats, four auth models, four places a number can drift - that a subscription total never shows either. Building, assembling, and buying one platform are three different trades, not two. ### Where this math stops applying **You only need one module, not several.** Building auth alone at $21,600-$43,200 is a defensible call for plenty of teams, [as the source post argues](/blog/cost-of-building-auth-yourself). The case for buying gets stronger with each module added to the same build, not because any one of them got more expensive, but because the team carrying the maintenance did not grow to match. **Infrastructure is your actual product.** A billing or auth company is pricing this in reverse - none of it is overhead, it's the thing being sold. **Your engineer's rate sits well below $150 an hour.** The gap compresses at a junior or offshore rate, though not by enough to flip a two-module build: even at $50 an hour, $162,000 becomes $54,000, still two orders of magnitude past $190. **You already have idle ops capacity.** [Self-hosting the same modules](/blog/self-host-vs-managed-cost) trades the license line for compute, a managed database and patch time, which is a different axis from this post entirely - it's managed-versus-self-hosted, not build-versus-buy, since self-hosting still means running BuildBase's modules rather than writing your own. **You're past roughly 1,000 tenants.** At real scale [the tenancy model itself becomes the binding cost](/blog/database-per-tenant-cost), and the constraint shifts from engineering hours to a connection-pool ceiling that no build-cost table on this page prices in. ### Where BuildBase sits in this We didn't write this post to make the arithmetic land somewhere convenient. PlugNode, AgentCenter and Imejis - three of the six products we run ourselves - use auth and OAuth, team workspaces, Stripe billing and usage-based credit metering, the exact module set this post prices out separately, on one platform instance each rather than a separately built and maintained stack. That's less a claim about BuildBase and more a description of what not re-deriving this math five times actually looks like day to day: infrastructure work like this is estimated to eat 60-70% of engineering time on a typical SaaS team, and every module you build instead of buy is a slice of that percentage with your name on it, every year, not just at launch. --- ## The maintenance cost AI code does not show you > AI can scaffold your auth and billing in a weekend. What it costs to maintain after is the number nobody prices - here is the year-two math. - Source: https://www.buildbase.app/blog/ai-generated-code-maintenance-cost - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-09-02 - Updated: 2026-09-22 ### In short An AI coding agent can scaffold basic auth code in a day or two, cheaper than an engineer building it by hand. What that comparison skips is maintenance: two studies found AI-authored code carries higher churn and unresolved technical debt than human-written code, and that gap compounds every year it keeps running. An AI coding agent will build you a working login screen and a Stripe checkout in an afternoon. That part of the pitch is true, and it's why "I built my SaaS backend with Claude Code in a weekend" posts keep doing numbers, the same way a [$199 boilerplate](/compare/shipfast-vs-buildbase) used to. What those posts don't do is come back in month eight and price what it actually takes to keep that code running. ### The question What does an AI-generated auth and billing integration cost across two years, once the maintenance line is priced honestly instead of assumed away? ### The assumptions Same rate and scope as [the cost of building auth yourself](/blog/cost-of-building-auth-yourself), so the two numbers are comparable: one senior engineer at a loaded $150 an hour, building email/password signup, sessions, password reset and one OAuth provider. No SSO, no MFA. - **AI build time: 8-24 hours.** Prompting, reviewing, testing and fixing the generated code into something that actually runs in production, not just a demo. That's our own working estimate for this scope, not a published figure - roughly a fifteenth to a tenth of the 120-240 hours the same post quotes for building it by hand. Swap in your own number; the shape of the argument survives a wide range here. - **Maintenance, human-written baseline: 20% of build cost a year.** The same benchmark the auth-cost post uses, held flat. - **Maintenance, AI-authored code: elevated, and not flat.** GitClear's analysis of 211 million lines of code found near-term code churn (code reverted or rewritten within two weeks of being added) roughly doubled industry-wide as AI coding assistants became common, from a 3.3% pre-AI baseline to 5.7% in 2024 and 7.1% in 2025. Separately, a large-scale study tracking 304,362 verified AI-authored commits across 6,275 public GitHub repositories ("Debt Behind the AI Boom") found unresolved technical debt introduced by AI tools growing from a few hundred issues in early 2025 to over 110,000 by February 2026, not getting paid down as the codebase aged. Both figures re-verified against the source reports on 2 September 2026. Neither paper hands you a dollar-maintenance percentage for AI-authored code specifically, and no published industry benchmark for one exists yet. So this post prices AI-code maintenance at double the human-written baseline in year one, rising further in year two to reflect debt that compounds instead of resetting. That is a reasoned estimate, not a sourced figure - it is the input most worth swapping for your own once you have real bug and rework data. ### The arithmetic | Year | AI build | AI maintenance | Year cost | Cumulative | | ---- | -------- | -------------- | --------- | ---------- | | 1 | $2,400 | $960 (40%) | $3,360 | $3,360 | | 2 | - | $1,560 (65%) | $1,560 | $4,920 | $960 in year one plus $1,560 in year two is $2,520 in maintenance alone over two years, on top of the $2,400 build. Two years in, that's $4,920 spent keeping AI-authored auth code alive, against $380 for two years of BuildBase's Launch plan at $190 a year. That isn't a like-for-like comparison - the $380 also buys billing and workspaces alongside auth, not auth alone - but it's the same shape of unfairness the "I built it in a weekend" posts run in reverse: they quote the cheap number and skip the line that keeps recurring. ### The total, and what moves it The build-cost gap is real and worth taking seriously: $2,400 to scaffold with an agent against $27,000 to write it by hand is not a rounding error, and nobody should pretend otherwise. What changes the story is the slope of the maintenance line. The human-written baseline in the auth-cost post holds maintenance flat at 20% of build cost, forever, because a person who wrote the code understands it and the fixes stay proportional. The AI-code line here doesn't hold flat because the debt studies above don't show it holding flat - unresolved issues grew by more than two orders of magnitude in about a year in the commit sample, which is a codebase accumulating debt faster than anyone is paying it down, not settling into a steady rate. Push the model to year three and the AI-built total keeps climbing while BuildBase's stays at $190 a year, flat, because we carry the maintenance line instead of you. The AI route is still cheaper than paying someone to hand-write the same scope. It was never actually free. > **Key takeaway:** An AI agent can scaffold basic auth for around $2,400 in engineer time, > against $27,000 to build it by hand. But the maintenance rate on AI-authored > code runs higher than the human-written 20%-a-year benchmark, and two years in > that puts the AI-built total at $4,920, still cheaper than hand-coding it but > about thirteen times what BuildBase's Launch plan costs for the same period, > with billing and workspaces included. ### Where this math stops applying **You review and own every line the agent writes**, the way a senior engineer would review a junior's pull request, and refactor as you go instead of shipping whatever passes the tests. That discipline is exactly what the churn studies say most teams aren't doing yet, and it closes most of the gap this post prices. **The build is genuinely throwaway** - a prototype you'll rewrite before it touches a real user. None of the maintenance math matters for code that has a two-week lifespan by design. **Your team's engineering rate sits well below $150 an hour.** The maintenance premium still applies proportionally, but the absolute dollars at stake shrink enough that the decision gets closer. ### Where BuildBase sits in this We don't regenerate auth, billing and workspace code per project and hope the next AI-authored copy holds up. It's one module, maintained once, and it runs unmodified across the six products BuildBase operates itself. A fix lands there once and every product gets it the same day, instead of each AI-generated instance quietly accumulating its own separate pile of unresolved debt. That's the actual alternative to pricing this maintenance line at all: not writing less code with an agent, but not carrying the line yourself in the first place - the same logic that applies once auth stops being the only line item, [across the rest of the stack](/blog/auth-billing-stack-cost). --- ## Database-per-tenant vs shared schema: the decision is about migrations, not isolation > Shared schema, schema-per-tenant or database-per-tenant. Everyone frames it as isolation versus cost. The real fork is how many times you run every migration. - Source: https://www.buildbase.app/blog/database-per-tenant-vs-shared-schema - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-09-02 ### In short Shared schema puts every tenant in the same tables behind a tenant_id column. Schema-per-tenant gives each its own namespace in one database. Database-per-tenant gives each its own instance. The usual framing is isolation versus cost. What actually decides it is how many times you will run every schema change. Shared schema puts [every tenant](/blog/what-is-multi-tenancy) in the same tables behind a `tenant_id` column. Schema-per-tenant gives each tenant its own namespace inside one database. Database-per-tenant gives each its own instance. Every post on this topic then draws the same table: isolation on one axis, cost on the other, pick your point on the line. That table is not wrong. It is just not the thing that decides the choice, because isolation is mostly solvable in software and cost is mostly the database line item, which is the smallest bill involved. The thing that decides it is a schema change. ### Why the isolation framing misleads The fear behind database-per-tenant is a query that forgets its `WHERE tenant_id = ?` and hands one customer another customer's rows. Real fear, real incidents. But it is a fear about one bug class, and row-level security in Postgres closes most of it at the database rather than in application code. Once every table carries a policy that filters on the session's tenant, a forgotten filter returns nothing rather than everything. What row-level security does not solve is the tenant whose data is a hundred times bigger than anyone else's, sitting in the same table, slowing every query that touches it. That is the noisy neighbour, and it is a performance problem dressed up as an isolation problem. The shared schema handles it by extracting that one tenant, not by moving everyone. So the isolation axis collapses to two honest cases. A contract or regulator requires physical separation, in which case the decision was made for you and the cost is simply what the contract costs to deliver. Or it does not, in which case row-level security plus the ability to extract a whale gets you almost all of the way there. ### What a migration means in each model This is the fork. **Shared schema.** A migration runs once. It touches one set of tables. If it fails, it fails once, at a known time, with one person watching. Adding a column to `projects` is a Tuesday. **Database-per-tenant.** The same migration runs once per tenant. With 100 tenants that is 100 runs. With 10,000 it is 10,000, and some of them will fail, because some tenant will have a row that violates the new constraint or a database that was mid-backup when the job arrived. Now someone is supervising a rollout, and rollouts across thousands of databases take days. [The cost post on this pattern](/blog/database-per-tenant-cost) worked that supervision out at roughly $25,050 a month at 10,000 tenants, at a $150 an hour loaded rate. It is the largest line in that post by a wide margin. Larger than the databases. **Schema-per-tenant.** The migration runs once per schema, which is once per tenant. So the migration cost is the database-per-tenant cost. And the connection pool, the backups and the noisy neighbour are the shared-schema problems, because it is still one instance. This is why the pattern reads well in a design doc and badly in an incident review. > **Key takeaway:** Count the migrations, not the databases. A shared schema runs each schema > change once. Per-tenant models run it once per tenant, and past a few hundred > tenants the supervision of those runs costs more than the instances do. ### How to actually choose Two numbers decide it: how many tenants, and how much each one pays. | Tenants | Contract size | Model | | ------------------------------------ | -------------------------------------------- | -------------------------------------------------------------------- | | A handful | Six figures, with data terms in the contract | Database-per-tenant | | Hundreds to thousands | Self-serve, per seat or per usage | Shared schema, row-level security | | A shared base plus one or two whales | Mixed | Shared schema, extract the whales | | Any | Any | Not schema-per-tenant, unless the count is small and will stay small | Five customers paying six figures each, with a clause about where their data lives, is a per-tenant product whatever the ops cost, because the ops cost is in the price. Five hundred teams paying per seat is a shared schema, because the alternative is a migration rollout that competes with the roadmap every sprint. Under about 100 tenants, none of this adds up to much either way, which is exactly when it is hardest to migrate away from whatever you picked. Pick for the count you expect at the point the product is working, not the count you have now. ### When each one is the wrong choice Database-per-tenant is wrong for a self-serve product. A signup that provisions a database is a signup that takes seconds instead of milliseconds, costs money whether or not the customer ever returns, and adds one more migration target for every trial that churns. The pattern assumes tenants are few and valuable. Free tiers violate both assumptions at once. Shared schema is wrong when the contract says otherwise. Not when the customer prefers otherwise, or when a security questionnaire has a checkbox for it. When the signed terms require it. Everything short of that is a conversation about row-level security and a data-residency region. Schema-per-tenant is wrong more often than it is right. It is the pattern teams reach for to avoid choosing, and it postpones the choice by inheriting both sets of problems. If the count is genuinely small, say a dozen tenants that will stay a dozen, it is fine. If the count is going to grow, it is the one you will regret. ### What this looks like from where we sit BuildBase runs both, at two different levels, and that turns out to be the useful way to think about it. Each customer of ours, an org building a product on the SDK, gets its own database. Inside that, the org's own customers are workspaces, which share the org's schema and are [isolated by workspace rather than by instance](/guides/per-org-data-isolation-nextjs). A schema change on the workspace model runs once per org database, and the ceiling an org hits is workspace count per plan rather than a connection limit per workspace. Which is to say: per-tenant where tenants are few and paying, shared where they are many and self-serve, and the boundary drawn at the point where the tenant count changes character. That is the same rule as the table above, applied twice. The [workspaces guide](/guides/multi-tenant-workspaces-in-an-afternoon) is the working-code version of the shared half, and the [cost post](/blog/database-per-tenant-cost) is the arithmetic behind the per-tenant half. --- ## Entitlements are not feature flags, even when the same component renders both > A flag says the code is ready. An entitlement says this customer paid. Same boolean at the render site, different owner, lifecycle and failure mode. - Source: https://www.buildbase.app/blog/entitlements-are-not-feature-flags - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-09-02 ### In short A feature flag says whether code is ready to show. An entitlement says whether this customer paid for it. At the render site both are a boolean around a component, but they have different owners, change on different schedules and fail in opposite directions. Flags die after a rollout. Entitlements outlive it. A feature flag says whether code is ready to show. An entitlement says whether this customer paid for it. At the render site they look identical, a boolean around a component, and that is the whole reason they get confused. The confusion is cheap until the first pricing change. Then someone spends an afternoon in a flag dashboard trying to remember which of forty toggles mean "Pro" and which mean "we were testing that in March". ### Why the two look the same Because the UI cannot tell them apart. Here is a dashboard with both kinds of gate on it: ```tsx ``` The first one is an entitlement. `advanced-analytics` is on because the workspace is on a plan that includes it, and it goes off on their next page load or session refresh after the downgrade. The second one is a flag. `beta-editor` is on because someone put this user on a targeting list, and it goes off when the editor ships to everyone and the flag is deleted. Same shape. Same `slug` prop. And we ship both under a module called feature flags, with docs that call them both feature flags, which is a fair description of the mechanism and a bad description of what they are for. This post exists partly to correct our own naming. ### What actually differs **Who owns it.** A flag is owned by the engineer who is shipping the thing. An entitlement is owned by whoever owns the pricing page. When those are the same person, which they are at every company with under ten people, the difference feels academic. It stops being academic the first time a salesperson promises a feature to a customer and expects it to turn on without a deploy. **Where the truth lives.** A flag's truth is a list: these users, this percentage, this environment. An entitlement's truth is the plan. The plan version says [which features, limits and quotas it includes](/blog/what-are-entitlements), and the entitlement is read from that, not stored beside it. Change the plan, and every workspace on it changes with it. That is not a nice-to-have. It is the definition. **How it dies.** A flag's endpoint is deletion: the rollout finishes, the flag is 100% on, someone removes the `if`. A flag that survives past its rollout is technical debt with a dashboard entry. An entitlement never dies while the plan exists. Deleting one is a pricing decision, not a cleanup. **Which way it fails.** A flag stuck on shows unfinished code to everyone. A flag stuck off hides a finished feature. Annoying, both recoverable, and neither costs money directly. An entitlement stuck on gives a feature away to customers who did not pay for it, and you will not find out, because nobody emails to say they are getting too much. An entitlement stuck off refuses a paying customer, and you will find out within the hour. | | Feature flag | Entitlement | | ---------------------- | ------------------------------------------- | ------------------------------------------- | | Answers | Is this ready? | Did they pay for this? | | Owned by | Engineering | Pricing | | Truth lives in | A targeting list | The plan version | | Changes when | A rollout moves | A plan changes, or a customer switches plan | | Ends when | The rollout is done and the flag is deleted | The plan is retired | | Fails expensively when | Rarely | Stuck on: revenue leaks. Stuck off: churn | > **Key takeaway:** If changing the pricing page should change who has access, that gate is an > entitlement and it must resolve from the plan. If shipping the code should > change who has access, that gate is a flag and it should be gone in a month. ### The mechanism, concretely An entitlement resolves from a published plan version. The version carries its items: features, limits and quotas. When a session loads, the workspace's current plan is read, the items come with it, and the checks in the UI read from that cached set. No extra request per render, and no separate place where "Pro includes analytics" is written down a second time. Which version is not a detail. A subscription stays pinned to the version it was sold, so [publishing new pricing leaves existing customers exactly where they are](/guides/plan-versioning-nextjs) and a check that reads the plan's latest version instead hands them whatever you shipped last week. One consequence worth knowing before it surprises you: the entitlements change on the next page load or session refresh, not instantly in an open tab. That is the correct behaviour for a commercial rule. Nobody needs an upgrade to appear mid-keystroke. It is the wrong behaviour for a kill switch, which is one more reason a kill switch is a flag and not an entitlement. On a downgrade the lag is longer than a session: [the plan reports the change immediately while the features run to the end of the period](/guides/proration-on-plan-change-nextjs). Then there is the composition, which is where the distinction earns its keep: ```tsx ``` Three gates, three different questions. Does the plan include AI generation? Is this member allowed to spend? Are there at least 10 credits? Entitlement, permission, balance. They nest because they are independent, and they are independent because each one has a different owner and a different reason to change. Collapsing them into one flag called `can-generate` would work for exactly as long as nobody changes a plan, a role or a price. ### When an entitlement is the wrong tool A beta rollout. A percentage ramp. A kill switch for a feature that is misbehaving in production. An experiment where half of one plan sees a new onboarding. None of these have anything to do with what the customer paid for, and encoding them as plan items pollutes the pricing model with engineering state. Use a flag. Delete it afterwards. ### When a flag is the wrong tool Anything that appears on the pricing page. If the word is in a plan comparison table, it is an entitlement, whatever tool currently gates it. The failure mode of using a flag here is slow: it works fine, then a plan changes, then someone updates most of the flags, then a customer on the old plan keeps a feature for four months because one flag was missed. That is not a bug in the flag tool. It is a flag being asked to remember something only the plan knows. ### What this is not An entitlement is not a permission. The plan entitles the workspace to billing management; [the role decides which member may do it](/blog/what-is-rbac). And an entitlement is not a quota, although a quota is attached to one: the plan entitles the workspace to `api-calls`, and the quota is the number. The quota side of that, and the difference between a quota and a credit, is the sibling post: [quotas are not credits](/blog/quotas-are-not-credits). BuildBase resolves plan-tied features from the plan version and user-targeted features from a list, under one [feature flags module](/features), and the [reference](https://docs.buildbase.app/feature-flags/overview) shows both. The distinction above is the same whatever you build it on. The naming is on us. --- ## Quotas are not credits: which one your plan actually needs > A quota resets on a fixed cycle and belongs to the plan. A credit is a balance the customer bought. Pick by who absorbs the spike. - Source: https://www.buildbase.app/blog/quotas-are-not-credits - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-09-02 - Updated: 2026-10-23 ### In short A quota is an allowance in a plan that resets on a fixed cycle, usually monthly: 10,000 API calls a month, gone at the reset. A credit is a balance the customer bought that carries until spent. Quotas belong to the subscription, credits to the customer, and picking the wrong one shows up as an email about a bill. A quota is an allowance that comes with a plan and resets on a fixed cycle, usually monthly: 10,000 API calls a month, included, gone at the reset. A credit is a balance the customer bought that sits until it is spent or expires. Quotas belong to the subscription. Credits belong to the customer. That sounds like a distinction for the billing team. It is not. It decides who absorbs a spike, whether a customer can keep working on the 28th of the month, and what the support inbox looks like on the 1st. ### Why there are two mechanisms at all Subscription revenue is predictable and consumption revenue is not, and the two mechanisms exist to encode two different promises. A quota says: pay this much every month and you get this much, and we both know the ceiling. A credit says: pay for what you will use, use it when you like, and the ceiling is your wallet. Quotas alone leave money on the table. Products that only offer credits make budgeting impossible for the customer who needs a fixed number to put in a purchase order. So most pricing pages end up with both, often without anyone having decided that on purpose. ### How a quota actually works A quota is a counter against a slug. `api-calls`, `storage-mb`, `video-renders`. The plan version says how many units are included. Each time the thing happens you record it, server-side, and the record comes back with what is left: ```typescript const usage = await bb.usage.record(workspaceId, { quotaSlug: 'api-calls', quantity: 1, idempotencyKey: req.headers.get('x-request-id'), }); if (usage.available <= 0) { return Response.json({ error: 'Quota exceeded' }, { status: 429 }); } ``` Three things in that snippet are the whole design. The record and the check are one call, so there is no window where a burst of requests all pass the check before any of them is counted. [The idempotency key means a retried request does not count twice](/blog/idempotency-in-billing), which matters the moment you put this behind a queue. And the response is a number, not a boolean, so the UI can warn at 80% instead of refusing at 100%. At the limit a quota does one of two things. It stops: the record call fails with a 402 carrying `code: 'QUOTA_EXHAUSTED'`, the `quotaSlug` and `resetsAt`, and your route answers with a 429 and a message about upgrading. Or it enters overage, where the units past the included amount are metered and billed separately. Both are legitimate. What is not legitimate is a quota that silently keeps counting past the limit with no state change, because then the number on the invoice is the first the customer hears of it. Then the period rolls over and the counter goes back to zero. Whatever was unused is gone. That is the defining property, and it is the one customers argue about. ### How a credit actually works A credit is a ledger entry. The customer buys a package and the balance goes up. Spend some, it goes down. Nothing resets. [Standing the wallet up](/guides/credits-wallet-nextjs) is its own job, and the balance turns out not to be a single number. ```typescript try { await bb.credits.consume(workspaceId, { amount: 50, description: 'Batch export', idempotencyKey: req.headers.get('x-request-id'), }); } catch (err) { if (err.code === 'INSUFFICIENT_CREDITS') { return Response.json({ error: 'Not enough credits' }, { status: 402 }); } } ``` Notice what your route answers. The platform refuses both with a 402: an exhausted quota with `code: 'QUOTA_EXHAUSTED'`, a short balance from its own credits route. The quota route above answers its own caller with a 429, too many requests, because the customer has hit a rate the plan set. A credit exhaustion stays a 402, payment required, because the fix is to buy more. [Writing that route in Next.js](/guides/charge-per-credit-nextjs) is its own guide. That is not pedantry. The two errors send the customer to two different screens, and the one for credits should have a buy button on it. Two properties of credits cause most of the design work. The first is that `amount` is a parameter, so different actions can cost different amounts, and the price of an action can change without touching the customer's balance. A quota counts events; a credit system prices them. The second is expiry. Credits that never expire are an open liability on your books forever. Credits that do expire need the customer to see what is expiring and when, or the expiry reads as theft. A downgrade is where the two clocks separate: [credits already bought run until they expire on their own](/guides/proration-on-plan-change-nextjs) while the quota allowance drops at the switch. > **Key takeaway:** A quota counts events and resets. A credit prices events and carries. Quota > exhaustion should reach your caller as a 429 that says upgrade, credit > exhaustion is a 402 that says buy, and the two should send the customer to two > different screens. ### Which one, then It comes down to three questions, and the third is the one people skip. **Does usage reset?** If a customer who used nothing in March should start April with the same allowance as everyone else on the plan, that is a quota. If what they did not use in March is still theirs in April, that is a credit. **Is the unit priced, or counted?** If every event costs the same and the plan includes a number of them, count with a quota. If a short render and a long render should cost different amounts, price with credits. Trying to express variable cost as a quota means inventing a synthetic unit, and every synthetic unit eventually needs a page explaining it. **Who absorbs the spike?** A quota with a hard stop puts the spike on the customer: they hit the wall and wait or upgrade. A quota with overage puts it on the invoice, which is fine if they expected it and a dispute if they did not. Credits put it on the customer's wallet, in advance, which is the only version where nobody is surprised. | If the answer is | Use | | ---------------------------------------- | ------- | | Resets monthly, same cost per event | Quota | | Carries over, same cost per event | Credits | | Variable cost per event, any reset rule | Credits | | Fixed monthly budget in a purchase order | Quota | ### When each one is the wrong choice Credits are the wrong tool for anything the plan should simply include. Seats are the usual mistake. A team plan that includes five members is a quota on members, and making people buy member-credits turns a pricing page into a puzzle. The same goes for storage, projects, and most things a customer counts on their fingers. Quotas are the wrong tool when the wall is the churn moment. A self-serve product where a customer hits the limit on the 20th and cannot do anything until the 1st has just handed them ten days to try a competitor. Overage softens that, but overage on a product with no spending cap is how a customer ends up with an invoice they did not authorise. If usage is bursty and the customer would rather top up than wait, that is a credit system, and it should have been from the start. The combination most API products land on is a quota included with the plan and credits for what goes over. The included amount gives the customer a number for the budget. The credits give them a way past it without a plan change. The [per-call billing guide](/guides/charge-per-api-call-nextjs) walks through that loop in one route handler, including the case where the unit is not a request. A trial is the third thing again: not an allowance and not a balance, but a clock, and [running one without a card](/guides/free-trial-without-a-card-nextjs) is where that difference starts to bite. ### What this is not A quota is not an entitlement, although it is enforced by one. The plan entitles the workspace to `api-calls`; the quota is the number attached to that entitlement. And neither is a feature flag, even though all three end up as a boolean around a component in the UI. That confusion has its own post: [entitlements are not feature flags](/blog/entitlements-are-not-feature-flags). Both mechanisms, the quota counter and the credit ledger, sit inside BuildBase's [billing module](/billing), and the [quota reference](https://docs.buildbase.app/credits/quotas) has the full surface. But the decision above is the same whatever you build it on. --- ## The hidden revenue tax of billing platforms > Some billing platforms charge a percentage of revenue instead of a flat fee. Here is the crossover math showing when that costs more than a flat plan, and how to run it with your own numbers. - Source: https://www.buildbase.app/blog/billing-platform-revenue-tax - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-08-30 - Updated: 2026-10-22 ### In short Some billing platforms price by taking a cut of the revenue you process, not a flat fee. That cut scales with your business, not your platform usage, so it behaves like a tax on growth. The crossover point, where percentage pricing starts costing more than a flat plan, usually lands under $1M ARR. A 0.5% fee on your revenue sounds like nothing. It is nothing, at $200,000 a year - $1,000. Run the same rate once revenue clears $10M and it is $50,000, more than most teams spend on [their entire billing stack combined](/blog/auth-billing-stack-cost). That is the part a rate card does not put in the hero section: a percentage of revenue is not a price, it is your own growth rate turned into a bill. Several billing and subscription-infrastructure vendors, Stripe Billing, Chargebee, Paddle, Orb and Metronome among them, have been reported elsewhere as pricing at least part of what they sell as a cut of the revenue or billing volume that flows through the platform, instead of a flat subscription fee. This is a real pricing model, not a straw man. Checked against each vendor's own pricing page on 24 September 2026: | Vendor | What they charge | | -------------- | ---------------------------------------------------------- | | Stripe Billing | 0.7% of billing volume, pay-as-you-go | | Metronome | 0.8% of billing volume on the Startup plan | | Chargebee | 0.80% with no platform fee, or $99/mo plus 0.65% | | Orb | Prices on billings, but publishes no rate - custom pricing | | Paddle | 5% + 50c per checkout transaction, as merchant of record | Three of the five publish a rate, and all three land between 0.65% and 0.8%. Orb says outright that it prices on "the total value of all invoices" you issue through it, then puts every tier behind a sales conversation, so the rate exists but the number is not public. Paddle is the odd one out and should be read separately: 5% is high because it is a merchant of record bundling payment processing, tax registration and chargeback liability into one line, which is a genuinely different purchase from a billing platform sitting on top of your own Stripe account. Rates move without an announcement, so check your vendor's page on the day you run this. [The Stripe Billing alternatives post](/compare/stripe-billing-alternatives) and [the Lago alternatives post](/compare/lago-alternatives) compare these vendors in more depth, and [best usage-based billing tools](/compare/best-usage-based-billing-tools) covers which of them enforce a usage limit rather than only billing for it after the fact. What follows is the shape of the math, with the percentage left as a variable you plug in yourself. ### The question At what revenue level does a straight percentage-of-revenue billing fee start costing more than a flat platform fee, and how fast does the gap grow after that? ### The assumptions - **A rate range of 0.25% to 1% of revenue.** Wide enough to bracket every published rate in the table above - Stripe Billing's 0.7%, Metronome's 0.8% and Chargebee's 0.65-0.80% all sit inside it - so you can find your own vendor's actual rate and read off the row that applies. It deliberately excludes merchant-of-record pricing like Paddle's 5%, which is buying something else. - **Annual recurring revenue standing in for billing volume.** The two are not always identical (refunds and one-time charges move billing volume without moving ARR), but they are close enough for the shape of this argument. - **BuildBase's own numbers from `PLANS` in `packages/shared/src/constants/platform-stats.ts`, re-read 31 October 2026.** Launch is $190 a year, Grow $490, Scale $990 - the published annual prices, not monthly times twelve. There is also a Free plan at $0, and the paid plans start on a 7-day trial that does not require a card. - **BuildBase's fee stays flat regardless of revenue processed.** The quotas that bill incrementally on the paid plans are workflow runs (from $0.25 per 1,000), web analytics events ($2 per 100,000) and storage ($0.10 per GB-month) beyond the plan allowance - all unrelated to how much revenue moves through your connected Stripe account. ### The arithmetic First, the crossover: the ARR at which a percentage fee equals each flat BuildBase plan's annual price. Below this line, percentage pricing is cheaper. Above it, flat pricing is, and stays that way. | Assumed rate | Crossover vs Launch ($190/yr) | Crossover vs Grow ($490/yr) | Crossover vs Scale ($990/yr) | | ------------ | ----------------------------- | --------------------------- | ---------------------------- | | 0.25% | $76,000 | $196,000 | $396,000 | | 0.50% | $38,000 | $98,000 | $198,000 | | 0.75% | $25,300 | $65,300 | $132,000 | | 1.00% | $19,000 | $49,000 | $99,000 | Second, what the percentage fee actually costs at real revenue levels, against a flat $990-a-year Scale plan that does not move: | ARR | 0.25% | 0.50% | 0.75% | 1.00% | BuildBase Scale (flat) | | ---- | ------- | -------- | -------- | -------- | ---------------------- | | $1M | $2,500 | $5,000 | $7,500 | $10,000 | $990 | | $5M | $12,500 | $25,000 | $37,500 | $50,000 | $990 | | $10M | $25,000 | $50,000 | $75,000 | $100,000 | $990 | | $25M | $62,500 | $125,000 | $187,500 | $250,000 | $990 | Even the low end of the range, 0.25%, already costs more than BuildBase's top flat plan at $1M ARR. By $10M, the mid-scenario rate of 0.5% is $50,000 a year against BuildBase's flat $990 - a difference of $49,010, and that gap did not come from anything getting more expensive to run. It came from revenue going up. ### The total, and what moves it Read the crossover table honestly and the pattern holds across every plan and every rate in the range. A percentage-of-revenue fee overtakes a flat annual plan somewhere between roughly $19,000 and $396,000 in ARR, depending on the rate and the plan you are comparing against. That is a revenue level a lot of funded or bootstrapped SaaS companies reach well before their platform choices stop being easy to change, which is exactly when this math is worth running. The one input that actually moves this conclusion is the rate itself, and every published rate we could find today sits between 0.65% and 0.8% - which is to say between the 0.50% and 0.75% rows, near the middle of the band. If your vendor publishes 0.4%, use the 0.50% row as an upper bound and interpolate down. If they publish 1.2%, extrapolate past the 1.00% row - the crossover point only gets closer, not further. The direction of the argument does not change; only how soon you hit it does. > **Key takeaway:** A percentage-of-revenue billing fee is not a fixed cost. It is a cost that > grows every time your revenue does, with no ceiling, while a flat platform fee > stays the same number on the invoice whether you process $200,000 or $20 > million through it. ### Where this math stops applying **Revenue is low or unpredictable.** Below the crossover point, a percentage fee is genuinely cheaper, and it carries no fixed cost to pay before you have made any money at all. That is a real advantage for a pre-revenue or early company, not a rounding error. **The percentage is bundled with work that is actually hard.** Merchant-of- record vendors take on tax and VAT compliance, chargeback liability and fraud handling as part of that cut - infrastructure a flat-fee platform sitting on top of your own Stripe account does not take on for you. That is a fairness point worth stating plainly rather than waving away: the fee is buying something real in that case, not just a rate card. **Your growth has already plateaued.** The whole argument is about a fee that compounds with growth. A mature company with flat or slow-growing revenue does not feel the compounding the way a company doubling every year does - the crossover math still applies, it just stops mattering as much once the denominator stops moving. ### Where BuildBase sits in this BuildBase's billing module does not process payments itself. It runs subscription lifecycle, plan versioning and usage-based metering on top of your own connected Stripe account - you still need a Stripe account, and you still pay Stripe's own processing fees on top, separately. What BuildBase itself charges is whichever flat plan you are on: Free, Launch, Grow or Scale, with no percentage layered over your revenue at any point, ever. The only things that change your bill are which plan tier your MAU, workspace count or storage needs land in, and any overage on workflow runs, analytics events or storage, not how much money moves through your Stripe account that month. [PlugNode](https://plugnode.ai) runs its own credit-based billing on this same module in production, alongside BuildBase auth and team workspaces - one of the products this platform is dogfooded on before it ships to anyone else. The module is also what [charging per API call in Next.js](/guides/charge-per-api-call-nextjs) is built on, if you want to see the metering-to-Stripe path this post's numbers assume. None of that makes a percentage-of-revenue vendor wrong to choose. It makes the choice worth running through the crossover math above with your actual numbers, rather than deciding on the headline rate alone. Building the metering and subscription logic yourself instead of buying either shape of vendor sidesteps the percentage too, but it carries [its own real cost](/blog/cost-of-building-usage-metering-yourself), not a free one. --- ## Self-host vs managed: the real cost comparison > What self-hosting BuildBase really costs: a custom-priced license plus compute, a managed database, monitoring and patch time, line by line against one flat managed bill. - Source: https://www.buildbase.app/blog/self-host-vs-managed-cost - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-08-29 ### In short Self-hosting BuildBase is custom-priced, and on top of that license you pay for compute, a managed database, monitoring and the hours to patch and run it. Priced in dollars, that ops time is the largest line, and it pushes the self-hosted total past the managed plan before the license is counted. BuildBase ships a self-hosted option: your own Docker containers, your own database, the same 20 modules, on a license priced for your setup rather than a public plan. The pitch writes itself - your infrastructure, your control. Pricing the infrastructure out looks just as easy: one small VPS running the whole quick-start compose file comes in under $30 a month, not far off the Launch plan's $19. That number is not the bill. It never is - the same blind spot shows up [pricing a database per tenant](/blog/database-per-tenant-cost) and [pricing an assembled vendor stack](/blog/auth-billing-stack-cost): the sticker price is real, and it is the smallest part of the real cost. A single box with no managed backups and no redundancy is also not what anyone would actually run once paying customers depend on it - so that is not the setup this post prices out. ### The assumptions Every input here is stated so you can swap in your own and recompute. - **The self-hosted license is left out of every total.** Self-hosting is custom-priced per setup, so there is no public figure to put in the table. Every number below is before it, which makes this comparison generous to self-hosting, not harsh on it. - **A workload sized like the Launch plan** - up to 25,000 monthly active users, the tier most teams actually evaluating this trade-off sit at. - **A production-grade setup**, not the single-VPS quick start. Two `app` replicas behind an nginx load balancer, which is exactly what BuildBase's own `deploy/docker-compose.prod.yml` defaults to, plus an externally managed database - that template ships no database service at all, unlike the quick-start compose, so you bring your own. - **A fully loaded US backend engineer costs roughly $70 an hour.** Public salary data puts the range closer to $58-$85 depending on seniority and market; $70 is a stated midpoint, not a sourced vendor figure. Halve or raise it and the shape of the argument does not change. - **Three hours a week of patch and on-call time** - OS and dependency patches, a database or Redis version bump every so often, checking a backup actually restores, responding to the occasional alert. This is a stated assumption, not a benchmark, and it is the number most worth arguing with. - Compute and database prices below are commodity 2026 rates for VMs and a small managed database tier, gathered from public pricing summaries rather than a single invoice - directional, not a quote you can hold a vendor to. ### The arithmetic | Line item | Monthly cost | Where it comes from | | ---------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | | Compute, 2 nodes | ~$48 | Two small cloud VMs at roughly $24 each, 2 vCPU / 4 GB - sized above the platform's stated 2 GB minimum for production headroom | | Managed database | ~$57 | A small dedicated managed database tier | | Redis | $0 | Runs in your own container - the one line self-hosting actually saves | | Monitoring | $0 | Covered by a free ingest tier at this scale | | Patch and on-call time | ~$910 | 3 hrs/week, ~13 hrs/month, at $70/hr | | **Total** | **~$1,015** | | Compute and the managed database together come to roughly **$105 a month**, before the license - already past Launch's $19, Grow's $49 and Scale's $99 too, before anyone opens a terminal to patch anything. Add the hours it actually takes to run that infrastructure and the total lands over fifty times Launch's plan price for the equivalent workload. > **Key takeaway:** The infrastructure self-hosting replaces is the cheap part. The hours to > patch, monitor and be on call for it are the expensive part, and they are the > part every self-hosting pitch leaves off the calculator. ### What moves the total Sensitivity matters more than the headline. Halve the assumed ops time to 1.5 hours a week and the total is still roughly **$560 a month** - more than twenty-nine times Launch's plan price, and still more than five times Scale's $99. Cut the hourly rate to $35 instead, leave the hours alone, and you land at about **$560** again. Same number, different lever. That tells you this figure is dominated by hours, not by rate - halving either one cuts the total by the same amount, because the patch-and-on-call line is the only one that scales with attention instead of a vendor's price sheet. The one line that moves the other direction is Redis. Running it in your own container instead of paying for a managed tier is a real saving against what a managed Redis tier would otherwise cost. It isn't free of risk, though - BuildBase backs sessions and BullMQ workflow queues with Redis, with append-only persistence enabled in the self-hosted compose, so losing that container without a working backup costs you active sessions and queued workflow runs, not nothing. ### Where this math stops applying **You already carry the ops capacity.** If patching and on-call for this stack rides along with patching and on-call you're already doing elsewhere - same engineer, same rotation, no new hire - the marginal hours are close to zero. The calculus flips. This post prices the hours as new; for a team that already staffs them, they are not. **Data residency or a contract requires it.** When a customer or a regulator requires the database to sit somewhere specific, self-hosting is not a cost decision being weighed against a managed plan. It is a term of the deal, and the number above is what that term costs to deliver. **The workload outgrows the flat plan anyway.** Past Scale's included 500,000 MAU, BuildBase's own pricing moves to a custom Enterprise conversation rather than a fixed $99. At that size the comparison in this post - a fixed plan price against a self-hosted total - is not the one that applies. The real question becomes what a custom managed contract costs against the same infrastructure at that scale - and that math needs its own post. ### Where BuildBase sits in this Self-hosting BuildBase does not trade away modules - every module on the [managed plans](/pricing) ships in the [self-hosted](/self-hosted) image too. What you are actually buying with the monthly plan price is someone else carrying the three hours a week this post prices out, plus the on-call rotation behind it. Whether that is worth roughly $910 a month depends entirely on whether your team's ops hours are already spoken for - which is an honest question this post can price but cannot answer for you. It's also a different question from [whether to build the modules yourself](/blog/buy-vs-build-saas-infrastructure) in the first place. Self-hosting still means running BuildBase's auth and metering, not writing your own - the ops-hours math above and the build-hours math there answer two different questions that only look like one. --- ## The cost of building usage metering yourself > The real engineering cost of building usage metering in-house: build time, the maintenance tax that follows it, and the meter-drift bug nobody prices until it happens. - Source: https://www.buildbase.app/blog/cost-of-building-usage-metering-yourself - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-08-28 - Updated: 2026-10-22 ### In short Building usage metering in-house runs $86,400 to $172,800 in year one for one engineer, most of it in the maintenance tax that keeps landing after launch. Vendor blog posts cite $100,000 to $1,000,000 as if it were one number - the real range depends on your build timeline, not the parts they emphasize. Search "cost of building usage metering" and every top result is written by a company selling the alternative. Their numbers range from $100,000 to over $1,000,000, with no visible arithmetic behind either end. That's not a cost model. It's a sales page with a dollar sign on it. So here's the arithmetic, with every input stated so you can swap in your own numbers and get a different answer. If your inputs are different, they should give you a different total - that's the point of showing the work instead of quoting a headline figure. ### The assumptions - **One senior engineer, not a team**, building it from scratch. - **A loaded rate of $150 an hour.** The same assumption this blog uses for [building auth yourself](/blog/cost-of-building-auth-yourself) and [database-per-tenant](/blog/database-per-tenant-cost). It roughly matches an independent source too: the U.S. Bureau of Labor Statistics puts the median U.S. software developer salary at $135,980 a year as of its May 2025 release, and loading that up by the same 30-70% overhead the auth post cites lands in the same $95-$180-an-hour band. $150 sits toward the middle. - **Scope: [idempotent event ingestion](/blog/idempotency-keys-metering-write-path), quota tracking across more than one metric, and a correction path for when a count turns out wrong after the fact.** Not a single incrementing counter. Every vendor selling this agrees that scope is where the time actually goes, which is also the scope this post prices. - **Build time: 3 to 6 months.** We don't have our own published estimate for metering the way we do for auth - `MARKETING_CLAIMS.authBuildTime` in the platform constants says 3-6 weeks, but that's a narrower build, not this one. The range comes from companies that sell metering infrastructure and have an obvious incentive to make building it yourself sound slow. We couldn't re-verify any single one of those claims against its own source page today, so no specific figure or company is quoted here - only the range their own estimates cluster around once idempotency and backfill enter the picture. - **Maintenance: 20% of the build cost every year after**, the same generic software-maintenance benchmark the auth post uses. No metering-specific figure exists to replace it. ### The arithmetic Hours assume roughly 160 working hours a month for one engineer. | Build time | Hours | Build cost at $150/hr | Maintenance at 20%/yr | Year-one total | | ---------------- | ----- | --------------------- | --------------------- | -------------- | | 3 months (low) | 480 | $72,000 | $14,400 | $86,400 | | 4.5 months (mid) | 720 | $108,000 | $21,600 | $129,600 | | 6 months (high) | 960 | $144,000 | $28,800 | $172,800 | None of those three totals include the cost of a mistake. A meter that double-counts on retry over-bills a customer, who disputes it and asks pointed questions about every invoice since. A meter that silently drops events under-bills quietly, for months, until someone [reconciles revenue against usage logs](/guides/usage-does-not-match-invoice) and finds the gap. Both are common enough that they show up in every vendor's sales pitch - and neither has a dollar figure attached to it anywhere we could find, ours included. ### The total, and what moves it At the middle of the range, building usage metering in-house costs roughly **$129,600** in year one for one engineer - closer to the low end of the "$100,000 to $1,000,000" vendor blogs cite than the high end. The gap comes down to scope: the high numbers usually assume a team, not one engineer, and a longer list of billing models than most products actually need on day one. Sensitivity matters more than the headline. Halve the loaded rate to $75 an hour - a junior or offshore rate - and the mid-scenario total is still $64,800, not nothing, and it repeats every year the maintenance line is due. Double the build timeline instead, to 12 months because idempotency and backfill turned out harder than planned, and the total is $345,600 before a single customer dispute gets counted. > **Key takeaway:** Building usage metering in-house runs $86,400 to $172,800 in year one for one > engineer, most of it recurring as a 20%-a-year maintenance tax rather than a > one-time build cost. The vendor number you'll see quoted elsewhere skips the > arithmetic and goes straight to the headline. ### Where this math stops applying **Your pricing model has one metric and never changes.** A single incrementing counter with no proration, no correction path and no per-customer override is a much smaller build - weeks, not months - and the buy case gets correspondingly weaker. Most of what makes metering expensive is the correction and dispute-handling machinery, and a product that genuinely doesn't need it shouldn't price as though it does. **Metering is your actual product.** If you're building a billing or metering company, none of this is overhead - it's the thing you sell, and the calculation runs backward the same way it does for auth. **Event volume is still small.** Early on, a meter-drift bug affects a handful of invoices, not thousands. The maintenance tax is real at any volume, but the cost of getting it wrong scales with how many customers are counting on the number being right. ### Where BuildBase sits in this BuildBase's [credits and usage metering module](https://docs.buildbase.app/credits/overview) tracks per-plan quota limits across metrics like API calls, seats, storage and emails sent, syncs metered usage to Stripe, and applies overage billing automatically - the job a dedicated metering engine like Lago or Orb would otherwise do. The record-and-enforce loop itself is one route handler, [shown here for a Next.js API route](/guides/charge-per-api-call-nextjs), which is most of what the build-cost estimate above is actually pricing. It's not unlimited scope: on our own paid plans three quotas bill overage today - workflow runs (from $0.25 per 1,000), web analytics events ($2 per 100,000) and storage ($0.10 per GB-month) beyond the plan allowance; emails, webhook deliveries, web push and MAU are hard allowances that don't bill past their limit yet. If your pricing model needs overage on a metric outside that list, the module doesn't cover it yet either - check before assuming it does. Set the module's cost against the arithmetic above: BuildBase's Launch plan is $19 a month, $190 a year paid annually (verified against the platform constants on 31 October 2026), against $86,400-$172,800 to build a narrower version of the same thing yourself in year one. That $190 also buys auth, billing and workspaces alongside metering, not metering alone - so it isn't "same scope, different price," it's what you'd pay to make this math moot for that particular line item. That's a different trade than picking a dedicated metering vendor instead of building. [Lago](/compare/lago-vs-buildbase) and [Stigg](/compare/buildbase-vs-stigg) both go deeper on metering and entitlements specifically, at the cost of being one more system to wire in rather than one already wired to a workspace and a role. Buying either of those is still buying, though - this post is about the third option, building the whole thing yourself. --- ## The cost of building auth yourself > The real line-item cost of building auth in-house at small-SaaS scale, in hours and dollars, not the enterprise figures everyone else quotes. - Source: https://www.buildbase.app/blog/cost-of-building-auth-yourself - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-08-27 - Updated: 2026-09-22 ### In short Building basic auth yourself (signup, login, sessions, password reset, one OAuth provider) runs 120-240 engineer-hours at $150 an hour, plus 15-25% of that every year in maintenance. At small-SaaS scale that is $21,600-$43,200 in year one, against $190 a year on a managed plan covering billing and workspaces too. Search "cost of building auth" and you get two kinds of numbers. A vendor's $300,000-to-$700,000 horror story, or an indie hacker's "I built it in a weekend for free." Neither is the number you actually need. The first prices a full passkey, MFA and fraud-detection stack sized for an enterprise buyer. The second is one data point with no maintenance math attached. What's missing from both is the arithmetic a two-person SaaS can actually check against its own hours: what does a basic login flow cost to build, and then to keep alive, in year one? ### The assumptions Every input here is stated so you can swap in your own and recompute. - **One senior engineer, not a team**, building it from scratch. - **A loaded rate of $150 an hour.** ZipRecruiter, Indeed and Glassdoor put a senior US engineer's 2026 salary at roughly $143,000-$210,000; loaded cost - benefits, overhead, taxes - typically runs 30-70% above base, which is where the commonly cited $95-$180-an-hour range comes from. We're using a round $150, toward the middle. Halve it for a junior or offshore rate and the shape of the argument does not change, just the size. - **Scope: email/password signup, session handling, a password reset flow and one OAuth provider** - Sign in with Google, say. No SSO, no MFA, no fraud detection. [The enterprise-scale figures you'll see elsewhere](/compare/auth0-vs-buildbase) are priced for those, not this. - **Build time: 3-6 weeks per engineer.** That's our own published estimate for building auth from scratch, and it covers a broader scope than the one above - so treat it as an upper bound on this narrower build, not a precise fit. We'll show the low, middle and high end rather than pretend it's one number. - **Maintenance: 20% of the original build cost every year after.** Cost-benchmarking write-ups on software maintenance put ongoing upkeep at 15-25% of build cost annually - patching, dependency bumps, provider API changes - and we're using the middle of that too. ### The arithmetic | Build time | Hours | Build cost at $150/hr | Maintenance at 20%/yr | Year-one total | | --------------- | ----- | --------------------- | --------------------- | -------------- | | 3 weeks (low) | 120 | $18,000 | $3,600 | $21,600 | | 4.5 weeks (mid) | 180 | $27,000 | $5,400 | $32,400 | | 6 weeks (high) | 240 | $36,000 | $7,200 | $43,200 | Maintenance is the row people forget to run. It doesn't show up on the day you ship, so it's easy to price the build and stop there. It arrives instead as a Tuesday when Google rotates an OAuth scope, or a password-reset email starts landing in spam, or a dependency bump breaks session handling three minutes before a demo. ### The total, and what moves it The number that matters isn't the $32,400 in the middle row. It's that the maintenance line repeats every year while the build cost doesn't. Cut the maintenance rate in half, to 10%, and you're still paying $1,800-$3,600 a year, forever, just to keep a login screen working. That recurring bill is the part the $300K horror stories and the weekend-build tweets both leave out. Set that against what the same year costs on a managed plan: BuildBase's Launch tier is $19 a month, $190 a year if you pay annually, $228 if you pay monthly, and the Free plan covers the same basic auth at $0 up to 10,000 monthly active users. Either way, it's a rounding error next to $21,600-$43,200 - though it's a fair point that $190 also buys billing, workspaces and RBAC alongside auth, not auth alone. The comparison isn't "same scope, different price." It's "what you'd actually pay to make this math moot." > **Key takeaway:** A basic signup, login, session and one OAuth button costs $21,600 to $43,200 > for one engineer to build and maintain in year one. The same scope is $190 a > year on a managed plan, and the gap is almost entirely the maintenance line > nobody prices up front. ### Where this math stops applying The arithmetic above doesn't decide everything. **Auth is your actual product.** If you're building an identity or auth company, none of this is overhead - it's the thing you sell, and the calculation runs backward. You're not saving engineering time; you're spending it on your moat. **A customer needs more than a login button.** Once a deal requires [single sign-on](/compare/workos-vs-buildbase), dedicated compliance work or anything past this post's scope, you've left the basic build behind, and the much bigger figures circulating elsewhere start to apply. This post is deliberately about the smaller build most small SaaS teams actually need first. **Your engineer's rate is far from $150 an hour.** Junior-market or offshore rates a third of that still don't flip the outcome - the mid-scope build at $50 an hour is still $10,800 in year one, not $190 - but they do compress the gap enough that the decision gets closer for a team that's genuinely rate-constrained rather than time-constrained. ### Where BuildBase sits in this We didn't do this math once and stop. BuildBase's own auth module runs unmodified across six products we operate ourselves - PlugNode, AgentCenter and Imejis among them - which is what building it once instead of six times actually looks like. Auth is also just [the first bill in a bigger pattern](/blog/auth-billing-stack-cost): infrastructure work like this is estimated to eat 60-70% of engineering time on a typical SaaS team, and this post covers one line item inside that, not the whole thing. --- ## What database-per-tenant actually costs > The real cost of a database per tenant: infra bills, connection pooling, ops load, and the tenant count where it stops paying for itself. - Source: https://www.buildbase.app/blog/database-per-tenant-cost - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-08-26 - Updated: 2026-10-26 ### In short Database-per-tenant costs more than the database line item - raw hosting is often the smallest part. Connection pooling, per-tenant backups, monitoring and migration supervision add up fast, and past a certain tenant count the ops overhead outweighs the infrastructure bill itself. Database-per-tenant looks cheap on the pricing calculator. Pick a small managed instance, multiply by the tenant count, and the number that comes out is usually smaller than people expect. That number is also not the bill. The same blind spot shows up whenever a sticker price stands in for the real cost - [totaling an assembled auth-and-billing stack](/blog/auth-billing-stack-cost) hits it too, just with vendor subscriptions instead of database instances, and so does [pricing self-hosting against a managed plan](/blog/self-host-vs-managed-cost), with ops hours standing in for the subscriptions. And the sticker really is small. PlanetScale sells a single-node Postgres cluster for $5 a month, a Supabase Pro project - a dedicated Postgres instance - starts at $25, and a Neon database that has scaled to zero bills $0 for compute while it sleeps (each figure verified 26 October 2026 on the vendor's pricing page, and none of the three had moved). A hundred tenants at five dollars each is $500 a month, which most teams would sign off without a meeting. That is the number the calculator gives you, and it is the least important number in this post. ### The assumptions Every input here is stated so you can swap in your own and recompute. - **A fully loaded senior engineer costs $150 an hour.** This is a common loaded-cost assumption for US engineering time (salary, benefits, overhead) rather than a sourced vendor figure - halve it if your team's real number is lower, the shape of the argument does not change. - **One managed Postgres instance per tenant**, the pattern the whole post is about. Not a connection-pooled shared cluster, not schema-per-tenant on one instance - a genuinely separate database per customer. - **A routine schema change happens roughly once a month.** Adding a column, adding an index, backfilling a default - the kind of migration most SaaS products ship regularly, not a rare rewrite. - **1% of nightly backup jobs need a human look** in a given month - a stalled job, a size anomaly, a restore test that fails. That rate is a guess, not a benchmark; if your real failure rate is different, the backup line moves with it. - Three tenant counts examined: **100, 1,000 and 10,000** - roughly where a new product, a growing one, and a mature multi-tenant SaaS sit. ### The arithmetic The database instance cost is real but it is not where this pattern gets expensive. What scales with tenant count is supervision time, and it scales because every operation that would be "run once" on a shared database becomes "run N times, watched" on N databases. | Tenant count | Pooling upkeep | Backup triage | Migration supervision | Monitoring/alerting | Total labor | Ops cost @ $150/hr | | ------------ | -------------- | ------------- | --------------------- | ------------------- | ----------- | ------------------ | | 100 | 1 hr | 0.25 hr | 1.7 hr | 0.5 hr | ~3.4 hr | ~$510 | | 1,000 | 2 hr | 2.5 hr | 16.7 hr | 2 hr | ~23 hr | ~$3,450 | | 10,000 | 4 hr | 25 hr | 167 hr | 8 hr | ~204 hr | ~$30,600 | How each column is built: - **Pooling upkeep.** Every managed Postgres instance caps total open connections in the low hundreds without an external pooler. N databases means N connection ceilings, so past a few hundred tenants you are running and re-tuning a pooler (PgBouncer or equivalent) rather than relying on the database's own limit. The hours here are re-tuning and capacity review, not first-time setup. - **Backup triage.** One backup job per database, each with its own retention policy and point-in-time-recovery target. At the assumed 1% failure rate, 10,000 databases produce 100 failures a month to investigate at roughly 15 minutes each. - **Migration supervision.** A migration against a shared database runs once. Against database-per-tenant it has to run, or be orchestrated to run, once per database - with concurrency limits so you do not take every tenant offline at the same instant. At roughly one minute of supervised rollout time per database, this is the column that dominates, and it dominates because it is the one direct multiplication by tenant count with no economy of scale. - **Monitoring and alerting.** Every isolated database is a distinct monitored target - CPU, disk, replication lag, slow queries. More targets means more dashboard noise and more alerts that turn out to be nothing, and someone has to triage that noise even on a quiet month. ### The total, and what moves it At 10,000 tenants, a month that includes one routine schema change costs roughly **$30,600** in ops labor: ~$25,050 of migration supervision, ~$3,750 of backup triage, ~$1,200 of monitoring and ~$600 of pooler upkeep - before anyone looks at what the 10,000 database instances cost to host. Sensitivity matters more than the headline number. Halve the assumed hourly rate to $75, and the 10,000-tenant ops labor is still roughly **$15,300**, more than most teams have budgeted for a single column addition. Halve the tenant count to 5,000 instead and migration supervision is still on the order of $12,500. What actually protects you isn't a cheaper engineer. It's not choosing database-per-tenant at that scale in the first place - or building the tooling to run one migration unattended across every tenant database, which is itself an engineering project, not a free option. > **Key takeaway:** The database instance is rarely the expensive part of database-per-tenant. The > expensive part is that every operation which would run once on a shared > database has to run, and be watched, once per tenant. ### Where this math stops applying Three cases where the arithmetic above does not decide anything: **Compliance-driven isolation.** When a contract or a regulator requires a tenant's data to sit in a physically or logically separate database - data residency terms, a healthcare or government deployment - the isolation is not a scaling choice you are weighing against cost. It is a term of the deal, and the ops cost above is simply what that term costs to deliver. **Low tenant counts.** Under roughly 100 tenants, none of the columns above add up to more than a few hours a month. The pattern is not expensive yet; it becomes expensive when it grows, which is exactly when it is hardest to migrate away from. **Automated, unattended migration tooling.** If a team has already built orchestration that runs a schema change across every tenant database without a human watching each one, the migration-supervision column collapses toward zero. That tooling is real engineering work with its own cost, so building it is a bet that you will run enough migrations across enough tenants for the investment to pay back - not a reason to treat the pattern as free. ### Where BuildBase sits in this BuildBase's [workspaces module](https://docs.buildbase.app/workspaces/overview) isolates each customer's data, feature flags, members and billing by workspace rather than by database - the ceiling is workspace count per plan (50 on Free, 1,000 on Launch, 25,000 on Grow, 100,000 on Scale, per `PLANS` in the platform constants, verified 31 October 2026), not a connection limit per instance. A schema change runs once, against one database, regardless of how many workspaces sit on top of it. That is a different tradeoff than database-per-tenant, not a strictly better one - a workspace does not get its own physically separate database, which is exactly the property compliance-driven isolation above requires. If that property is what you need, this math was never arguing against it. For the fuller version of that tradeoff - a workspace-scoped SDK against a Postgres database you provision and query yourself - see [Supabase vs BuildBase](/compare/buildbase-vs-supabase). If you're counting per-tenant instances because [what multi-tenancy costs in general](/guides/multi-tenant-workspaces-in-an-afternoon) is the real question, this post is the narrower, working-code version of it. --- ## The real monthly cost of Clerk plus Stripe plus Lago plus Knock > Four best-of-breed vendors, added up with the assumptions shown. The subscriptions are not the expensive part. - Source: https://www.buildbase.app/blog/auth-billing-stack-cost - Section: Blog - Author: Dharmendra Jagodana - Published: 2026-08-14 ### In short At 20,000 users the published subscriptions for auth and notifications come to roughly $375 a month before Stripe fees, and metering is unpriced because Lago publishes no cloud rate. The larger cost is the integration you own between four systems, which no pricing page shows and which does not go away. Every "build vs buy" post compares subscription prices and stops there. The subscriptions are the part you can see. They are rarely the part that makes the decision expensive. Here is the arithmetic anyway, with every assumption stated so you can argue with it. ### The assumptions Change any of these and the total moves. That is why they are listed. - A B2B SaaS with **20,000 monthly active users** - Selling a **metered** product, so usage has to be counted and billed - **Transactional notifications**: receipts, alerts, quota warnings - US-based, standard card payments - No more than 100 customer organizations, so Clerk's per-organization metering ($1 a month for each one past 100 per app) never applies - Prices verified **24 September 2026** and quoted from each vendor's own page ### The subscriptions | Vendor | Job | Monthly at 20,000 users | | ------ | ------------- | -------------------------------------- | | Clerk | Auth | $25 Pro plus $100 B2B add-on, so $125 | | Stripe | Payments | Percentage of revenue, see below | | Lago | Metering | Not published, see below | | Knock | Notifications | $250 Starter, 50,000 messages included | **Clerk** is the pleasant surprise. The Pro plan is $25 a month with 50,000 monthly retained users included, and $0.02 for each one beyond that. At 20,000 users you are inside the included allowance. The costs that bite are the add-ons: each enterprise SSO connection beyond the first is $75 a month, and the B2B organizations add-on is $100 a month. A B2B product selling to teams probably needs the second one, which takes the auth line from $25 to $125. **Knock** is the largest published line at $250 a month for Starter, including 50,000 messages, then $0.005 per message. A metered product that emails a quota warning at 80 percent, a receipt monthly and an alert on failure will generate more messages than user count suggests. **Stripe** is a percentage rather than a subscription. It scales with revenue, not with users, which makes it the one line you should be happy to see grow - though if it's specifically the Billing add-on's platform fee pushing you to look elsewhere, [Stripe Billing alternatives](/compare/stripe-billing-alternatives) sorts the options by what they actually replace. And if it's the revenue-share shape itself you're weighing rather than Stripe specifically, [the crossover point where a percentage fee costs more than a flat plan](/blog/billing-platform-revenue-tax) runs that math with your own numbers. **Lago** publishes no cloud pricing. The self-hosted edition is open source under AGPLv3, so the real cost there is infrastructure and the engineer who maintains it. Cloud pricing requires a sales conversation. I am not going to invent a figure for a post whose entire purpose is arithmetic you can check. If metering depth specifically is what's pulling you toward Lago rather than the rest of this stack, [how it stacks up against bundling metering into BuildBase](/compare/lago-vs-buildbase) is the narrower version of this same arithmetic. So: **roughly $375 a month** in visible subscriptions at this shape, or $275 if you skip the B2B add-on, plus Stripe's percentage, plus whatever Lago costs you. ### The line nobody puts on a pricing page Four vendors means three integrations you own forever. Clerk knows who the user is. Lago knows what they used. Stripe knows what they paid. Knock knows what they were told. Nothing in that list knows all four things, so you write the code that makes them agree, and you keep writing it every time one of them changes an API or a webhook payload. Concretely, the agreements you maintain: - A user in Clerk maps to a customer in Stripe maps to a subscriber in Lago - Usage recorded in Lago has to reach Stripe before the invoice closes - A quota warning needs usage from Lago, entitlement from Lago or Stripe, and identity from Clerk before Knock can send it - Every one of those has a failure mode, and the failure mode is a wrong invoice That is not hypothetical overhead. It is the code that produces the support ticket that starts "I was charged for". ### Where the assembled stack wins Honestly: in depth, and in exit. Each of these products is better at its single job than a module in a bundle. Knock's notification engine does more than our email module. Lago's metering model is richer. If one of them stops fitting, you replace one thing rather than migrating a platform. If your product's difficulty is concentrated in exactly one of those areas, buy the best one for that area and assemble around it. That is a good decision and this post is not arguing against it. ### Where the bundle wins When no single area is your hard problem, and you need all four to work together. Then the integration is the work, and it is work that produces no product. Our numbers are at [/pricing](/pricing). The comparison against a vendor that takes the assembled-stack position is in [Kinde vs BuildBase](/compare/buildbase-vs-kinde), the entitlements-first position in [Stigg vs BuildBase](/compare/buildbase-vs-stigg), and the identity-first position in [Auth0 vs BuildBase](/compare/auth0-vs-buildbase), and the auth-with-billing-attached position - Clerk is the first line in the table above - in [Clerk vs BuildBase](/compare/clerk-vs-buildbase). There is also a version of this argument one layer lower, starting from a raw database instead of a vendor stack, in [Supabase vs BuildBase](/compare/buildbase-vs-supabase), and the mobile-and-realtime-first version of that same primitives argument in [Firebase vs BuildBase](/compare/firebase-vs-buildbase). There is also a no-code, page-builder-first version of the same choice, for a stack built on Webflow or Squarespace instead of a codebase, in [Outseta vs BuildBase](/compare/outseta-vs-buildbase). And the same sticker-price-versus-real-cost pattern shows up in pure infrastructure terms, no vendor stack involved, in [what database-per-tenant actually costs](/blog/database-per-tenant-cost), and again in the self-hosted-versus-managed decision itself, where the ops hours replace the subscription line entirely, in [Self-host vs managed: the real cost comparison](/blog/self-host-vs-managed-cost). If your plan was to skip the vendors entirely and buy a boilerplate, the same four accounts show up there too - [what a one-time boilerplate leaves you operating](/compare/shipfast-vs-buildbase) is where that version of the arithmetic goes. Skip the vendors and build the pieces yourself instead, and [the auth piece alone still costs real hours](/blog/cost-of-building-auth-yourself) - [metering runs a similar bill](/blog/cost-of-building-usage-metering-yourself), most of it recurring as maintenance rather than the initial build. Not four subscriptions this time - your own engineering time. ### Re-check these numbers Every figure above has a date on it because every figure above will move. Clerk, Knock and Stripe all changed pricing in the last two years. If you are making a decision on this post more than a month after that date, open the four pricing pages yourself. That is the honest instruction, and it applies to our page too. --- ## BuildBase changelog What shipped, week by week. Source: https://www.buildbase.app/changelog ### Content and links stored as typed, and clearer upload refusals Week of 2 November 2026. Docs, testimonials, titles and short links keep exactly what you typed, every too-large upload gets the same answer, and the workspace's creator now holds workspace:delete. #### Added - **Blueprints:** A blueprint can carry your organization's time zone as app.timezone. Applying it checks the zone the same way Settings > General does. - **Docs:** A new guide, Keep your existing sign-in, says what works when your app already signs people in with Supabase, Clerk, Auth0, Firebase or its own code, and what does not. #### Improved - **Console:** The console's markdown editor shows HTML inside a post, doc or content block as inert, so a script in it cannot run while you edit. #### Fixed - **Content:** Docs, content blocks, testimonials, blog titles and FAQ questions are stored exactly as typed. A & or < no longer comes back as & or <, and a title such as Q&A: