How to Calculate MRR from the Stripe API (Code + Formula)
Stripe API · Updated 11 November 2026
TL;DR
Stripe does not return an MRR field. List subscriptions with status active, trialing, and past_due, follow auto-pagination, and sum each licensed item as unit_amount × quantity normalized to one month. The TypeScript below does the listing and calls normalizeStripeSubscriptionMrr for the interval, coupon, and currency rules. Trialing subscriptions are excluded. past_due is excluded unless you opt in. A subscription with cancel_at_period_end stays active until the period ends and is included until then.
The definition of the metric is on the monthly recurring revenue glossary page. Try the factors on plans you type in with the SaaS metrics calculator. A Dashboard subscriptions CSV can be normalized in the browser with the Stripe MRR CSV calculator. That page does not call the API and does not upload the file. The same monthly normalization is what the Next.js Stripe analytics dashboard shows for active subscriptions. The live demo uses sample data and does not call Stripe.
- License
- $59 once
- Refund
- 7-day no-questions refund
- Stack
- Next.js 16, shadcn/ui, Recharts, Postgres, Drizzle, Clerk, optional Stripe
What this page calculates
Monthly recurring revenue is the monthly run-rate of subscription revenue after each price is normalized to one month. A one-time charge is not MRR. Cash that landed this month is not MRR. Annual recurring revenue on this page is that monthly total, after rounding, multiplied by 12. Churn needs a starting snapshot and the subscriptions that left. This page is one snapshot. How to calculate churn rate from Stripe is the procedure for customer churn, gross MRR churn, and net MRR churn. How to calculate net revenue retention from Stripe keeps that starting book and reports NRR and GRR, including expansion, contraction, and churned MRR. How to calculate customer lifetime value from Stripe uses this monthly ARPU, divided by the churn fraction from that starting book.
The glossary states the formula. This page is the Stripe API call: which statuses to request, how pagination and expand actually behave, and the TypeScript that feeds the shared normalizer. The normalizer is the MIT file on the calculator, lib/tools/stripe-mrr.ts. The interval table is not copied here.
1. List active, trialing, and past_due
stripe.subscriptions.list takes one status at a time. The snippet requests active, trialing, and past_due so you can see the rows a policy might drop. It does not request canceled, incomplete, incomplete_expired, unpaid, or paused.
If you omit status, Stripe returns subscriptions that have not been canceled. That set still includes incomplete, unpaid, paused, trialing, and past_due. status=all also returns canceled subscriptions, including those on deleted customers. Either shortcut will inflate MRR if you sum every row.
The default page size is 10 and the maximum limit is 100. has_more means another page. The official Node SDK method autoPagingToArray follows starting_after until the list ends or the limit you pass is reached. The snippet uses 100 per request and a safety cap of 100,000 records per status. That cap is local. It is not a Stripe maximum. The three lists run together with Promise.all. Each list still pages itself in order.
2. Load every item and expand coupons
A subscription can have more than one item, and items.has_more can be true after the first page of items. When that happens, list subscriptionItems for that subscription id and auto-page those too. Each item contributes unit_amount × quantity. A missing quantity is treated as 1. A negative quantity is skipped.
Discounts arrive as ids unless you expand them. An id has no percent_off or amount_off, so the normalizer leaves the price unchanged and counts the id in unexpandedDiscounts. Expand data.discounts.source.coupon on the subscription list. Stripe allows four expand levels, so data.items.data.discounts.source.coupon does not fit on that same call. The snippet expands data.items.data.discounts there, then reloads the items with data.discounts.source.coupon when a coupon is still a string. A coupon id that is still unresolved is retrieved with coupons.retrieve and cached.
Coupons that live only on the Customer object are not on subscription.discounts. This function does not read customer.discount. Tax is not added or removed. unit_amount is the price as stored.
3. Trials, past_due, and cancel at period end
trialing means the subscription is still in its trial. The snippet lists those rows and then leaves them out of the sum. An active subscription whose trial_end is already in the past is a paying subscription and counts. The decision uses status, not a guess about the first invoice.
past_due means a payment failed or an invoice was not paid by its due date, and Stripe may still be retrying. Some teams keep that revenue in MRR until the subscription is canceled or unpaid. This function leaves it out unless you pass includePastDue: true. That flag is a policy switch. It does not change the price math.
cancel_at_period_end: true does not flip status to canceled today. Stripe keeps the subscription active through the current period. The default is to include it, because the customer is still in a paid period. Pass excludeCancelAtPeriodEnd: true when you want MRR to count only subscriptions you expect to renew. A future cancel_at with cancel_at_period_end set to false is a different field. The flag does not read cancel_at, so that subscription still counts.
4. Quantity, intervals, and coupons
The shared normalizer converts minor units, multiplies by quantity, and normalizes the billing interval. These factors are a run-rate convention. They are not fields Stripe returns.
monthdivides byinterval_count. A quarter isinterval: "month"andinterval_count: 3, so the factor is 1/3.yeardivides by12 × interval_count.weekmultiplies by52/12, then divides byinterval_count. That is not “× 4”.daymultiplies by365/12, then divides byinterval_count.
For USD, divide the minor units by 100. A zero-decimal currency such as JPY is already a major unit: amount 1500 is ¥1,500, not ¥15.00. The normalizer follows Stripe’s zero-decimal list and still divides UGX by 100, because Stripe’s currencies guide keeps UGX amounts in two-decimal form for backwards compatibility. For a three-decimal currency (BHD, JOD, KWD, OMR, TND), pass minorUnitFactor: 1000. The function does not assume that divisor on its own.
Item discounts apply to that item. Subscription discounts then apply to the subscription total. Stripe documents that order on the discount arrays. percent_off scales the amount. Two percent coupons multiply. A 20% item coupon and a 10% subscription coupon leave 72% of the item, not 70%. amount_off is a minor-unit discount for the billing period of that item, or of the first priced item when the coupon sits on the subscription. It is then normalized with the same interval factor. A $12 forever amount-off on a $120 yearly price is $1 of MRR, not $12.
duration: "forever" always applies. duration: "once" does not change MRR, because the next invoice is full price. duration: "repeating" applies while discount.end is null or still in the future. Stripe sets end for a repeating coupon and leaves it null for once and forever. If a repeating discount arrives with a null end, this function still applies it.
The result is rounded once, to the currency’s decimal places. ARR is that rounded MRR multiplied by 12, then rounded again. Do not add the latest invoice into this sum.
5. Currencies and metered prices
The normalizer locks the currency of the first priced item and skips later items in another currency. Those skipped items increment mixedCurrencyItems. It does not call an exchange rate. If you bill in more than one currency, split the subscriptions by currency and call the function once per currency. Do not add those MRR figures together.
usage_type: "metered" bills recorded usage. billing_scheme: "tiered" has no single unit_amount. Both are skipped and counted in skippedItems. Using the per-unit rate as if it were a flat monthly fee overstates or understates the run-rate, depending on usage you have not loaded. Usage belongs on a separate sum of invoice lines or meter events. This snippet does not compute that sum. transform_quantity is not applied.
TypeScript
Install stripe and copy lib/tools/stripe-mrr.ts from the SaaS metrics calculator. The file below is lib/guides/calculate-stripe-mrr.ts. It lists the three statuses, hydrates coupons, and calls normalizeStripeSubscriptionMrr. Keep the MIT copyright notice on the normalizer. Pass a secret key only on the server.
/**
* List Stripe subscriptions and normalize them to monthly recurring revenue.
*
* Stripe does not return an MRR field. Interval math, quantity, minor units,
* metered and tiered prices, and coupon duration live in
* `normalizeStripeSubscriptionMrr` (MIT, `lib/tools/stripe-mrr.ts`). Copy that
* file with this one and keep the copyright notice. Change the import below
* if `stripe-mrr.ts` does not sit at `../tools/stripe-mrr`.
*
* Run this on the server. `STRIPE_SECRET_KEY` is a secret key.
*/
import Stripe from "stripe"
import {
normalizeStripeSubscriptionMrr,
type NormalizedStripeMrr,
type StripeDiscountLike,
type StripeSubscriptionItemLike,
type StripeSubscriptionLike,
} from "../tools/stripe-mrr"
/** Statuses worth inspecting before the MRR policy. Canceled, unpaid, incomplete, and paused are not requested. */
export const MRR_LIST_STATUSES = ["active", "trialing", "past_due"] as const
export type MrrListStatus = (typeof MRR_LIST_STATUSES)[number]
/**
* Safety cap passed to `autoPagingToArray`. This is not a Stripe page size.
* Stripe's list `limit` max is 100. A warning is logged if the cap is hit.
*/
const AUTO_PAGE_LIMIT = 100_000
export interface CalculateStripeMrrOptions {
/** Count `past_due` subscriptions. Default false. */
includePastDue?: boolean
/**
* Omit subscriptions with `cancel_at_period_end`. Default false: Stripe
* keeps those subscriptions `active` until the period ends, and they count
* until then. A future `cancel_at` with `cancel_at_period_end` false still counts.
*/
excludeCancelAtPeriodEnd?: boolean
now?: Date
/** Override the auto-pagination cap. */
pageLimit?: number
/** Divisor for a three-decimal currency (BHD, JOD, KWD, OMR, TND). Pass 1000. */
minorUnitFactor?: number
}
export interface MrrSubscriptionSource {
status?: string | null
cancel_at_period_end?: boolean | null
discounts?: Array<string | StripeDiscountLike> | null
items?: { data?: Array<StripeSubscriptionItemLike> | null } | null
}
export interface StripeMrrReport extends NormalizedStripeMrr {
/** Subscriptions rejected by the status and cancellation policy before item math. */
omittedSubscriptions: number
/** Subscriptions passed in, or returned by the three status lists. */
listedSubscriptions: number
}
export function createStripeClient(secretKey: string): Stripe {
return new Stripe(secretKey, {
apiVersion: "2025-10-29.clover",
typescript: true,
})
}
export function subscriptionIncludedInMrr(
subscription: { status?: string | null; cancel_at_period_end?: boolean | null },
options: Pick<CalculateStripeMrrOptions, "includePastDue" | "excludeCancelAtPeriodEnd"> = {},
): boolean {
if (options.excludeCancelAtPeriodEnd && subscription.cancel_at_period_end) return false
if (subscription.status === "active") return true
if (options.includePastDue && subscription.status === "past_due") return true
return false
}
/** Keep included subscriptions and mark them active so the shared normalizer counts an opted-in `past_due` row. */
export function toMrrSubscription(
subscription: MrrSubscriptionSource,
options: Pick<CalculateStripeMrrOptions, "includePastDue" | "excludeCancelAtPeriodEnd"> = {},
): StripeSubscriptionLike | null {
if (!subscriptionIncludedInMrr(subscription, options)) return null
return {
status: "active",
discounts: subscription.discounts ?? [],
items: { data: subscription.items?.data ?? [] },
}
}
export function calculateMrrFromListedSubscriptions(
subscriptions: readonly MrrSubscriptionSource[],
options: CalculateStripeMrrOptions = {},
): StripeMrrReport {
const included: StripeSubscriptionLike[] = []
let omittedSubscriptions = 0
for (const subscription of subscriptions) {
const mapped = toMrrSubscription(subscription, options)
if (!mapped) {
omittedSubscriptions += 1
continue
}
included.push(mapped)
}
const normalized = normalizeStripeSubscriptionMrr(included, {
now: options.now,
minorUnitFactor: options.minorUnitFactor,
})
return {
...normalized,
omittedSubscriptions,
listedSubscriptions: subscriptions.length,
}
}
async function hydrateDiscounts(
stripe: Stripe,
discounts: Array<string | Stripe.Discount> | null | undefined,
cache: Map<string, Stripe.Coupon>,
): Promise<Array<string | StripeDiscountLike>> {
if (!discounts?.length) return []
const resolved: Array<string | StripeDiscountLike> = []
for (const discount of discounts) {
if (typeof discount === "string") {
resolved.push(discount)
continue
}
let coupon = discount.source?.coupon ?? null
if (typeof coupon === "string") {
try {
const cached = cache.get(coupon)
if (cached) {
coupon = cached
} else {
const fetched = await stripe.coupons.retrieve(coupon)
cache.set(fetched.id, fetched)
coupon = fetched
}
} catch (error) {
console.error("[Data Lighthouse] Error fetching coupon:", error)
resolved.push(discount.id)
continue
}
}
if (!coupon || typeof coupon === "string") {
resolved.push(discount.id)
continue
}
resolved.push({
end: discount.end,
source: {
coupon: {
percent_off: coupon.percent_off,
amount_off: coupon.amount_off,
currency: coupon.currency,
duration: coupon.duration,
},
},
})
}
return resolved
}
function itemCouponsAreIds(items: Stripe.SubscriptionItem[]): boolean {
return items.some((item) =>
item.discounts.some((discount) => typeof discount !== "string" && typeof discount.source.coupon === "string"),
)
}
async function loadItems(
stripe: Stripe,
subscription: Stripe.Subscription,
cache: Map<string, Stripe.Coupon>,
pageLimit: number,
): Promise<StripeSubscriptionItemLike[]> {
let items = subscription.items.data
// Expand on the subscription list stops at four levels, so an item coupon
// (`data.items.data.discounts.source.coupon`) is not expanded there.
if (subscription.items.has_more || itemCouponsAreIds(items)) {
items = await stripe.subscriptionItems
.list({
subscription: subscription.id,
limit: 100,
expand: ["data.price", "data.discounts.source.coupon"],
})
.autoPagingToArray({ limit: pageLimit })
}
const prepared: StripeSubscriptionItemLike[] = []
for (const item of items) {
const price = item.price
prepared.push({
quantity: item.quantity ?? null,
discounts: await hydrateDiscounts(stripe, item.discounts, cache),
price: {
unit_amount: price.unit_amount,
unit_amount_decimal: price.unit_amount_decimal,
currency: price.currency,
billing_scheme: price.billing_scheme,
recurring: price.recurring
? {
interval: price.recurring.interval,
interval_count: price.recurring.interval_count,
usage_type: price.recurring.usage_type,
}
: null,
},
})
}
return prepared
}
export async function calculateMrrFromStripe(
stripe: Stripe,
options: CalculateStripeMrrOptions = {},
): Promise<StripeMrrReport> {
const pageLimit = options.pageLimit ?? AUTO_PAGE_LIMIT
const cache = new Map<string, Stripe.Coupon>()
const pages = await Promise.all(
MRR_LIST_STATUSES.map(async (status) => {
const subscriptions = await stripe.subscriptions
.list({
status,
limit: 100,
expand: ["data.discounts.source.coupon", "data.items.data.discounts"],
})
.autoPagingToArray({ limit: pageLimit })
if (subscriptions.length >= pageLimit) {
console.warn(`[Data Lighthouse] Stripe auto-pagination stopped at ${pageLimit} ${status} subscriptions.`)
}
return subscriptions
}),
)
const sources: MrrSubscriptionSource[] = []
for (const subscription of pages.flat()) {
sources.push({
status: subscription.status,
cancel_at_period_end: subscription.cancel_at_period_end,
discounts: await hydrateDiscounts(stripe, subscription.discounts, cache),
items: { data: await loadItems(stripe, subscription, cache, pageLimit) },
})
}
return calculateMrrFromListedSubscriptions(sources, options)
}
calculateMrrFromStripe(stripe) returns mrr, arr, currency, omittedSubscriptions, mixedCurrencyItems, skippedItems, and unexpandedDiscounts. Read the last three before you trust the total. calculateMrrFromListedSubscriptions is the same math for objects you already have in tests.
Hypothetical book
Every figure below is hypothetical. It is not the public demo and not a customer account. Each line is one subscription passed through calculateMrrFromListedSubscriptions. The combined row is one call with all eight subscriptions, so the yen price is skipped instead of added to the dollars.
| Subscription | Rule | On its own |
|---|---|---|
| $30 every month, quantity 2 | unit_amount 3000 × quantity 2 | $60.00 |
| $120 every year | unit_amount 12000, interval year, divided by 12 | $10.00 |
| $90 every 3 months | interval month, interval_count 3 | $30.00 |
| $10 every week | multiplied by 52/12 | $43.33 |
| $1 every day | multiplied by 365/12 | $30.42 |
| ¥1,500 every month | A second currency. The combined USD total skips it. | ¥1,500 |
| Trialing, $50 every month | status trialing | Excluded |
| past_due, $70 every month | Left out unless includePastDue is set | Excluded |
Combined, the function returns $173.75 MRR and $2,085.00 ARR. 2 subscriptions are omitted (the trial and the past_due row). 1 item is in another currency and is not added to the USD total. Opting the past_due row back in, on its own, returns $70.00.
A second hypothetical subscription is $100 every month with a forever 20% item coupon, a forever 10% subscription coupon, and a $120 yearly item. Item discounts run first: $100 × 0.8 = $80. The yearly item is $10. The subscription coupon then takes 10% off that $90, leaving $81.00 MRR, not $80. A $120 yearly price with a forever $12 amount-off (1,200 minor units on the yearly invoice) normalizes the discount as well: $9.00 MRR, which is $10 minus $1.
Common mistakes
- Stopping after the first page. The default page size is 10.
has_moremeans you do not have the account yet. - Omitting
status, or passingall, and summing canceled, incomplete, unpaid, or paused subscriptions. - Forgetting
quantity, or treating a null quantity as zero. A missing quantity is one seat. - Adding a yearly
unit_amountstraight into MRR, or dividing by 12 and ignoringinterval_count. - Turning a week into a month by multiplying by 4. This function uses 52/12.
- Counting
trialingsubscriptions before the first paid period. - Dropping
cancel_at_period_endsubscriptions as if Stripe had already canceled them. - Applying a
duration: oncecoupon to the run-rate. It changes one invoice. - Leaving discounts as ids. An unexpanded id does not change the amount, and a four-level expand cannot reach an item coupon from the subscription list.
- Subtracting
amount_offin major units, or forgetting to spread a yearly amount-off across 12 months. - Adding percent-off coupons. A 20% item coupon and a 10% subscription coupon compound.
- Treating a metered
unit_amountas the monthly fee, or a tiered price with a nullunit_amountas zero dollars of MRR when the line was skipped. - Adding USD and JPY amounts, or dividing a zero-decimal currency by 100.
- Adding the latest charge or paid invoice into the same total. That is cash collected.
- Expecting a customer-level coupon to apply when it is not also on the subscription or the item.
See it on a dashboard
The overview on the Next.js Stripe analytics dashboard template normalizes active subscriptions to one month with these interval factors, multiplies by quantity, follows Stripe auto-pagination, and leaves trialing subscriptions out. ARR on that card is the normalized MRR multiplied by 12. You host the Next.js app and set STRIPE_SECRET_KEY there. The license is $59 once.
The live demo renders the same overview with sample data. It does not call Stripe. The SaaS metrics calculator runs the MIT normalizer in the browser from plans you enter. The Stripe MRR CSV calculator runs that same normalizer on a subscriptions export, and the MRR glossary entry is the definition this code implements. Whether to build this route, pay a hosted metrics product, or start from the template is a separate decision, covered in build vs buy a SaaS metrics dashboard. This page is one live list. Whether that list should run on each view, or land in your database through webhooks and a reconciliation job, is how to sync Stripe data for a SaaS metrics dashboard.
Sources
Stripe’s API reference for the objects this snippet reads. Product behavior above was checked against this repository.
- Stripe API: list subscriptions
- Stripe API: Subscription object
- Stripe API: Subscription Item object
- Stripe API: Price object
- Stripe API: Coupon object
- Stripe API: Discount object
- Stripe API: pagination
- Stripe: expanding responses
- Stripe: zero-decimal currencies
- Stripe: subscription statuses
- Stripe: subscription quantities
Stripe MRR API questions
Short answers about the listing, the statuses, and the coupons.
Does the Stripe API return MRR?
No. The Subscription, Subscription Item, and Price objects do not include an MRR field. You compute it from price.unit_amount, quantity, recurring.interval, and recurring.interval_count, after you paginate the subscriptions you decided to count.
Which Stripe subscription statuses should I list for MRR?
List active, trialing, and past_due so the excluded rows are visible. The function on this page counts status active only. Trialing is excluded. past_due is excluded unless includePastDue is true. incomplete, incomplete_expired, unpaid, paused, and canceled are not requested. Omitting the status filter returns every subscription that has not been canceled, which is a wider set.
Does cancel_at_period_end remove a subscription from MRR?
Not by itself. Stripe keeps status active until the current period ends, then moves the subscription to canceled. The function includes those subscriptions unless excludeCancelAtPeriodEnd is true. A future cancel_at with cancel_at_period_end set to false still counts.
How do once, repeating, and forever coupons affect MRR?
A forever coupon applies to the run-rate. A once coupon reduces one invoice and does not change MRR. A repeating coupon applies while the discount end timestamp is null or still in the future. percent_off scales the monthly amount. amount_off is a minor-unit discount for that billing period and is normalized with the same interval factor. Item discounts apply before subscription discounts. An unexpanded discount id is ignored.
Why are metered and mixed-currency prices left out?
A metered price bills recorded usage, and a tiered price has no single unit_amount. Summing the per-unit rate would invent a flat fee. The normalizer skips both and reports them as skipped items. It also locks the first priced currency and skips later items in another currency instead of converting them. Report each currency on its own.
Where can I see this MRR calculation in a dashboard?
Data Lighthouse is a self-hosted Next.js template. The overview normalizes active Stripe subscriptions to one month with the same interval factors, includes quantity, follows auto-pagination, and leaves trialing subscriptions out. The license is $59 once. The buyer page is https://datalighthouse.dev/nextjs-stripe-analytics-dashboard and the sample dashboard is https://datalighthouse.dev/demo. The demo uses sample data and does not call Stripe. The SaaS metrics calculator at https://datalighthouse.dev/tools/saas-metrics-calculator runs the same monthly normalization in the browser. The Stripe MRR CSV calculator at https://datalighthouse.dev/tools/stripe-mrr-csv-calculator reads a subscriptions CSV in the browser and does not upload it.