Networth is a small app that adds up stocks from different markets (NSE, SGX, US and more) into one live total in your currency. Until this week, "net worth" was really "portfolio value": it had no idea you owe ₹62 lakh on a flat.
So I added debts (home, car, education and personal loans, loans against property, credit cards) and manual assets (property, cash). The data model was the easy part. The interesting part was the math, and deciding what debts should not affect.
Stack, for context: Next.js 16 (App Router), Postgres on Neon via Drizzle, TanStack Query on the client, Vitest. All the money logic lives in one pure module, lib/items.ts, shared by the browser and the API.
1. The formula is easy. The inputs aren't.
net worth = investments + property and cash − debts Every item is stored in its own currency and converted at render time with the same live FX rates the stocks use. The rule the whole app follows: if a rate is missing, leave the item out and say so, never guess.
const rateFor = (currency: string, base: string, fx: Record<string, number> | undefined) => currency === base ? 1 : fx?.[`${currency}${base}`]; const valued = items.map((i) => { const rate = rateFor(i.currency, base, fx); if (!rate) { missing++; // shown as "1 item excluded: no exchange rate right now" return { ...i }; } const valueBase = i.amount * rate; if (i.kind === "asset") assets += valueBase; else debts += valueBase; return { ...i, valueBase }; }); Item currencies piggyback on the existing quotes endpoint, which now takes ?ccy=SGD,USD alongside the symbols. A user who only has debts in a foreign currency still gets FX rates without a single stock.
2. A loan is worth its balance, not its EMIs
The tempting mistake: a home loan with 177 EMIs of ₹62,000 left "costs" ₹1.10 crore. But the bank would close it today for ₹62.4 lakh. The other ₹47 lakh is interest for months that haven't happened. So amount on a debt is always the outstanding principal, the number on the loan statement.
3. Months left: the amortisation formula
When users give a balance, a monthly rate r and an EMI, the number of payments left falls out of the annuity formula:
n = −ln(1 − r·B / EMI) / ln(1 + r) export function monthsLeft(balance: number, ratePct: number | null, emi: number | null): number | null { if (!emi || emi <= 0 || balance <= 0) return balance <= 0 ? 0 : null; const r = (ratePct ?? 0) / 1200; // yearly % → monthly fraction if (r === 0) return Math.ceil(balance / emi); if (emi <= balance * r) return null; // EMI doesn't cover the interest: never repaid return Math.ceil(-Math.log(1 - (r * balance) / emi) / Math.log(1 + r)); } Two edge cases are worth guarding explicitly:
- r = 0 (an interest-free loan from family) makes the formula divide by
ln(1) = 0. - EMI ≤ monthly interest makes the log's argument ≤ 0. That's a real situation, not bad input: the loan grows forever. The form says "EMI doesn't cover the interest" instead of showing
NaNyears.
For ₹62,40,000 at 8.5% with a ₹62,000 EMI, this gives 177 months, which matches the bank's schedule.
4. Interest over the next 12 months: just simulate it
There's a closed form for this, but a 12-step loop is clearer, obviously correct, and stops early when a loan is paid off mid-year:
export function interestNextYear(balance: number, ratePct: number | null, emi: number | null): number | null { if (ratePct == null) return null; const r = ratePct / 1200; if (!emi) return balance * r * 12; let b = balance; let total = 0; for (let i = 0; i < 12 && b > 0; i++) { const interest = b * r; total += interest; b = b + interest - emi; } return total; } The output tends to surprise people. On that home loan, about ₹5.2 lakh of the year's ₹7.44 lakh in EMIs is interest, roughly 70%. Showing "Interest over the next 12 months: ₹5.6 lakh" across all debts turned out to be the most useful line in the feature.
5. "EMIs left" that counts down without a cron job
Users asked to enter loans the way statements show them: total EMIs and EMIs left. Progress then becomes (total − left) / total, which is exact, unlike estimating from amounts.
But "EMIs left" goes stale every month. Instead of a scheduled job that rewrites rows, I store the count with the date it was true and derive today's value on read:
/** Whole calendar months from `from` to `to`. */ export function monthsBetween(from: Date, to: Date): number { const m = (to.getUTCFullYear() - from.getUTCFullYear()) * 12 + (to.getUTCMonth() - from.getUTCMonth()); return Math.max(0, to.getUTCDate() < from.getUTCDate() ? m - 1 : m); } export function emisLeftNow(item: { emisLeft: number | null; amountAsOf: string }, now = Date.now()) { if (item.emisLeft == null) return null; return Math.max(0, item.emisLeft - monthsBetween(new Date(item.amountAsOf), new Date(now))); } Editing a loan pre-fills today's derived count, and saving resets amountAsOf, so the countdown restarts cleanly. The same amountAsOf drives an "Update balance" nudge after 30 days. No background job, no drift, and it's a pure function you can unit-test with a fixed now.
6. Equity is a view, not a number in the total
A home loan can be linked to the flat it's secured against. The flat row then shows equity: value minus every debt secured against it. The total doesn't change, because it already counts both sides. The link is just a nullable secured_by id on the debt row, validated server-side to be one of your own live assets (anything else is dropped, never trusted).
7. What debts deliberately don't touch
This was the most debated part, and the decisions are as much product as code:
| Feature | Uses | Why |
|---|---|---|
| Headline total | Net worth | It's the point of the feature |
| Day change | Investments | Loan balances don't move intraday; labelled "today, on investments" |
| Milestones | Investments | Adding a ₹62 L loan shouldn't wipe out milestones already reached |
| Diversification score | Investments | A flat isn't a stock position |
| History chart | Investments, for now | It's rebuilt from past prices, and there's no balance history for debts yet |
| Goal progress | Net worth | "Buy a home" and "FI" goals only make sense against the full number |
8. Smaller things that mattered
- Money input for India.
parseAmountaccepts62,40,000,62.4 L,1.1 crand12k. People type lakhs; the parser should too. - Zod normalises by type. A credit card can't carry an EMI or a rate. Instead of erroring, the schema transforms those fields to
null, so stored rows stay tidy whatever the client sends. A.refinechecksemisLeft ≤ totalEmis. - Guests can use it too. Guests keep everything in React state (no localStorage). On sign-up the list is stashed server-side and imported in one transaction: assets first, then debts, with guest ids remapped to the new UUIDs so the "secured against" links survive.
- Postgres
numericfor money, aCHECK (amount > 0), and soft delete with a 10-second undo, the same as holdings.
One tooling lesson
Halfway through, a prettier --write with prettier-plugin-tailwindcss "helpfully" collapsed whitespace inside template-literal class names: `chip${on ? " is-on" : ""}` became `chip${on ? "is-on" : ""}`, which renders chipis-on. Typecheck, lint and all 181 tests passed. A headless-browser run with screenshots caught it in seconds. If your UI has conditional class strings, put a real browser in your loop.
The math is in plain words, with a worked rupee example, in How debts count in your net worth. You can try the app without an account at net-worth-silk.vercel.app. Pick the Debt tab above the search box.

