# Mortgage calculator

Source: https://help.ruuster.com/idx/recipe-mortgage-calculator

> The listing page's mortgage calculator, from MortgageCalculator and GET /v1/mortgage/estimate, with loan type, term, price, down payment and rate controls, a line-by-line monthly payment, est. badges and the required disclosures.

Under the property details, the listing page shows what the home could cost each month: principal
and interest, property taxes, home insurance, mortgage insurance and HOA dues, in a ring chart and a
list, at today's market rates. The visitor can change the loan type, the term, the price, the down
payment and the rate, and the figures follow. Every figure comes from
[`GET /v1/mortgage/estimate`](https://help.ruuster.com/idx/mortgage-estimate): the browser asks your
own listings route, which adds your secret key on your server, and shows the answer. The page carries
no key. `ListingDetail` shows the calculator when you pass `apiBaseUrl="/api/idx"`.

Your listings route is one file, from the SDK:

```ts
// app/api/idx/[...path]/route.ts
import { createListingsRoute } from "@ruuster/idx/route";

export const GET = createListingsRoute({ basePath: "/api/idx" });
```

On a site builder with no server of its own, the calculator asks `https://idx.ruuster.com/v1` with no
key instead, from an approved website address: [No key in your
pages](https://help.ruuster.com/idx/keys-and-domains) explains both ways.

## What the visitor sees

<figure class="idx-shot"><img src="/idx-docs/screens/ours/mortgage-calculator-1440.png" alt="The mortgage calculator with the first answer for the listing (its own tax and HOA figures, an estimated insurance line), on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>The calculator on a listing page.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/mortgage-calculator-375.png" alt="The mortgage calculator with the first answer for the listing (its own tax and HOA figures, an estimated insurance line), on a phone (375 px wide)" width="375" height="1337" loading="lazy" decoding="async"><figcaption>The calculator on a listing page.</figcaption></figure>

The markup is `static/html/mortgage-calculator.html` in `@ruuster/idx-recipes`. The [HTML and CSS recipe](https://help.ruuster.com/idx/recipe-html-css) shows how to fill it and which stylesheet and script to load.

<figure class="idx-shot"><img src="/idx-docs/screens/ours/mortgage-calculator-ineligible-1440.png" alt="The mortgage calculator for a loan type the scenario does not qualify for (USDA with 5 percent down): the reasons and the mortgage insurance note, on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>A loan the home can't use, with what to change to qualify.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/mortgage-calculator-ineligible-375.png" alt="The mortgage calculator for a loan type the scenario does not qualify for (USDA with 5 percent down): the reasons and the mortgage insurance note, on a phone (375 px wide)" width="375" height="1597" loading="lazy" decoding="async"><figcaption>A loan the home can't use, with what to change to qualify.</figcaption></figure>

The markup is `static/html/mortgage-calculator-ineligible.html` in `@ruuster/idx-recipes`. The [HTML and CSS recipe](https://help.ruuster.com/idx/recipe-html-css) shows how to fill it and which stylesheet and script to load.

## What it shows

- **Loan type and term**, as two menus. The choices come from the answer's `options`: Conventional,
  FHA, VA, USDA and Jumbo with 30, 20 and 15 years fixed or a 5/6 ARM in the United States, and
  fixed or variable rates with 1 to 10 year terms in Canada.
- **Home price**, from the listing's price, with a slider from $50,000 to $2,500,000 (or three times
  the price, for a higher price) in steps of $5,000 and a field for an exact figure.
- **Down payment** in dollars or percent, 20 percent to start, with the other figure under it, such as
  "$125,000 down".
- **Interest rate**, today's market rate to start, with "Market rate on July 24, 2026" under it. A
  rate the visitor types reads "Your rate" with "Use the market rate" beside it.
- **More options**: the credit score band (United States), the yearly property tax, the yearly home
  insurance and the monthly HOA dues (condo fees in Canada). Each field shows the figure the estimate
  used until the visitor types their own.
- **The monthly payment**: the ring chart with the total and "per month", then each line and the
  total. The HOA line is always there, at $0 when the home has no dues. A line the API estimated
  carries an "est." badge, whose name for screen readers is "Estimated. Enter your own figure under
  More options."
- **When the scenario misses a loan type's rules**, "To qualify for this loan type, adjust the
  scenario:" and the API's sentences, such as the down payment a loan type needs.
- **The mortgage insurance note** when the loan carries mortgage insurance, and "Some rates may be a
  few days old." when the API answers `stale: true`.
- **The disclosures**, every line of the answer's `requiredDisclosures`, in small text under the estimate.

A change waits 350 milliseconds, then asks the API once; a newer change cancels the request before
it. The last estimate stays on screen while the next one loads, and screen readers hear "Updating the
estimate." When a request fails, the calculator shows "The estimate could not load. Please try again
in a moment." with a "Try again" button.

## When the page shows it

`ListingDetail` shows the calculator under the property details when all of these hold:

- you pass `apiBaseUrl` (your listings route, such as `/api/idx`);
- you leave `mortgage` unset or `true` (`mortgage={false}` leaves it off the page);
- the listing has a price, and it is neither sold nor a rental or lease.

It starts from `mortgagePrefill(listing)`: the price, the home's state and ZIP code, the HOA dues
from the listing's details turned into a monthly figure (yearly, quarterly and monthly dues), and the
yearly tax when the listing carries it.

## What the browser calls

| When | Request | Key | Cached |
|---|---|---|---|
| When the page loads, and after each change | `GET /v1/mortgage/estimate`, through your listings route | your secret key, added on your server | 5 minutes at Ruuster's edge for the same scenario |

The estimate costs no daily units. The request for this listing's first estimate:

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/mortgage/estimate" \
  --data-urlencode price=625000 \
  --data-urlencode downPaymentPercent=20 \
  --data-urlencode state=GA \
  --data-urlencode zip=30308 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.mortgage({
  price: 625000,
  downPaymentPercent: 20,
  state: "GA",
  zip: "30308",
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/mortgage/estimate",
    params={
        "price": "625000",
        "downPaymentPercent": "20",
        "state": "GA",
        "zip": "30308",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'price' => '625000',
    'downPaymentPercent' => '20',
    'state' => 'GA',
    'zip' => '30308',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/mortgage/estimate' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

The answer holds `options` for the menus, `inputs` as the API used them, `rate`, `loan`, `monthly`
with each line and its `provenance` (`actual` or `estimated`), `eligible` with
`ineligibleReasons`, `mortgageInsuranceNote`, `requiredDisclosures` and `stale`. The
[reference page](https://help.ruuster.com/idx/mortgage-estimate) lists every parameter and field.

## A first answer from your server

The calculator asks for its first estimate in the browser. To have the figures in the HTML from the
start, ask `idx.mortgage()` on your server and pass the answer as `initialEstimate`. The calculator
shows it in the first HTML, then refreshes it in the browser and follows every change.

```tsx
// The mortgage calculator on your own layout, with its first answer rendered on your server: the
// figures are in the HTML from the start, and the browser asks your listings route for a new
// estimate as the visitor moves a slider. Every figure comes from GET /v1/mortgage/estimate.
import type { ListingDetail as ListingDetailData } from "@ruuster/idx";
import { createClient } from "@ruuster/idx";
import { MortgageCalculator, mortgagePrefill } from "@ruuster/idx-recipes";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY, baseUrl: process.env.IDX_BASE_URL || undefined });

export async function ListingMortgage({ listing }: { listing: ListingDetailData }) {
  const p = mortgagePrefill(listing);
  if (!p.price) return null;
  const first = await idx.mortgage({ price: p.price, state: p.state || null, zip: p.zip, hoaMonthly: p.hoaMonthly, propertyTaxAnnual: p.propertyTaxAnnual });
  return (
    <MortgageCalculator
      baseUrl="/api/idx"
      price={p.price}
      state={p.state}
      zip={p.zip}
      hoaMonthly={p.hoaMonthly}
      propertyTaxAnnual={p.propertyTaxAnnual}
      initialEstimate={first.ok ? first.data : null}
    />
  );
}
```

`idx.mortgage()` and `toMortgageQueryString()` are in [the TypeScript SDK](https://help.ruuster.com/idx/guide-sdk).
The calculator builds the same query string as `toMortgageQueryString()`, so a scenario your server
asked for and the same scenario from the browser are one cached answer.

## Props

| Prop | Type | Required | What it does |
|---|---|---|---|
| `price` | `number` | Yes | The listing's price: `mortgagePrefill(listing).price` |
| `state` | `string \| null` | One of the two | The home's state or province code |
| `zip` | `string \| null` | One of the two | The home's ZIP code |
| `hoaMonthly` | `number \| null` | No | The monthly HOA dues |
| `propertyTaxAnnual` | `number \| null` | No | The yearly property tax |
| `insuranceAnnual` | `number \| null` | No | The yearly home insurance |
| `initial` | `{ downPaymentPercent?, loanType?, termYears? }` | No | The starting choices. Default 20 percent down and the country's default loan |
| `baseUrl` | `string` | No | Your listings route, such as `/api/idx`. Default `https://idx.ruuster.com/v1`, with no key |
| `debounceMs` | `number` | No | The pause after a change before the request. Default 350 |
| `initialEstimate` | `MortgageEstimate \| null` | No | A first answer from your server |
| `publishableKey` | `string` | No | Leave out. Kept only for pages built before keyless requests |

On `ListingDetail`, `apiBaseUrl` and `mortgage` control it; the listing fills the rest.

## Rules this screen follows

**MUST**

- Show every line of `requiredDisclosures` under the estimate. Showing them is a condition of using the
  rates.
- Mark each estimated line, so the visitor knows which figures to replace with their own.
- Show the figures the API answers. The browser never computes a payment itself.

**NEVER**

- Present the estimate as a loan offer, a quote or an approval.
- Show the calculator on a sold home or a rental.
- Change the wording of the disclosures.

## Without React

The static listing page prints the calculator with a first answer from the server, and
`ruuster-idx.js` asks for a new one as the visitor changes it, through the address in
`data-rw-base-url` on the calculator: your listings route, or `https://idx.ruuster.com/v1` with no key
on a site builder. The hooks
(`data-rw-mortgage`, `data-rw-mortgage-field`, `data-rw-mortgage-out` and the rest) are in
`static/HOOKS.md`. See [Build without React](https://help.ruuster.com/idx/recipe-html-css).
