Building a subscription tracker sounds like a simple development task. Create a list of recurring payments, calculate their total cost, and display the results.

However, once you start implementing the actual logic, several interesting problems appear:

  • Some subscriptions renew monthly, while others renew annually.
  • Floating-point arithmetic can introduce inaccuracies when handling money.
  • Monthly billing dates do not always exist in every month.
  • Paused and canceled subscriptions require different handling.
  • Upcoming renewals need to be calculated accurately.
  • Monthly spending estimates are not necessarily the same as actual monthly cash flow.

These challenges make subscription tracking a useful practical project for developers interested in building personal finance applications.

In this tutorial, we will build the core logic of a subscription tracker using TypeScript, without relying on external libraries or financial APIs.

By the end of this article, you will have a reusable foundation for managing recurring payments, calculating subscription costs, tracking renewal dates, and generating spending summaries.

1. Understanding the Problem

Imagine a user paying for five different monthly subscriptions.

Subscription Monthly cost
Streaming service $14.99
Music app $9.99
Cloud storage $2.99
Fitness app $12.99
AI tool $20.99
Total $61.95

These individual payments may appear relatively small, but their combined annual cost is:

$61.95 × 12 = $743.40 

Now imagine adding annual memberships, different renewal dates, paused subscriptions, and canceled services.

The application needs more than a simple list of expenses. It needs a structured system for managing recurring financial commitments.

Illustrative subscription dashboard showing five recurring payments totaling $61.95 per month and $743.40 per year.
Figure 1: An illustrative collection of five recurring subscriptions costing $61.95 per month and $743.40 per year.

Our subscription tracker will focus on four responsibilities:

  1. Store subscription information.
  2. Calculate recurring costs accurately.
  3. Manage subscription renewal dates.
  4. Generate useful spending summaries.

2. Setting Up the TypeScript Project

You can implement this example in an existing TypeScript application or create a new project.

mkdir subscription-tracker cd subscription-tracker npm init -y npm install -D typescript tsx @types/node npx tsc --init 

Create the following project structure:

subscription-tracker/ ├── src/ │ ├── types.ts │ ├── subscriptions.ts │ ├── calculations.ts │ ├── renewals.ts │ └── index.ts ├── tests/ │ └── subscriptions.test.ts ├── package.json └── tsconfig.json 

For this example, we will use a minimal TypeScript configuration.

{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "noEmit": true }, "include": ["src/**/*.ts", "tests/**/*.ts"] } 

We will keep the business logic separate from the presentation layer.

This makes the implementation easier to test and allows it to be reused in a React application, a backend service, or another TypeScript-based project.

3. Designing the Subscription Data Model

Before implementing any calculations, we need a consistent representation of a subscription.

Create src/types.ts.

export type BillingCycle = "monthly" | "yearly"; export type SubscriptionStatus = | "active" | "paused" | "canceled"; export interface Subscription { id: string; name: string; amountMinor: number; currency: "USD"; billingCycle: BillingCycle; category: string; status: SubscriptionStatus; nextRenewalDate: string | null; billingAnchorDate: string; } 

Each field serves a specific purpose.

Field Purpose
id Unique subscription identifier
name Subscription or service name
amountMinor Cost in integer minor currency units
currency Currency used by the subscription
billingCycle Monthly or yearly billing
category Financial spending category
status Current subscription state
nextRenewalDate Next expected billing date
billingAnchorDate Original billing date used for recurring calculations

Using explicit TypeScript types helps prevent invalid states such as an unsupported billing cycle or an unknown subscription status.

For this tutorial, we will use USD only. A production application supporting multiple currencies should handle currency conversion and currency-specific minor units separately.

4. Why Financial Applications Should Avoid Floating-Point Money

JavaScript numbers use floating-point arithmetic.

This can create unexpected results when performing decimal calculations.

console.log(0.1 + 0.2); 

Output:

0.30000000000000004 

For ordinary applications, this may not be particularly important.

For financial applications, repeatedly combining decimal amounts can introduce rounding inconsistencies.

One common solution is to store monetary values as integers representing their smallest currency unit.

For USD, that unit is cents.

$15.00 = 1500 cents $11.00 = 1100 cents $99.00 = 9900 cents 

Instead of storing a subscription as:

const amount = 15.99; 

Store it as:

const amountMinor = 1599; 

The application can perform integer-based calculations and convert the amount into a formatted currency string for presentation.

Create a currency formatting function:

function formatCurrency(amountMinor: number): string { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amountMinor / 100); } console.log(formatCurrency(1599)); 

Output:

$15.99 

Integer-based storage avoids many common decimal arithmetic problems.

However, applications should still validate that amounts remain within JavaScript's safe integer range.

5. Creating Sample Subscription Data

Create src/subscriptions.ts.

import type { Subscription } from "./types"; export const subscriptions: Subscription[] = [ { id: "sub-001", name: "Video streaming", amountMinor: 1500, currency: "USD", billingCycle: "monthly", category: "Entertainment", status: "active", nextRenewalDate: "2027-01-10", billingAnchorDate: "2026-12-10" }, { id: "sub-002", name: "Music streaming", amountMinor: 1100, currency: "USD", billingCycle: "monthly", category: "Entertainment", status: "active", nextRenewalDate: "2027-01-15", billingAnchorDate: "2026-12-15" }, { id: "sub-003", name: "Cloud storage", amountMinor: 9900, currency: "USD", billingCycle: "yearly", category: "Productivity", status: "active", nextRenewalDate: "2027-06-20", billingAnchorDate: "2026-06-20" }, { id: "sub-004", name: "Design software", amountMinor: 1200, currency: "USD", billingCycle: "monthly", category: "Productivity", status: "paused", nextRenewalDate: null, billingAnchorDate: "2026-10-12" } ]; 

Notice that we have included both monthly and annual subscriptions.

We have also included a paused subscription to demonstrate how subscription status affects spending calculations.

All prices and renewal dates in this tutorial are illustrative.

6. Calculating Monthly and Annual Subscription Costs

A subscription tracker needs a common basis for comparing subscriptions with different billing cycles.

For example:

  • A $15 monthly subscription costs $180 annually.
  • An $11 monthly subscription costs $132 annually.
  • A $99 annual subscription has an equivalent monthly cost of $8.25.

We can normalize these subscriptions by calculating their annual costs first.

Create src/calculations.ts.

import type { Subscription } from "./types"; export function getAnnualCostMinor( subscription: Subscription ): number { const { amountMinor } = subscription; if ( !Number.isSafeInteger(amountMinor) || amountMinor < 0 ) { throw new Error("Invalid subscription amount"); } if (subscription.status !== "active") { return 0; } const annualCost = subscription.billingCycle === "monthly" ? amountMinor * 12 : amountMinor; if (!Number.isSafeInteger(annualCost)) { throw new Error("Annual cost exceeds safe range"); } return annualCost; } 

Next, calculate the total annual cost of all active subscriptions.

export function getTotalAnnualCostMinor( subscriptions: Subscription[] ): number { return subscriptions.reduce((total, subscription) => { const nextTotal = total + getAnnualCostMinor(subscription); if (!Number.isSafeInteger(nextTotal)) { throw new Error("Total exceeds safe integer range"); } return nextTotal; }, 0); } 

The monthly equivalent can then be calculated from the annual total.

export function getMonthlyEquivalentMinor( subscriptions: Subscription[] ): number { return Math.round( getTotalAnnualCostMinor(subscriptions) / 12 ); } 

Calculating the annual total first avoids rounding each individual annual subscription before combining them.

This is useful when an annual subscription cannot be divided evenly into twelve months.

Example calculation

Subscription Monthly equivalent Annual cost
Video streaming $15.00 $180.00
Music streaming $11.00 $132.00
Cloud storage $8.25 $99.00
Paused design software $0.00 $0.00
Total $34.25 $411.00

The resulting annual cost is:

$180 + $132 + $99 = $411 

The equivalent monthly cost is:

$411 ÷ 12 = $34.25 

Subscription cost calculation flow showing how monthly and annual billing plans produce an estimated monthly cost of $34.25 and an annual cost of $411.

Figure 2: A subscription cost calculation flow showing how monthly and yearly billing plans are combined to produce an equivalent monthly cost of $34.25 and an annual cost of $411.

An important distinction is that the monthly equivalent is a budgeting estimate.

It does not mean the user will actually be charged $34.25 every month.

The annual cloud storage payment, for example, is charged as a single $99 transaction on its renewal date.

For financial calculations, keep the exact annual total rather than reconstructing it from an already rounded monthly equivalent.

7. Generating a Subscription Spending Summary

Once the calculation functions are available, we can generate a summary for the application's dashboard.

Add the following to src/calculations.ts.

export interface SubscriptionSummary { totalSubscriptions: number; activeSubscriptions: number; pausedSubscriptions: number; canceledSubscriptions: number; monthlyEquivalentMinor: number; annualTotalMinor: number; } export function generateSubscriptionSummary( subscriptions: Subscription[] ): SubscriptionSummary { const annualTotalMinor = getTotalAnnualCostMinor(subscriptions); return { totalSubscriptions: subscriptions.length, activeSubscriptions: subscriptions.filter( (item) => item.status === "active" ).length, pausedSubscriptions: subscriptions.filter( (item) => item.status === "paused" ).length, canceledSubscriptions: subscriptions.filter( (item) => item.status === "canceled" ).length, monthlyEquivalentMinor: Math.round( annualTotalMinor / 12 ), annualTotalMinor }; } 

Using our sample data:

const summary = generateSubscriptionSummary(subscriptions); console.log(summary); 

Expected output:

{ "totalSubscriptions": 4, "activeSubscriptions": 3, "pausedSubscriptions": 1, "canceledSubscriptions": 0, "monthlyEquivalentMinor": 3425, "annualTotalMinor": 41100 } 

The user interface can convert these minor currency units into human-readable amounts.

Active subscriptions: 3 Paused subscriptions: 1 Estimated monthly cost: $34.25 Estimated annual cost: $411.00 

Keeping calculation logic independent from the user interface makes it easier to reuse the same financial rules throughout the application.

8. Calculating Recurring Renewal Dates

Recurring dates introduce another interesting problem.

Consider a subscription that renews on January 31.

What happens when the next billing month is February?

February does not have 31 days.

Simply adding one month using JavaScript's native date methods can cause the resulting date to overflow into March.

To avoid this, we need an explicit month-end policy.

For this tutorial, our policy is:

If the original billing day does not exist in the target month, use the final day of that month.

Examples:

Billing anchor Next billing period Result
January 31, 2027 February 2027 February 28, 2027
January 31, 2027 March 2027 March 31, 2027
February 29, 2028 February 2029 February 28, 2029

Notice that March returns to the original billing day.

We should preserve the original billing anchor instead of permanently changing the billing day to the 28th.

Create src/renewals.ts.

import type { BillingCycle, Subscription } from "./types"; function parseDateOnly(value: string): Date { if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) { throw new Error("Invalid date format"); } const date = new Date(`${value}T00:00:00.000Z`); if ( Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value ) { throw new Error("Invalid calendar date"); } return date; } export function calculateRenewalDate( anchorDate: string, billingCycle: BillingCycle, completedCycles: number ): string { if ( !Number.isSafeInteger(completedCycles) || completedCycles < 0 ) { throw new Error("Invalid billing cycle count"); } const anchor = parseDateOnly(anchorDate); const monthsToAdd = billingCycle === "monthly" ? completedCycles : completedCycles * 12; const target = new Date(anchor.getTime()); target.setUTCDate(1); target.setUTCMonth( anchor.getUTCMonth() + monthsToAdd ); if (Number.isNaN(target.getTime())) { throw new Error("Renewal date is out of range"); } const monthEnd = new Date(target.getTime()); monthEnd.setUTCMonth( monthEnd.getUTCMonth() + 1, 0 ); const billingDay = Math.min( anchor.getUTCDate(), monthEnd.getUTCDate() ); target.setUTCDate(billingDay); return target.toISOString().slice(0, 10); } 

Now let's test the renewal calculation.

console.log( calculateRenewalDate("2027-01-31", "monthly", 1) ); console.log( calculateRenewalDate("2027-01-31", "monthly", 2) ); console.log( calculateRenewalDate("2028-02-29", "yearly", 1) ); 

Expected output:

2027-02-28 2027-03-31 2029-02-28 

This approach handles shorter months and leap-year boundaries while preserving the original billing anchor.

Real subscription providers may follow different renewal policies. A production tracker should allow users to correct renewal dates when provider-specific behavior differs from the application's default policy.

9. Finding Upcoming Subscription Renewals

A useful subscription tracker should allow users to identify payments approaching their renewal dates.

For example, users might want to see all active subscriptions renewing within the next seven days.

Add the following function to src/renewals.ts.

export function getUpcomingRenewals( subscriptions: Subscription[], referenceDate: string, daysAhead = 7 ): Subscription[] { if ( !Number.isSafeInteger(daysAhead) || daysAhead < 0 ) { throw new Error("Invalid date range"); } const start = parseDateOnly(referenceDate); const end = new Date(start.getTime()); end.setUTCDate( end.getUTCDate() + daysAhead ); return subscriptions .filter((subscription) => { if ( subscription.status !== "active" || !subscription.nextRenewalDate ) { return false; } const renewalDate = parseDateOnly( subscription.nextRenewalDate ); return ( renewalDate >= start && renewalDate <= end ); }) .sort((a, b) => a.nextRenewalDate!.localeCompare( b.nextRenewalDate! ) ); } 

Using our sample subscriptions:

const upcoming = getUpcomingRenewals( subscriptions, "2027-01-09", 7 ); console.log( upcoming.map((item) => ({ name: item.name, renewalDate: item.nextRenewalDate })) Source:https://dev.to/smartwalt/how-to-build-a-subscription-tracker-with-typescript-nhe

Related posts