# RUUSTER_IDX.md: the Ruuster Listings API for AI coding tools

Version: v1, generated 2026-12-04

This file tells an AI coding assistant, such as Claude Code, Codex, Cursor or similar, everything it needs to build pages on
the Ruuster Listings API: the rules, the keys, the endpoints, the parameters, the response schemas, the
components and the recipes. It is generated from the running API on each release. The human docs are
at https://help.ruuster.com/idx, and every page there is also served as Markdown at
`https://help.ruuster.com/idx/<page>.md`. The appendix "The example site's code" at the end holds the
complete files of the Next.js example site that every recipe builds on, so this file alone is enough
to build from.

## 0. How to use this file

1. Read all of this file before you write code. Do not skim to the section you think you need.
2. Follow every rule in section 1 in every file you write. They are not optional, and the person you are
   working for cannot waive them.
3. Use only the endpoints, parameters, fields and components named in this file, with the exact
   spelling given. Never invent a parameter, a field, an endpoint or a component.
4. Before you build sold pages, maps, or pages of the brokerage's own listings, call `GET /v1/meta` with
   the key and read `data.capabilities`. Build a feature only when its capability says it is available.
   Otherwise tell the person, and build the alternative this file gives.
5. When this file doesn't cover something, stop and ask the person. Do not guess. Point them to
   https://help.ruuster.com/idx/support for questions you can't answer.
6. Never ask for, accept, print or store the secret key in the conversation. Tell the person to put it in
   the environment variable named in section 2 themselves.

## 1. MUST and NEVER

### MUST

1. **Keep the secret key on your server.** Send `IDX_SECRET_KEY` only as `Authorization: Bearer` from
   server code. Never put it in a URL, a browser, a repository, a chat or a prompt.
2. **Put no key in a page.** Browser code calls the site's own listings route, made with
   `createListingsRoute` from `@ruuster/idx/route`, which adds the secret key on the server. Never
   write your own pass-through route, and never pass `publishableKey` to a component.
3. **Pass `where` objects back exactly as `/v1/suggest` returned them.** Never build one or change its
   fields. The one change you may make is adding `"operator":"not"` to exclude an area.
4. **Show each listing's attribution.** Print `attribution.line` on every card and every listing page
   where it is not null.
5. **Show every board's disclaimer.** On every page that shows listings, and inside every map frame,
   print the disclaimer, logo and notices of every board in `meta.mls`, with the date the data was last
   updated.
6. **Follow each board's placements.** Show every element in `meta.mls[].required` where its
   `placement` says: on the card, on the listing page, once on the page or on the map.
7. **Keep hidden addresses hidden.** Use the address, slug and alt text exactly as the API returns
   them. When `address.hidden` is true, show no street, no unit, no map pin and no coordinates
   anywhere: not in the page, the URL, the head tags, the JSON-LD, analytics events or CRM payloads.
8. **Answer the listing's status.** 410 when the API answers 410, 404 when it answers 404, and a 301 from
   an outdated slug to the current one. Drop removed listings from your sitemap.
9. **Handle 429 and 503 calmly.** Wait `Retry-After` seconds before you try again. In server rendering,
   throw, so your cache keeps serving the last good page.
10. **Check `/v1/meta` capabilities before you build on sold data, maps or your own listings,** and
    build those features only where they are available.
11. **Send forms to your own server, then to your own CRM.** Consent boxes start unchecked, and the lead
    source is your site's name.
12. **Follow fair housing in every word.** Describe homes, places and amenities, never people or who a
    place suits, and show the Equal Housing Opportunity notice.
13. **Print JSON-LD safely,** with `<JsonLd>` in React or `jsonLdHtml` exactly as returned.

### NEVER

1. **Never store listings beyond a cache.** Don't copy listings, photos or their fields into a
   database of your own, and never keep showing a listing after the API stops returning it.
2. **Never add data the API didn't return.** Don't show a field it left out, and don't fill one from
   another source.
3. **Never show sold data the API didn't return.** Don't keep sold listings or sold prices from earlier
   answers once they leave the API.
4. **Never call a CRM from the browser.** Lead data goes from your form to your server, and from your
   server to your CRM.
5. **Never put calls to action on result cards.** Tour and contact buttons belong on the listing page.
6. **Never use attribution contact details to route leads.** An agent's email or phone in
   `attribution.contact` is for display only.
7. **Never fetch pages in parallel,** and never keep more than four calls in flight per key.
8. **Never let staging or visitor-filtered search pages be indexed.**
9. **Never rank schools or describe who lives in a place as a reason to buy.**

### Fair housing, for any text you write

When you write area copy, listing summaries, headings, meta descriptions, alt text, ads or emails:
describe the home, the place and its amenities (rooms, finishes, lot, views, parks, transit, shops,
commute times, schools by name and boundary). Never describe the people who live in a place or who a
home or place would suit. Never use words about families, children, age, religion, nationality,
disability, gender or safety to describe a place, never call a place private or restricted, and never
rank schools as a reason to buy. If the person asks for such copy, explain the rule and offer factual
copy instead.

## 2. Keys and environment names

- The API is HTTPS and JSON, GET only. Every path in this file starts with `/v1` on the host
  `idx.ruuster.com`, for example `https://idx.ruuster.com/v1/status`.
- The **secret key** (`idx_sk_…`) is the one key the site uses. It is for server code and is sent as
  `Authorization: Bearer idx_sk_…`. Some endpoints need it (see section 3). A secret key in a URL answers 400 `secret_key_in_url`, and
  one sent from a browser answers 403 `secret_key_in_browser`; both flag the key.
- **No key goes in a page.** Browser code (the search box, the filter choices, the mortgage
  calculator) calls the site's own listings route, which adds the secret key on the server and passes
  on only what a page may ask for; everything only a secret key may do answers 404 through it. It
  limits each visitor (120 requests a minute by IP address, option `perVisitorPerMinute`) and lets a
  CDN keep answers for `cacheSeconds` (default 60). It runs anywhere that hands it a standard
  `Request` (Next.js, Astro, SvelteKit, Remix, Hono, Cloudflare Workers, Vercel and Netlify
  functions):

  ```ts
  // app/api/idx/[...path]/route.ts (Next.js App Router)
  import { createListingsRoute } from "@ruuster/idx/route";

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

  Point the components at it: `baseUrl="/api/idx"` on `SearchBox`, `Filters`, `FiltersDrawer`
  and `MortgageCalculator`, `apiBaseUrl="/api/idx"` on `ListingDetail`, and
  `data-rw-base-url="/api/idx"` on plain HTML widgets.
- **A site with no server that runs JavaScript** (WordPress, Squarespace, Webflow, Wix, or a PHP,
  Python, Ruby or Go server) uses the widgets with no key: `data-rw-base-url` is
  `https://idx.ruuster.com/v1` or left out. The API recognizes the account from the page's website
  address, which must be on the account's allowed domains and approved for its MLSs. A page on
  `localhost` can't be recognized this way (403 `origin_not_allowed`): build locally through the
  listings route, or test on a staging address added to the account.
- The person starts with free sandbox keys on sample listings in Atlanta, GA and Dallas, TX. The site
  uses the sandbox secret key (`idx_sk_test_…`). They come from the person's console, under Keys and domains. Live keys
  replace them when the person goes live, and the code stays the same. Every answer to a sandbox key
  has `meta.sandbox: true`.
- A call with no key and no `Origin` header is refused with 403 `origin_required`. Server code always
  sends the secret key.
- A staging site on live keys must be behind a password or send `X-Robots-Tag: noindex` on every
  response.
- Use these names exactly. Rename only the browser variables (the Google Maps key and Map ID) to the
  framework's prefix: Astro and SvelteKit `PUBLIC_`, Vite and Remix on Vite `VITE_`, Nuxt
  `NUXT_PUBLIC_`, Next.js `NEXT_PUBLIC_`. Never give `IDX_SECRET_KEY` a browser prefix, and never
  pass `NEXT_PUBLIC_IDX_KEY` to a page or a component: the site reads only `IDX_SECRET_KEY`.

| Name | Where | What |
|---|---|---|
| `IDX_SECRET_KEY` | Server only | Your secret key (idx_sk_…), sent as Authorization: Bearer. |
| `NEXT_PUBLIC_IDX_KEY` | Not used by new pages | Leave it unset. Pages carry no key: they call your own route made with @ruuster/idx/route. Only pages built before keyless requests read it. |
| `IDX_BASE_URL` | Server, optional | Leave it unset in production. The examples' offline runs set it to a local server. |
| `SITE_ORIGIN` | Server | Your site's origin, such as https://www.example.com, for canonical URLs and pageHref. |
| `SITE_NAME` | Server | Your site's name, sent as the lead source to your CRM. |
| `SITE_AGENT_NAME` | Server | Your own agent or office, named on the listing page's contact card, mobile bar and contact dialog. |
| `SITE_AGENT_PHOTO_URL` | Server, optional | That agent's photo, an https URL. |
| `SITE_AGENT_PHONE` | Server, optional | That agent's phone number, for the Call buttons. |
| `SITE_AGENT_EMAIL` | Server, optional | That agent's email address, for the Email buttons. |
| `SITE_AGENT_LICENSE` | Server, optional | That agent's license number, shown under Agent information. |
| `NEXT_PUBLIC_GOOGLE_MAPS_KEY` | Browser | Your own Google Maps key. |
| `NEXT_PUBLIC_GOOGLE_MAP_ID` | Browser | Your own Google Maps Map ID. |
| `NEXT_PUBLIC_GTM_ID` | Browser | Your Google Tag Manager container ID, which starts with GTM-. |
| `RUUSTER_WEBHOOK_SECRET` | Server | The signing secret of your listing-change webhook. |
| `FUB_API_KEY` | Server | Your Follow Up Boss API key. |
| `FUB_SYSTEM` | Server | The system name you registered with Follow Up Boss. |
| `FUB_SYSTEM_KEY` | Server | The system key Follow Up Boss gave your registered system. |
| `FUB_COOKIE_SECRET` | Server | A long random string your server uses to sign the cookie that links listing views to a registered visitor. |
| `SIERRA_API_KEY` | Server | Your Sierra Interactive API key. |
| `SURESEND_API_KEY` | Server | Your Sure Send API key. |

## 3. Endpoints

Each line gives the method, the path, who may call it (`publishable` means a page may ask for it,
through the listings route or with no key from an approved address, and server code may call it with
the secret key; `secret` means server code with the secret key only), its units, its edge cache and
its docs page.

| Method | Path | Key | Units | Cache | Page |
|---|---|---|---|---|---|
| GET | /v1/status | no key | free | cached 30 s | https://help.ruuster.com/idx/status |
| GET | /v1/meta | publishable or secret key | free | cached 3600 s | https://help.ruuster.com/idx/meta |
| GET | /v1/filters | publishable or secret key | 1 unit | cached 3600 s | https://help.ruuster.com/idx/filters |
| GET | /v1/filters/options | publishable or secret key | 1 unit | cached 3600 s | https://help.ruuster.com/idx/filters-options |
| GET | /v1/listings | publishable or secret key | 2 units | cached 120 s | https://help.ruuster.com/idx/listings-search |
| GET | /v1/listings/ids | secret key only | 5 units | never cached | https://help.ruuster.com/idx/listings-ids |
| GET | /v1/listings/{listingId} | publishable or secret key | 1 unit | cached 300 s | https://help.ruuster.com/idx/listings-get |
| GET | /v1/listings/{listingId}/photos | publishable or secret key | 1 unit | cached 900 s | https://help.ruuster.com/idx/listings-photos |
| GET | /v1/listings/{listingId}/similar | publishable or secret key | 2 units | cached 600 s | https://help.ruuster.com/idx/listings-similar |
| GET | /v1/listings/{listingId}/history | publishable or secret key | 1 unit | cached 900 s | https://help.ruuster.com/idx/listings-history |
| GET | /v1/agents/{agentMlsId}/production | publishable or secret key | 2 units | cached 3600 s | https://help.ruuster.com/idx/agents-production |
| GET | /v1/suggest | publishable or secret key | 1 unit | cached 3600 s | https://help.ruuster.com/idx/suggest |
| GET | /v1/boundaries/{boundaryId} | publishable or secret key | 1 unit | cached 3600 s | https://help.ruuster.com/idx/boundaries-get |
| GET | /v1/market | publishable or secret key | 2 units | cached 3600 s | https://help.ruuster.com/idx/market |
| GET | /v1/market/snapshot | publishable or secret key | 2 units | cached 3600 s | https://help.ruuster.com/idx/market-snapshot |
| GET | /v1/market/metrics | publishable or secret key | 1 unit | cached 3600 s | https://help.ruuster.com/idx/market-metrics |
| GET | /v1/shapes | publishable or secret key | 1 unit | cached 300 s | https://help.ruuster.com/idx/shapes-list |
| GET | /v1/shapes/{shapeId} | publishable or secret key | 1 unit | cached 600 s | https://help.ruuster.com/idx/shapes-get |
| GET | /v1/collections | publishable or secret key | 1 unit | cached 300 s | https://help.ruuster.com/idx/collections-list |
| GET | /v1/collections/{collectionId} | publishable or secret key | 1 unit | cached 300 s | https://help.ruuster.com/idx/collections-get |
| GET | /v1/collections/{collectionId}/listings | publishable or secret key | 2 units | cached 300 s | https://help.ruuster.com/idx/collections-listings |
| GET | /v1/render/listings | publishable or secret key | 2 units | cached 120 s | https://help.ruuster.com/idx/render-listings |
| GET | /v1/render/listing/{listingId} | publishable or secret key | 1 unit | cached 300 s | https://help.ruuster.com/idx/render-listing |
| GET | /v1/changes | secret key only | 5 units | never cached | https://help.ruuster.com/idx/changes |
| GET | /v1/beacon | publishable or secret key | free | never cached | https://help.ruuster.com/idx/beacon |
| GET | /v1/events | publishable or secret key | free | never cached | https://help.ruuster.com/idx/events |
| GET | /v1/mortgage/estimate | publishable or secret key | free | cached 3600 s | https://help.ruuster.com/idx/mortgage-estimate |
| GET | /v1/usage | secret key only | free | never cached | https://help.ruuster.com/idx/usage |
| GET | /v1/account/billing | secret key only | free | never cached | https://help.ruuster.com/idx/account-billing |
| GET | /v1/public-records/lookup | secret key only | 1 unit | never cached | https://help.ruuster.com/idx/public-records-lookup |
| GET | /v1/public-records/market | secret key only | 1 unit | never cached | https://help.ruuster.com/idx/public-records-market |
| GET | /v1/public-records/{recordId}/history | secret key only | 1 unit | never cached | https://help.ruuster.com/idx/public-records-history |
| GET | /v1/sandbox/public-records/lookup | secret key only | 1 unit | never cached | https://help.ruuster.com/idx/sandbox-public-records-lookup |
| GET | /v1/sandbox/public-records/{recordId}/history | secret key only | 1 unit | never cached | https://help.ruuster.com/idx/sandbox-public-records-history |

Every successful answer is `{ "ok": true, "data": …, "meta": … }`. `meta` holds `brokerageId`,
`freshness.asOf`, `mls` (one compliance block per board in the answer) and `canonical`. Every error is
`{ "ok": false, "error": { "code", "message", "retryable" }, "requestId" }`.

The TypeScript SDK `@ruuster/idx` wraps every endpoint:

- Install `npm install @ruuster/idx @ruuster/idx-recipes`. Both packages ship TypeScript sources, so
  in Next.js add `transpilePackages: ["@ruuster/idx", "@ruuster/idx-recipes"]` to `next.config.mjs`.
- `createClient({ secretKey, baseUrl, detailHref, siteOrigin, fetch, retries, maxRetryAfterSec, next })`.
  Pass `secretKey` only in server code; it throws in a browser. Leave `baseUrl` unset in production.
  In the browser, call the listings route with `fetch` (such as `/api/idx/suggest?q=…`).
- Methods: `idx.status()`, `idx.meta()`, `idx.search(query)`, `idx.get(listingId, query)`,
  `idx.similar(listingId, query)`, `idx.suggest(query)`, `idx.boundary(boundaryId)`, `idx.market(query)`,
  `idx.ids(query)`, `idx.changes(query)`, `idx.collectionListings(collectionId, query)`,
  `idx.request(path, query)` for any other endpoint, and `idx.toMetadata(head)`.
- Every method returns `{ ok: true, status, data, meta, etag, headers }` or
  `{ ok: false, status, error, requestId, headers }`. It never throws for an HTTP error. Check `r.ok`
  and branch on `r.error.code`. A network failure has status 0 and the code `network_error`.
- After `r.ok`, `meta` is always there (only `idx.status()` answers `meta: null`), so write
  `r.meta.mls`, with no null check.
- `idx.search(query)` without `view` answers cards (`SearchResult<ListingCard>`), which `ListingGrid`
  and `AreaMap` take. Spread `fromSearchParams(searchParams)` into the query, or type the query as
  `Omit<SearchQuery, "view">`; a variable typed as plain `SearchQuery` answers the union of all three
  listing shapes.
- `idx.similar(id)` answers `data.listings` as `{ listing, why }[]`. Pass
  `r.data.listings.map((s) => s.listing)` to `ListingGrid`.
- Canonical URLs, card `href`s and JSON-LD URLs come back on the site's live domain (the first
  non-localhost domain on the account's allowed list, the domain of the detail-page template), even when the site runs on
  `localhost`. `siteOrigin` only makes a relative URL absolute. Sitemaps, `robots.txt` and the form
  routes use `SITE_ORIGIN`.
- `fmt.date` reads a date-only value, or a time of exactly midnight UTC such as `closeDate`, as that
  day in every time zone.
- It retries 429 and 503 after a short `Retry-After` by itself.
- Helpers: `fromSearchParams` (a page URL in the API's names to a query), `fromWidgetSearchParams` (the
  Ruuster widget's URL names to a query), `toQueryString`, `toMetadata`, `listingPath`,
  `parseListingSlug`, `serializeJsonLd`, `photoAttrs`, `breadcrumbJsonLd`, `fmt.usd`, `fmt.change`,
  `fmt.count`, `fmt.sqft`, `fmt.date`, `fmt.openHouse`, `assertDisplayable`, `renderAttribution`,
  `verifyWebhook`.
- The server-only subpath `@ruuster/idx/crm` sends leads to Follow Up Boss, Sierra Interactive and Sure
  Send (section 11).

## 4. Query grammar

- Repeatable parameters are sent once per value (`status=active&status=pending`), never joined with
  commas. Comma-list parameters (`groups`, `filterByMls`, `keys`) take one comma-joined value.
- `where` is one JSON object from `/v1/suggest`, URL-encoded. Repeat it for several areas, up to 20.
  Add `"operator":"not"` to an object to exclude that area.
- A search needs a location (`where`, `zip`, `city`, `state`, `boundariesId`, `bbox`, `polygon` or
  `shape`), unless it asks for `ownListings=1`, `agent` or `office`. Do not combine `ownListings`,
  `agent` or `office` with an included `where` or a `boundariesId`.
- `bbox` is `south,west,north,east`. `polygon` is `lat,lng,lat,lng,…`.
- Advanced filters are `f.<key>`, `f.<key>Min`, `f.<key>Max` and `f.<key>_o`, with keys from
  `/v1/filters` only.
- `status=closed` needs `soldPeriod` and boards that show sold data.
- Search pages with `page` and `limit`. `page` times `limit` can be at most 2,000. Use `data.pages` for
  page links.
- `pageHref` is the page's own URL without paging; send it on every results page you render.
  `indexable` forces the robots value.
- An unknown parameter, or a non-repeatable parameter sent twice, answers 400 `invalid_parameter`.

### GET /v1/status

No query parameters.

### GET /v1/meta

- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).

### GET /v1/filters

- `keys` (string, comma list): Only these filter keys (a comma list of filter key names). At most 50 values.
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).

### GET /v1/filters/options

- `filterKey` (string, required): The filter key whose options to list (a key from /v1/filters).
- `filterType` (enum) values text, keyword, boolean, number, date, integer, long, short, byte, float, double, half_float, scaled_float: The widget's filter type hint (the numeric index type names integer, long, short, byte, float, double, half_float and scaled_float read as number). Accepted, never trusted: the API picks the field from its own filter definitions.
- `filterByMls` (string, comma list): Only options from these boards: a comma list of MLS search names inside this key's scope. At most 20 values.
- `filterByValue` (string): Type-ahead text: only options containing it (case-insensitive). At most 60 characters.
- `filters` (json): The current search's other filters, as a JSON object { key: value | [values] } of at most 20 public filter keys, so the options reflect them. At most 2048 characters.
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).

### GET /v1/listings

- `where` (json, repeat): A location, as one JSON object exactly as /v1/suggest returned it in `where` (opaque: pass it back unchanged). Repeat for several areas (OR). An object with "operator":"not" excludes that area. A search needs where, near, bbox, polygon, boundariesId, zip, city, state or shape (or ownListings / agent / office). A boundary id is matched only under its own type's source. A listing-id or exact-address pick is answered as is: it matches wherever it is, and search filters such as price and beds apply to the areas in the search, not to the pick. Polygon and excluded locations don't narrow a pick either (a search of picks only plus either is 400; bbox does narrow them). Agent, office and MLS-area sources are built by the API only: use agent, office or ownListings. At most 20 values.
- `bbox` (string): A map box: south,west,north,east in decimal degrees (Google LatLngBounds.toUrlValue order). At most 20° on a side.
- `polygon` (string, repeat): A drawn area: lat,lng,lat,lng,… (at least three points). Repeat for several rings; at most 200 vertices in all.
- `boundariesId` (uuid): A platform boundary id (neighborhood, county, subdivision, area, community) from a /v1/suggest result; matched as that where object would be. A ZIP boundary id is 422: use a zip row from /v1/suggest instead. An unknown id is 404.
- `zip` (string): A five-digit ZIP code, matched exactly (zip=60645), or a Canadian postal code: the full code (zip=T3J 2S7) or its first three characters for the whole area (zip=T3J). Works alone or with city and state; when zip and city are both sent the ZIP is searched and city is left out. Counts as a location.
- `city` (string): A city name, matched exactly, case-insensitive (city=Austin). Works alone (every state the account's boards cover) or with state. Counts as a location. At most 80 characters.
- `state` (string): A two-letter state code, matched exactly (state=TX). Works alone (the whole state) or with city and zip. Counts as a location.
- `shape` (string): One of the account's saved shapes, by id (shp_…, from /v1/shapes): the search covers the area inside it, as one more location OR'd with the others. Counts as a location. A shape is a drawn area: inside it, the results are the listings whose address the MLS lets a site show.
- `near` (string): A point to search around: latitude,longitude in decimal degrees (near=26.142,-81.7948). Listings within radiusMiles of it (default 1 mile). Counts as a location on its own: it can't be combined with any other included location or with ownListings, agent or office (400); bbox, polygon and an excluded where narrow it. A malformed or out-of-range point is 422 location_not_supported. Inside the circle, the results are the listings whose address the MLS lets a site show.
- `radiusMiles` (number 0 to 25, default 1): With near: the radius in miles, more than 0 and at most 25 (default 1; decimals allowed, such as 0.5). Without near, or out of range, it is 422 location_not_supported.
- `priceMin` (integer from 0): Lowest list price, in dollars.
- `priceMax` (integer from 0): Highest list price, in dollars.
- `bedsMin` (integer 0 to 50): At least this many bedrooms.
- `bedsMax` (integer 0 to 50): At most this many bedrooms.
- `bathsMin` (integer 0 to 50): At least this many bathrooms.
- `bathsMax` (integer 0 to 50): At most this many bathrooms.
- `sqftMin` (integer from 0): Smallest living area, in square feet.
- `sqftMax` (integer from 0): Largest living area, in square feet.
- `lotSqftMin` (integer from 0): Smallest lot, in square feet (an acre is 43,560).
- `lotSqftMax` (integer from 0): Largest lot, in square feet.
- `yearMin` (integer 1600 to 2100): Built in or after this year.
- `yearMax` (integer 1600 to 2100): Built in or before this year.
- `hoaMin` (integer from 0): Lowest HOA / association fee, in dollars.
- `hoaMax` (integer from 0): Highest HOA / association fee, in dollars.
- `type` (enum, repeat) values all, ResidentialIncome, ManufacturedInPark, Land, Farm, CommercialSale, CommercialLease, ResidentialLease: Property type (repeat for several). No type = every type the account's boards carry (ResidentialLease only where rentals are enabled); type=all = every type except commercial; subtype narrows residential homes.
- `subtype` (enum, repeat) values house, condo, townhome, co-op, other: Residential subtype (repeat for several).
- `status` (enum, repeat) values active, coming_soon, pending, under_contract, closed: Listing status (repeat for several: status=active&status=pending; there is no all). Default: active. closed needs soldPeriod (format=widget and collections without one get every sold listing inside each board's sold window) and is available only on boards whose rules allow sold data (/v1/meta capabilities.sold).
- `soldPeriod` (enum) values 7d, 1m, 3m, 6m, 12m: With status=closed: closed within the last 7 days (7d) or 1, 3, 6 or 12 months, and never further back than each board's own sold window. Without status=closed it is 400 (saved widget searches and collections ignore it instead, as the Ruuster widget does).
- `openHousePeriod` (enum) values any, today_or_tomorrow, this_weekend, next_7_days: Only listings with an open house in this window (any = any upcoming open house).
- `newConstruction` (boolean (1 or 0)): 1 = new construction only, 0 = exclude it.
- `priceReduction` (enum) values 0d, 1d, 2d, 3d, 7d, 14d, 30d, 90d: Only listings whose price dropped within this many days (0d = today).
- `listedSince` (enum) values 1d, 3d, 7d, 14d, 30d: Only listings first on the market on or after the start of this period: midnight UTC that many days before today (7d = this week's new listings). Active listings are matched on their first on-market date (a future date counts as today); other statuses on the board's days-on-market count (that many days or fewer). Boards that hide Days on Market are left out of the search. Pair it with sort=newest.
- `modifiedSince` (string): Only listings the MLS modified on or after this point: a period (1d, 3d, 7d, 14d or 30d, from midnight UTC that many days ago) or an ISO 8601 date or date-time (2026-11-01 is midnight UTC; 2026-11-01T14:00:00Z or with an offset).
- `daysOnMarketMax` (integer 1 to 3650): At most this many days on market (Active listings: listed within that many days). Boards that hide Days on Market are left out of the search.
- `keywords` (string, repeat): Words to find in the public remarks (repeat for several). Only the public description is searched. At most 10 values. At most 60 characters.
- `ownListings` (boolean (1 or 0)): 1 = the brokerage's own listings (its agents' and confirmed offices'). Needs no location. ownListings, agent and office add their listings together (OR). bbox, polygon, an excluded where and the other filters narrow them; with an included where or boundariesId a JSON search is 400 (locations add listings too, so the answer would be wider than either).
- `agent` (string): One agent's listings: the agent's Ruuster slug or platform id (never an email). Needs no location; combines with the other filters as ownListings does.
- `office` (string): One listing office's listings, by its MLS office id. Needs no location; combines with the other filters as ownListings does.
- `filterByMls` (string, comma list): Narrow to these boards: a comma list of MLS search names (from /v1/meta mls[].searchName). Every name must be a board this key can show; it can only narrow. At most 20 values.
- `sort` (enum, default recommended) values recommended, featured, price_reduced, oldest, price_desc, price_asc, beds_desc, sqft_desc, lot_desc, baths_desc, close_date_desc, newest: Result order. close_date_desc is for sold searches; newest = first on market, newest first (listings without a listing date last).
- `page` (integer 1 to 40, default 1): Page number, from 1 (at most 40; page × limit at most 2,000).
- `limit` (integer 1 to 50, default 10): Results per page (1 to 50, default 10). view=map: 1 to 200, default 200; format=widget maps always get 200.
- `cursor` (string): The nextCursor of the previous page, where an op pages by cursor.
- `view` (enum, default card) values card, full, map: card = listing cards; full = cards plus the client detail fields; map = map pins (up to 200, page 1; listings that can't be placed exactly are left out).
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).
- `detailHref` (string): Override the account's detail URL template for this call: an http(s) URL or a path starting with /, containing {slug} or {id} (also allowed: {mlsNumber}). Drives each listing's href and canonical; a path is made absolute against your site for the canonical, og:url and JSON-LD. At most 500 characters.
- `pageHref` (string): Your own URL for this results page, without paging: an http(s) URL or a path starting with /. A path is made absolute against your site's origin. The answer's head.canonical and og:url are this URL (page 2 and later add ?page=N), and it is the last item of the BreadcrumbList. It changes no results. At most 500 characters.
- `indexable` (boolean (1 or 0)): Sets head.robots for this results page: 1 gives index,follow and 0 gives noindex,follow. Without it, a page whose filters a visitor picked (price, beds, baths, size, year, type, keywords and the other filters beyond location, status and sort) gets noindex,follow and every other page gets index,follow. It changes no results.
- `f.<key>` (string, repeat): Advanced filters by key from /v1/filters: f.<key>=value (repeat for several values), f.<key>Min / f.<key>Max for ranges, f.<key>_o=and|or|not|zbyes|zbno for the operator. Only keys /v1/filters lists are accepted. As in the Ruuster widget, a key the brokerage hides from its own filter bar is still accepted here.

### GET /v1/listings/ids

- `cursor` (string): The nextCursor of the previous page (icur_…). A cursor is bound to this key's boards: when they change it is refused and the sitemap restarts.
- `limit` (integer 1 to 1000, default 500): Listings per page (1 to 1000).

### GET /v1/listings/{listingId}

- `detailHref` (string): Override the account's detail URL template for this call: an http(s) URL or a path starting with /, containing {slug} or {id} (also allowed: {mlsNumber}). Drives each listing's href and canonical; a path is made absolute against your site for the canonical, og:url and JSON-LD. At most 500 characters.
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).

### GET /v1/listings/{listingId}/photos

- `limit` (integer 1 to 100, default 100): At most this many photos (1 to 100).
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).

### GET /v1/listings/{listingId}/similar

- `limit` (integer 1 to 12, default 6): At most this many similar homes (1 to 12), best match first.
- `include` (enum, default active) values active, sold, sold_only: active = homes for sale now (the default); sold = homes for sale now and recent sales, on the boards that show sold listings; sold_only = recent sales only (an empty list on a board that shows no sold listings).
- `maxMiles` (number 0.25 to 5, default 5): How far from the listing a similar home may be, in miles (0.25 to 5). The search starts within 1.5 miles (or this, when smaller) and widens once, up to this, when it finds fewer than 6 homes. When you send it, homes past that distance and homes whose location is not shown are left out. It has no effect when the listing's own address is hidden (its ZIP code is searched) or with shape.
- `maxPriceGapPct` (number 1 to 50, default 20): How far a similar home's price may be from the listing's price, in percent either way (1 to 50).
- `shape` (string): Only similar homes inside this saved shape (shp_…, from /v1/shapes), in place of the area around the listing.
- `detailHref` (string): Override the account's detail URL template for this call: an http(s) URL or a path starting with /, containing {slug} or {id} (also allowed: {mlsNumber}). Drives each listing's href and canonical; a path is made absolute against your site for the canonical, og:url and JSON-LD. At most 500 characters.

### GET /v1/listings/{listingId}/history

No query parameters.

### GET /v1/agents/{agentMlsId}/production

- `mls` (uuid, repeat): Only these of your MLS boards (their MLS ids; repeat for several). Default: every board of your account. The agent's MLS id is per board, so send the board when you have more than one. A board that isn't yours is 400 invalid_parameter. At most 20 values.
- `months` (integer 1 to 36, default 36): How many months of sales to count, ending now (1 to 36). Each MLS caps it again at its own sold window: period.soldFrom says from when sales are shown.

### GET /v1/suggest

- `q` (string, required): What the person typed: an address, city, ZIP, neighborhood, school, MLS number, … (at least 2 to 3 characters). At most 80 characters.
- `limit` (integer 1 to 10, default 7): Suggestions per group (1 to 10).
- `groups` (enum, comma list) values address, listing, city, zip, neighborhood, county, countyOrParish, school, subdivision, area, community, mlsArea, agent, office, place: Which suggestion groups to answer (a comma list). Default: address, city, zip, neighborhood, county, countyOrParish, school, subdivision, area, community, place. place = named places with an outline (cities and towns, ZIP areas, counties, neighborhoods, subdivisions, school districts) in the states the account's boards cover. listing (MLS numbers) is opt-in. mlsArea, agent and office are accepted but answer nothing: search by agent, office or ownListings instead.
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).

### GET /v1/boundaries/{boundaryId}

No query parameters.

### GET /v1/market

- `where` (json): The location, as one JSON object exactly as /v1/suggest returned it in `where`: a city, ZIP, neighborhood, county, school, place or county-or-parish row. Send exactly one location: where, boundariesId, zip / city / state, bbox, polygon, near or shape.
- `boundariesId` (uuid): The location as a platform boundary id (neighborhood, county, ZIP, school) from /v1/suggest. Send exactly one location.
- `zip` (string): The location as a five-digit ZIP code, or a Canadian postal code (T3J 2S7, or its first three characters for the whole area: T3J). zip, city and state together are one location; zip wins over city.
- `city` (string): The location as a city name, with or without state. zip, city and state together are one location. At most 80 characters.
- `state` (string): The location as a two-letter state code (the whole state), or the city's state. zip, city and state together are one location.
- `bbox` (string): The location as a map box: south,west,north,east in decimal degrees, at most 20° on a side. Send exactly one location.
- `polygon` (string, repeat): The location as a drawn area: lat,lng,lat,lng,… (repeat for several rings of the same area; at most 200 vertices in all). Send exactly one location.
- `near` (string): The location as a point: latitude,longitude in decimal degrees, with radiusMiles (default 1, up to 25). A circle is one location on its own.
- `radiusMiles` (number 0 to 25, default 1): The circle's radius around near, in miles (default 1, up to 25).
- `shape` (string): The location as one of the account's saved shapes (shp_…, from /v1/shapes). Send exactly one location.
- `type` (enum, repeat) values all, ResidentialIncome, ManufacturedInPark, Land, Farm, CommercialSale, CommercialLease, ResidentialLease: Only this property type (repeat for several); default every type the account shows.
- `subtype` (enum, repeat) values house, condo, townhome, co-op, other: Residential subtype (repeat for several).
- `subdivision` (string, repeat): Only listings in this subdivision or building, matched exactly as the MLS spells it (repeat for several: any of them). At most 20 values. At most 120 characters.
- `mlsArea` (string, repeat): Only listings in this MLS area (the board's own area code; repeat for several: any of them). At most 20 values. At most 120 characters.
- `mls` (uuid, repeat): Only these of your MLS boards (their MLS ids; repeat for several). Default: every board of your account. A board that isn't yours is 400 invalid_parameter. /v1/market/metrics lists your boards. At most 20 values.
- `priceMin` (integer from 0): Lowest price, in dollars: the asking price of a listing for sale, the sold price of a closed one.
- `priceMax` (integer from 0): Highest price, in dollars: the asking price of a listing for sale, the sold price of a closed one.
- `bedsMin` (integer 0 to 50): At least this many bedrooms.
- `bedsMax` (integer 0 to 50): At most this many bedrooms.
- `bathsMin` (number 0 to 50): At least this many bathrooms.
- `bathsMax` (number 0 to 50): At most this many bathrooms.
- `sqftMin` (integer from 0): Smallest living area, in square feet.
- `sqftMax` (integer from 0): Largest living area, in square feet.
- `lotAcresMin` (number 0 to 100000): Smallest lot, in acres.
- `lotAcresMax` (number 0 to 100000): Largest lot, in acres.
- `yearMin` (integer 1600 to 2100): Built in or after this year.
- `yearMax` (integer 1600 to 2100): Built in or before this year.
- `waterfront` (boolean (1 or 0)): true = waterfront listings only; false = leave them out.
- `newConstruction` (boolean (1 or 0)): true = new construction only; false = leave it out.
- `listingType` (enum, default sale) values sale, lease: sale (the default) or lease listings. Sales and leases never share a statistic. lease needs rentals on the account.
- `months` (integer 1 to 24, default 12): How many calendar months of history to return, ending with the current month (1 to 24). Sold history covers about the last 12 months; earlier months come back with null values and coverage says from when.
- `groupBy` (enum) values zip, city, subdivision, type, beds, priceBand, month: Split every metric by one dimension: zip, city, subdivision, type, beds or priceBand (at most 50 groups, largest first). month is the monthly series of /v1/market itself. Any median or average over fewer than 3 listings in a group is null.

### GET /v1/market/snapshot

- `where` (json): The location, as one JSON object exactly as /v1/suggest returned it in `where`: a city, ZIP, neighborhood, county, school, place or county-or-parish row. Send exactly one location: where, boundariesId, zip / city / state, bbox, polygon, near or shape.
- `boundariesId` (uuid): The location as a platform boundary id (neighborhood, county, ZIP, school) from /v1/suggest. Send exactly one location.
- `zip` (string): The location as a five-digit ZIP code, or a Canadian postal code (T3J 2S7, or its first three characters for the whole area: T3J). zip, city and state together are one location; zip wins over city.
- `city` (string): The location as a city name, with or without state. zip, city and state together are one location. At most 80 characters.
- `state` (string): The location as a two-letter state code (the whole state), or the city's state. zip, city and state together are one location.
- `bbox` (string): The location as a map box: south,west,north,east in decimal degrees, at most 20° on a side. Send exactly one location.
- `polygon` (string, repeat): The location as a drawn area: lat,lng,lat,lng,… (repeat for several rings of the same area; at most 200 vertices in all). Send exactly one location.
- `near` (string): The location as a point: latitude,longitude in decimal degrees, with radiusMiles (default 1, up to 25). A circle is one location on its own.
- `radiusMiles` (number 0 to 25, default 1): The circle's radius around near, in miles (default 1, up to 25).
- `shape` (string): The location as one of the account's saved shapes (shp_…, from /v1/shapes). Send exactly one location.
- `type` (enum, repeat) values all, ResidentialIncome, ManufacturedInPark, Land, Farm, CommercialSale, CommercialLease, ResidentialLease: Only this property type (repeat for several); default every type the account shows.
- `subtype` (enum, repeat) values house, condo, townhome, co-op, other: Residential subtype (repeat for several).
- `subdivision` (string, repeat): Only listings in this subdivision or building, matched exactly as the MLS spells it (repeat for several: any of them). At most 20 values. At most 120 characters.
- `mlsArea` (string, repeat): Only listings in this MLS area (the board's own area code; repeat for several: any of them). At most 20 values. At most 120 characters.
- `mls` (uuid, repeat): Only these of your MLS boards (their MLS ids; repeat for several). Default: every board of your account. A board that isn't yours is 400 invalid_parameter. /v1/market/metrics lists your boards. At most 20 values.
- `priceMin` (integer from 0): Lowest price, in dollars: the asking price of a listing for sale, the sold price of a closed one.
- `priceMax` (integer from 0): Highest price, in dollars: the asking price of a listing for sale, the sold price of a closed one.
- `bedsMin` (integer 0 to 50): At least this many bedrooms.
- `bedsMax` (integer 0 to 50): At most this many bedrooms.
- `bathsMin` (number 0 to 50): At least this many bathrooms.
- `bathsMax` (number 0 to 50): At most this many bathrooms.
- `sqftMin` (integer from 0): Smallest living area, in square feet.
- `sqftMax` (integer from 0): Largest living area, in square feet.
- `lotAcresMin` (number 0 to 100000): Smallest lot, in acres.
- `lotAcresMax` (number 0 to 100000): Largest lot, in acres.
- `yearMin` (integer 1600 to 2100): Built in or after this year.
- `yearMax` (integer 1600 to 2100): Built in or before this year.
- `waterfront` (boolean (1 or 0)): true = waterfront listings only; false = leave them out.
- `newConstruction` (boolean (1 or 0)): true = new construction only; false = leave it out.
- `listingType` (enum, default sale) values sale, lease: sale (the default) or lease listings. Sales and leases never share a statistic. lease needs rentals on the account.
- `window` (integer 7 to 365, default 30): The rolling window ending now, in days: 7, 30, 60, 90, 180, 365. Each windowed metric also comes with the window before it where the listing index still holds it.
- `metrics` (enum, comma list) values activeListings, comingSoon, underContractNow, newListings, backOnMarket, priceReductions, wentUnderContract, daysToContract, closings, closings12m, monthsOfInventory, monthsOfInventoryMls, absorptionRate, pendingRatio, marketType, listPriceActive, listPriceNew, soldPrice, pricePerSqftSold, pricePerSqftActive, salesVolume, priceBands, daysOnMarketSold, daysOnMarketActive, cumulativeDaysOnMarket, saleToList, saleToOriginalList, overAtUnderList, concessions, cashShare, mixByType, mixByBeds: Only these metrics (a comma list of names; default every metric). /v1/market/metrics defines each one. At most 32 values.
- `groupBy` (enum) values zip, city, subdivision, type, beds, priceBand: Split every metric by one dimension: zip, city, subdivision, type, beds or priceBand (at most 50 groups, largest first). Any median, average, sum or ratio over fewer than 3 listings in a group is null. For a breakdown by month use /v1/market.

### GET /v1/market/metrics

No query parameters.

### GET /v1/shapes

No query parameters.

### GET /v1/shapes/{shapeId}

No query parameters.

### GET /v1/collections

- `cursor` (string): The nextCursor of the previous page, where an op pages by cursor.
- `limit` (integer 1 to 100, default 25): Collections per page.

### GET /v1/collections/{collectionId}

- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).

### GET /v1/collections/{collectionId}/listings

- `sort` (enum, default recommended) values recommended, featured, price_reduced, oldest, price_desc, price_asc, beds_desc, sqft_desc, lot_desc, baths_desc, close_date_desc, newest: Result order. close_date_desc is for sold searches; newest = first on market, newest first (listings without a listing date last).
- `page` (integer 1 to 40, default 1): Page number, from 1 (at most 40; page × limit at most 2,000).
- `limit` (integer 1 to 50, default 10): Results per page (1 to 50, default 10). view=map: 1 to 200, default 200; format=widget maps always get 200.
- `cursor` (string): The nextCursor of the previous page, where an op pages by cursor.
- `view` (enum, default card) values card, full, map: card = listing cards; full = cards plus the client detail fields; map = map pins (up to 200, page 1; listings that can't be placed exactly are left out).
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).
- `detailHref` (string): Override the account's detail URL template for this call: an http(s) URL or a path starting with /, containing {slug} or {id} (also allowed: {mlsNumber}). Drives each listing's href and canonical; a path is made absolute against your site for the canonical, og:url and JSON-LD. At most 500 characters.
- `pageHref` (string): Your own URL for this results page, without paging: an http(s) URL or a path starting with /. A path is made absolute against your site's origin. The answer's head.canonical and og:url are this URL (page 2 and later add ?page=N), and it is the last item of the BreadcrumbList. It changes no results. At most 500 characters.
- `indexable` (boolean (1 or 0)): Sets head.robots for this results page: 1 gives index,follow and 0 gives noindex,follow. Without it, a page whose filters a visitor picked (price, beds, baths, size, year, type, keywords and the other filters beyond location, status and sort) gets noindex,follow and every other page gets index,follow. It changes no results.

### GET /v1/render/listings

- `where` (json, repeat): A location, as one JSON object exactly as /v1/suggest returned it in `where` (opaque: pass it back unchanged). Repeat for several areas (OR). An object with "operator":"not" excludes that area. A search needs where, near, bbox, polygon, boundariesId, zip, city, state or shape (or ownListings / agent / office). A boundary id is matched only under its own type's source. A listing-id or exact-address pick is answered as is: it matches wherever it is, and search filters such as price and beds apply to the areas in the search, not to the pick. Polygon and excluded locations don't narrow a pick either (a search of picks only plus either is 400; bbox does narrow them). Agent, office and MLS-area sources are built by the API only: use agent, office or ownListings. At most 20 values.
- `bbox` (string): A map box: south,west,north,east in decimal degrees (Google LatLngBounds.toUrlValue order). At most 20° on a side.
- `polygon` (string, repeat): A drawn area: lat,lng,lat,lng,… (at least three points). Repeat for several rings; at most 200 vertices in all.
- `boundariesId` (uuid): A platform boundary id (neighborhood, county, subdivision, area, community) from a /v1/suggest result; matched as that where object would be. A ZIP boundary id is 422: use a zip row from /v1/suggest instead. An unknown id is 404.
- `zip` (string): A five-digit ZIP code, matched exactly (zip=60645), or a Canadian postal code: the full code (zip=T3J 2S7) or its first three characters for the whole area (zip=T3J). Works alone or with city and state; when zip and city are both sent the ZIP is searched and city is left out. Counts as a location.
- `city` (string): A city name, matched exactly, case-insensitive (city=Austin). Works alone (every state the account's boards cover) or with state. Counts as a location. At most 80 characters.
- `state` (string): A two-letter state code, matched exactly (state=TX). Works alone (the whole state) or with city and zip. Counts as a location.
- `shape` (string): One of the account's saved shapes, by id (shp_…, from /v1/shapes): the search covers the area inside it, as one more location OR'd with the others. Counts as a location. A shape is a drawn area: inside it, the results are the listings whose address the MLS lets a site show.
- `near` (string): A point to search around: latitude,longitude in decimal degrees (near=26.142,-81.7948). Listings within radiusMiles of it (default 1 mile). Counts as a location on its own: it can't be combined with any other included location or with ownListings, agent or office (400); bbox, polygon and an excluded where narrow it. A malformed or out-of-range point is 422 location_not_supported. Inside the circle, the results are the listings whose address the MLS lets a site show.
- `radiusMiles` (number 0 to 25, default 1): With near: the radius in miles, more than 0 and at most 25 (default 1; decimals allowed, such as 0.5). Without near, or out of range, it is 422 location_not_supported.
- `priceMin` (integer from 0): Lowest list price, in dollars.
- `priceMax` (integer from 0): Highest list price, in dollars.
- `bedsMin` (integer 0 to 50): At least this many bedrooms.
- `bedsMax` (integer 0 to 50): At most this many bedrooms.
- `bathsMin` (integer 0 to 50): At least this many bathrooms.
- `bathsMax` (integer 0 to 50): At most this many bathrooms.
- `sqftMin` (integer from 0): Smallest living area, in square feet.
- `sqftMax` (integer from 0): Largest living area, in square feet.
- `lotSqftMin` (integer from 0): Smallest lot, in square feet (an acre is 43,560).
- `lotSqftMax` (integer from 0): Largest lot, in square feet.
- `yearMin` (integer 1600 to 2100): Built in or after this year.
- `yearMax` (integer 1600 to 2100): Built in or before this year.
- `hoaMin` (integer from 0): Lowest HOA / association fee, in dollars.
- `hoaMax` (integer from 0): Highest HOA / association fee, in dollars.
- `type` (enum, repeat) values all, ResidentialIncome, ManufacturedInPark, Land, Farm, CommercialSale, CommercialLease, ResidentialLease: Property type (repeat for several). No type = every type the account's boards carry (ResidentialLease only where rentals are enabled); type=all = every type except commercial; subtype narrows residential homes.
- `subtype` (enum, repeat) values house, condo, townhome, co-op, other: Residential subtype (repeat for several).
- `status` (enum, repeat) values active, coming_soon, pending, under_contract, closed: Listing status (repeat for several: status=active&status=pending; there is no all). Default: active. closed needs soldPeriod (format=widget and collections without one get every sold listing inside each board's sold window) and is available only on boards whose rules allow sold data (/v1/meta capabilities.sold).
- `soldPeriod` (enum) values 7d, 1m, 3m, 6m, 12m: With status=closed: closed within the last 7 days (7d) or 1, 3, 6 or 12 months, and never further back than each board's own sold window. Without status=closed it is 400 (saved widget searches and collections ignore it instead, as the Ruuster widget does).
- `openHousePeriod` (enum) values any, today_or_tomorrow, this_weekend, next_7_days: Only listings with an open house in this window (any = any upcoming open house).
- `newConstruction` (boolean (1 or 0)): 1 = new construction only, 0 = exclude it.
- `priceReduction` (enum) values 0d, 1d, 2d, 3d, 7d, 14d, 30d, 90d: Only listings whose price dropped within this many days (0d = today).
- `listedSince` (enum) values 1d, 3d, 7d, 14d, 30d: Only listings first on the market on or after the start of this period: midnight UTC that many days before today (7d = this week's new listings). Active listings are matched on their first on-market date (a future date counts as today); other statuses on the board's days-on-market count (that many days or fewer). Boards that hide Days on Market are left out of the search. Pair it with sort=newest.
- `modifiedSince` (string): Only listings the MLS modified on or after this point: a period (1d, 3d, 7d, 14d or 30d, from midnight UTC that many days ago) or an ISO 8601 date or date-time (2026-11-01 is midnight UTC; 2026-11-01T14:00:00Z or with an offset).
- `daysOnMarketMax` (integer 1 to 3650): At most this many days on market (Active listings: listed within that many days). Boards that hide Days on Market are left out of the search.
- `keywords` (string, repeat): Words to find in the public remarks (repeat for several). Only the public description is searched. At most 10 values. At most 60 characters.
- `ownListings` (boolean (1 or 0)): 1 = the brokerage's own listings (its agents' and confirmed offices'). Needs no location. ownListings, agent and office add their listings together (OR). bbox, polygon, an excluded where and the other filters narrow them; with an included where or boundariesId a JSON search is 400 (locations add listings too, so the answer would be wider than either).
- `agent` (string): One agent's listings: the agent's Ruuster slug or platform id (never an email). Needs no location; combines with the other filters as ownListings does.
- `office` (string): One listing office's listings, by its MLS office id. Needs no location; combines with the other filters as ownListings does.
- `filterByMls` (string, comma list): Narrow to these boards: a comma list of MLS search names (from /v1/meta mls[].searchName). Every name must be a board this key can show; it can only narrow. At most 20 values.
- `sort` (enum, default recommended) values recommended, featured, price_reduced, oldest, price_desc, price_asc, beds_desc, sqft_desc, lot_desc, baths_desc, close_date_desc, newest: Result order. close_date_desc is for sold searches; newest = first on market, newest first (listings without a listing date last).
- `page` (integer 1 to 40, default 1): Page number, from 1 (at most 40; page × limit at most 2,000).
- `limit` (integer 1 to 50, default 10): Results per page (1 to 50, default 10). view=map: 1 to 200, default 200; format=widget maps always get 200.
- `cursor` (string): The nextCursor of the previous page, where an op pages by cursor.
- `view` (enum, default card) values card, full, map: card = listing cards; full = cards plus the client detail fields; map = map pins (up to 200, page 1; listings that can't be placed exactly are left out).
- `format` (enum, default json) values json, widget: json = the public API shapes; widget = the shapes the Ruuster widget reads (for the widget and its adapters).
- `detailHref` (string): Override the account's detail URL template for this call: an http(s) URL or a path starting with /, containing {slug} or {id} (also allowed: {mlsNumber}). Drives each listing's href and canonical; a path is made absolute against your site for the canonical, og:url and JSON-LD. At most 500 characters.
- `pageHref` (string): Your own URL for this results page, without paging: an http(s) URL or a path starting with /. A path is made absolute against your site's origin. The answer's head.canonical and og:url are this URL (page 2 and later add ?page=N), and it is the last item of the BreadcrumbList. It changes no results. At most 500 characters.
- `indexable` (boolean (1 or 0)): Sets head.robots for this results page: 1 gives index,follow and 0 gives noindex,follow. Without it, a page whose filters a visitor picked (price, beds, baths, size, year, type, keywords and the other filters beyond location, status and sort) gets noindex,follow and every other page gets index,follow. It changes no results.
- `collection` (string): A saved configuration (emb_…) whose search is the starting point; parameters given here override it.
- `f.<key>` (string, repeat): Advanced filters by key from /v1/filters: f.<key>=value (repeat for several values), f.<key>Min / f.<key>Max for ranges, f.<key>_o=and|or|not|zbyes|zbno for the operator. Only keys /v1/filters lists are accepted. As in the Ruuster widget, a key the brokerage hides from its own filter bar is still accepted here.

### GET /v1/render/listing/{listingId}

- `detailHref` (string): Override the account's detail URL template for this call: an http(s) URL or a path starting with /, containing {slug} or {id} (also allowed: {mlsNumber}). Drives each listing's href and canonical; a path is made absolute against your site for the canonical, og:url and JSON-LD. At most 500 characters.
- `cta` (enum) values primary, secondary, none: Which of the account's calls to action the rendered detail includes.

### GET /v1/changes

- `cursor` (string): The nextCursor of the previous page (valid 7 days; after that, resync from /v1/listings/ids). Delivery is at least once: a listing can repeat (platform re-saves that changed nothing included; compare modifiedAt) and a removal can be reported again, so treat every row as idempotent and revalidate pages with If-None-Match (a 304 costs no units).
- `since` (string): First call only: changes after this ISO time (at most 7 days ago). Then follow nextCursor: call again at once while hasMore is true, later when it is false.
- `limit` (integer 1 to 1000, default 500): Changes per page (1 to 1000). A page can hold fewer, even none, while more are waiting: follow hasMore, not the row count.

### GET /v1/beacon

- `host` (string, required): The page's hostname (must match the Origin for a publishable key). At most 253 characters.
- `path` (string): The page path, e.g. window.location.pathname (only its first segment, at most 64 characters, is stored). At most 2048 characters.
- `v` (string): The widget version.
- `embed` (string): The saved configuration the page embeds, if any.
- `surface` (enum) values search, results, detail, map: Which widget surface the page shows.

### GET /v1/events

- `b` (string, required): A batch of up to 20 events: base64url of a JSON array, at most 4 KB decoded. At most 5500 characters.

### GET /v1/mortgage/estimate

- `price` (number 1000 to 100000000): The home price in dollars (required). On a listing page, send the listing's price.
- `downPayment` (number 0 to 100000000): The down payment in dollars, at most the price. Send this or downPaymentPercent, not both; with neither the estimate uses 20 percent.
- `downPaymentPercent` (number 0 to 100): The down payment as a percent of the price (0 to 100). Send this or downPayment, not both.
- `loanType` (enum) values conventional, fha, va, usda, jumbo, fixed, variable, adjustable: The loan type. In the United States: conventional (the default), fha, va, usda or jumbo. In Canada: fixed (the default), variable or adjustable. The answer's options.loanTypes lists the ones that apply.
- `termYears` (integer 1 to 30): The loan term in years. In the United States 30 (the default), 20 or 15. In Canada the contract term, 1 to 10 (default 5).
- `rateType` (enum, default fixed) values fixed, arm: United States only: fixed, or arm for a 5/6 adjustable-rate loan (termYears 30).
- `amortizationYears` (integer 15 to 30): Canada only: the years to pay the loan off (15 to 30, default 25).
- `creditScore` (enum, default 760+) values 760+, 740-759, 720-739, 700-719, 680-699, 660-679, 640-659, 620-639, <620: United States only: the buyer's credit score range, which sets the rate's credit adjustment.
- `rate` (number 0 to 15): An annual interest rate in percent that replaces today's market rate (for example 6.25).
- `state` (string): The home's two-letter state code (or Canadian province code, which makes the estimate Canadian). It sets the insurance average. Send state or zip.
- `zip` (string): The home's five-digit ZIP code. Without state, the estimate reads the state from it.
- `hoaMonthly` (number 0 to 100000): Monthly HOA dues (condo fees in Canada) in dollars. Without it the estimate shows 0 for this line.
- `propertyTaxAnnual` (number 0 to 10000000): The yearly property tax in dollars. Without it the estimate uses a national average and marks the line as estimated.
- `insuranceAnnual` (number 0 to 1000000): The yearly home insurance in dollars. Without it the estimate uses the state's average for the price and marks the line as estimated.

### GET /v1/usage

- `days` (integer 1 to 31, default 7): How many America/Chicago days of usage to return, today included (1 to 31).

### GET /v1/account/billing

No query parameters.

### GET /v1/public-records/lookup

- `address` (string): The property's street address with its 5-digit ZIP, for example 6104 Oak Forest Rd, Edmond, OK 73025. Add the unit when the building has several ("Unit 4"). Send exactly one of address or parcelNumber. At most 200 characters.
- `parcelNumber` (string): The county's parcel number, sent with postalCode. Dashes, dots and spaces are ignored. At most 40 characters.
- `postalCode` (string): The property's 5-digit ZIP, sent with parcelNumber (only with parcelNumber; put the ZIP inside address otherwise). At most 10 characters.
- `purpose` (enum) values cma, listing_presentation: Required. Why you are pulling this one property: cma (preparing a comparative market analysis) or listing_presentation. Public records are for one property at a time, for one of these two uses.
- `include` (enum) values owner: owner adds the owner's name and mailing address, for a CMA or listing presentation on the owner's own property. Left out, no name is returned.

### GET /v1/public-records/market

- `zip` (string): The area as one five-digit ZIP code. Send one area: zip, or city with state, or one county where object.
- `city` (string): The area as a city, sent together with state (city=Decatur&state=GA). The figures cover the ZIP codes of that city's listings on your MLS boards. At most 80 characters.
- `state` (string): The two-letter state code that goes with city.
- `where` (json): The area as one county, as the JSON object /v1/suggest returned for it in `where` (source "county"), passed back unchanged. Only a county is accepted here: no neighborhood, school, place, map area or saved shape.
- `type` (enum) values single_family, condo, townhouse, multi_family: Only this property type. Left out, every property on the tax roll.
- `yearMin` (integer 1800 to 2090): Built in or after this year. Whole decades only: a year ending in 0 (1980).
- `yearMax` (integer 1809 to 2099): Built in or before this year. Whole decades only: a year ending in 9 (1999).

### GET /v1/public-records/{recordId}/history

- `purpose` (enum) values cma, listing_presentation: Required. Why you are pulling this one property: cma (preparing a comparative market analysis) or listing_presentation. Public records are for one property at a time, for one of these two uses.
- `include` (enum) values owner: owner adds buyer, seller and borrower names. Left out, no name is returned.

### GET /v1/sandbox/public-records/lookup

- `address` (string): A sample home's street address with its 5-digit ZIP, for example 1370 Penn Ave NE, Atlanta, GA 30308. Send exactly one of address, parcelNumber or propertyId. At most 200 characters.
- `parcelNumber` (string): A sample home's parcel number, sent with postalCode. Dashes, dots and spaces are ignored. At most 40 characters.
- `postalCode` (string): The home's 5-digit ZIP, sent with parcelNumber (only with parcelNumber; put the ZIP inside address otherwise). At most 10 characters.
- `propertyId` (string): A sample listing's id from a search or detail answer: the county record of the home it lists. At most 36 characters.
- `include` (enum) values owner: owner adds the owners' names and mailing address (fictional in the sample data).

### GET /v1/sandbox/public-records/{recordId}/history

- `include` (enum) values owner: owner adds buyer, seller and borrower names (fictional in the sample data).

## 5. The recipe components

Use `@ruuster/idx-recipes` for React. The components reproduce the Ruuster embed's design, take the
brand through `--rw-*` CSS variables, and follow section 1. Server components need no browser API;
client components are marked.

| Component | Props | Kind |
|---|---|---|
| `ListingCard` | `listing`, `href?`, `priority?`, `mls?` | Server |
| `ListingGrid` | `listings`, `mls?`, `ga4ListName?`, `emptyText?`, `hrefOf?` | Server |
| `Pagination` | `page`, `pages`, `basePath`, `searchParams?`, `pageParam?` | Server |
| `ListingDetail` | `listing`, `mls?`, `backHref?`, `agent?`, `leadAction?`, `consentText?`, `alertsConsentText?`, `shareUrl?`, `googleMapsKey?`, `mapId?`, `apiBaseUrl?`, `mortgage?`, `aside?`, `ga4?`, `now?` | Server, with the client screens inside |
| `PhotoGrid`, `PriceBlock`, `MiniSummary`, `AgentCard`, `TourCard`, `ContactCards`, `AgentInfo`, `MobileActionBar` | the listing page's pieces (see the recipe components page) | Server |
| `DetailHeader`, `OpenHouses`, `LocationMap` | the listing page's pieces | Client |
| `FullGallery` | `listing`, `share`, `googleMapsKey?`, `sidebar?`, `mobileBar?` | Client |
| `Lightbox` | `photos`, `fallbackAlt`, `index`, `onIndex`, `returnFocusTo?` | Client |
| `ShareModal` | `listing`, `url`, `nativeShare?` | Client |
| `ContactAgentModal` | `listing`, `action`, `consentText`, `agent?`, `alertsConsentText?`, `now?` | Client |
| `RequestTourModal` | `listing`, `action`, `consentText`, `alertsConsentText?`, `now?` | Client |
| `MortgageCalculator` | `price`, `state?`, `zip?`, `hoaMonthly?`, `propertyTaxAnnual?`, `insuranceAnnual?`, `initial?`, `baseUrl?` (the listings route), `debounceMs?`, `initialEstimate?` | Client |
| `ListingDetailSkeleton`, `ListingUnavailable` | none; `backHref?` | Server, for `loading.tsx` and `not-found.tsx` |
| `MlsDisclaimers` | `mls`, `asOf?`, `placement?` | Server |
| `MlsAttribution` | `compliance`, `mls?` | Server |
| `MarketStats` | `market`, `measures?`, `mls?` | Server |
| `Filters` | `value`, `action`, `fields?`, `keep?`, `layout?` (`"stack"` or `"bar"`), `id?`, `actions?`, `activeCount?`, `filters?`, `baseUrl?` (the listings route) | Server form, works without JavaScript |
| `FiltersDrawer` | `value`, `action`, `fields?`, `keep?`, `activeCount?`, `id?`, `filters?`, `baseUrl?` (the listings route) | Client |
| `ResultsToolbar` | `total`, `view`, `basePath`, `searchParams?`, `sort?`, `sortOptions?`, `listHref?`, `mapHref?` | Server |
| `ListingGridSkeleton`, `ListingCardSkeleton`, `ResultsCountSkeleton` | `count?` (the grid) | Server, for `loading.tsx` |
| `Icon` | `name`, `size?`, `label?`, `className?` | Server |
| `JsonLd` | `docs` | Server |
| `RecipesStyles` | `themeVars?` | Server |
| `AreaMap` | `googleMapsKey`, `mapId?`, `viewport`, `boundary?`, `listings`, `mls?`, `height?`, `searchHref?`, `drawing?`, `boundaryKind?` | Client |
| `SearchBox` | `action`, `baseUrl?` (the listings route), `groups?`, `placeholder?`, `minChars?`, `debounceMs?` | Client |
| `TourForm`, `ContactForm`, `RegistrationForm` | `action`, `consentText`, `alertsConsentText?`, `submitLabel?`, `successText?`, `listing` | Client |
| `Ga4Event` | `event`, `params` | Client |

Also exported: `pushDataLayer(event, params)`, `RECIPES_CSS`, `miniSummaryOf(listing)` and
`mortgagePrefill(listing)` (the price, state, ZIP code, monthly HOA dues and yearly tax for the
calculator).

- Pass `r.meta.mls` as `mls` to every component that shows listings.
- `ListingCard` shows a closed listing's sold price (`closePrice`) and a "Sold" badge with its close
  date.
- Put `RecipesStyles` with `meta.themeVars` from `/v1/meta` in the layout once.
- The forms post JSON to `action`, a route on the person's own server. Their consent boxes start
  unchecked.
- Use the person's own Google Maps key and Map ID for `AreaMap` and for `ListingDetail`'s
  `googleMapsKey` and `mapId`.
- On the listing page, pass `ListingDetail` every screen prop: `backHref` (the search page), `agent`
  (the person's own agent or office, never the MLS listing agent: `name`, `photoUrl`, `phone`,
  `email`, `brokerage`, `license`), `leadAction` and `consentText` (together they turn on the
  contact and tour cards, the mobile action bar and the contact and tour screens), `shareUrl` (the
  page's own URL), `googleMapsKey` and `mapId` (the location map and Street view), and
  `apiBaseUrl="/api/idx"` (the mortgage calculator, which asks `GET /v1/mortgage/estimate`
  through the listings route). Never pass `publishableKey`: the prop is kept only for pages built
  before keyless requests, and where the example code below still passes it, leave it out. Add `loading.tsx` with `ListingDetailSkeleton` and `not-found.tsx` with
  `ListingUnavailable`.
- The listing page's screens open from buttons with `data-rw-open="gallery"`, `"share"`,
  `"contact"` or `"tour"` inside the element with `data-rw-detail`. On a layout of your own, put
  `data-rw-detail` on the root and mount each screen once inside it.
- Never add a favorite, heart or chat control to a listing page.
- On the search page, use `Filters` with `layout="bar"` (the More filters drawer), `ResultsToolbar`
  (the count, sort, and the Grid and Map switch, with `view=map` for the map) and `loading.tsx` with
  `ListingGridSkeleton`. Pass `searchHref` to `AreaMap` for "Search this area" and the drawing tools.

### Without React: HTML, CSS and JavaScript

On any other stack (PHP, Python, Ruby on Rails, Go, WordPress templates or plain HTML), build the same
UI from the files in the `static` folder of `@ruuster/idx-recipes`, which are generated from the React
components: `ruuster-idx.css` (the stylesheet), `ruuster-idx.js` (the browser script), one file per
widget in `html/` with its exact markup, `fields.md` (which API field fills which element) and
`HOOKS.md` (the `data-rw-*` attributes the script reads). The page
https://help.ruuster.com/idx/recipe-html-css shows every widget.

- Load `ruuster-idx.css` and `ruuster-idx.js` once per page from idx.ruuster.com, at the pinned version
  with its `integrity` and `crossorigin="anonymous"` attributes as https://help.ruuster.com/idx/recipe-html-css
  prints them (https://idx.ruuster.com/static/v1/manifest.json names the newest pinned version), or the
  current version 1 files at `https://idx.ruuster.com/static/v1/ruuster-idx.css` and `.js`. Self-hosting a
  copy is also fine.
- Print `data.themeVars` from `/v1/meta` right after the stylesheet as one rule,
  `<style>:where(.rw-recipes){--rw-name:value;...}</style>`, with only `--rw-*` names and values that
  have no `;`, `{`, `}`, `<`, `>` or backslash.
- Render the markup on the server from each widget's `html/` file, with every value escaped for HTML.
  Keep every class and every `data-rw-*` attribute exactly as the file prints it.
- Put no Listings API key in the page. Delete every `data-rw-key` attribute from the markup you copy,
  and set `data-rw-base-url` on the search box, the filters form and the mortgage calculator: the
  listings route (`/api/idx`) on a server that runs JavaScript, or `https://idx.ruuster.com/v1`
  (no key, recognized by the approved website address) otherwise. Put only the person's Google Maps
  browser key in `data-rw-maps-key`.
- Point each lead form's `action` at a route on the person's own server. The script posts the same
  LeadSubmission JSON as the React forms and screens.
- The listing page's `html/` file carries every screen: the gallery and the share, contact and tour
  screens as closed `<dialog>` elements, and the mortgage calculator with a first answer from the
  server. The script opens them from the same `data-rw-open` buttons as React.
- Section 1 applies unchanged: attribution, disclaimers, hidden addresses and fair housing.

## 6. Pages and limits

Units are charged per call; answers from the edge cache and 304 answers cost nothing. Daily units reset
at midnight America/Chicago. Over a limit, the API answers 429 `rate_limited` or
`daily_quota_exceeded` with `Retry-After`. Every answer carries `x-ratelimit-limit`,
`x-ratelimit-remaining`, `x-ratelimit-reset` (Unix seconds) and `x-ratelimit-window` (5 or 60).

Per key, by plan. A call over a window answers 429 `rate_limited` with Retry-After. Daily units reset at midnight America/Chicago.

| Plan | Key | Search | Suggest | Detail | Feed | Daily units |
|---|---|---|---|---|---|---|
| starter | publishable | 35 per 5 s, 300 per minute | 70 per 5 s, 600 per minute | 600 per minute | not available | 50,000 |
| starter | secret | 70 per 5 s, 600 per minute | 70 per 5 s, 600 per minute | 1200 per minute | 60 per minute | 150,000 |
| standard | publishable | 70 per 5 s, 600 per minute | 210 per 5 s, 1800 per minute | 1800 per minute | not available | 150,000 |
| standard | secret | 70 per 5 s, 600 per minute | 210 per 5 s, 1800 per minute | 3600 per minute | 180 per minute | 450,000 |
| pro | publishable | 70 per 5 s, 600 per minute | 700 per 5 s, 6000 per minute | 6000 per minute | not available | 500,000 |
| pro | secret | 70 per 5 s, 600 per minute | 700 per 5 s, 6000 per minute | 12000 per minute | 600 per minute | 1,500,000 |

Per account, for every key together, on top of the limits above. These are the defaults; an account can have its own. A call past one answers 429 and names the limit and when it resets.

| Calls | Each minute | Each day |
|---|---|---|
| Public Records lookups and history (add-on) | 20 | 500 |
| Public Records market figures (add-on) | 10 | 200 |
| Telemetry: /v1/beacon, /v1/events | The key's own limits | 2,000,000 |
| Calls that cost no units: /v1/meta, /v1/mortgage/estimate, /v1/usage, /v1/account/billing | The key's detail limit | 500,000 |

Units per successful call:

- GET /v1/status: 0
- GET /v1/meta: 0
- GET /v1/filters: 1
- GET /v1/filters/options: 1
- GET /v1/listings: 2
- GET /v1/listings/ids: 5
- GET /v1/listings/{listingId}: 1
- GET /v1/listings/{listingId}/photos: 1
- GET /v1/listings/{listingId}/similar: 2
- GET /v1/listings/{listingId}/history: 1
- GET /v1/agents/{agentMlsId}/production: 2
- GET /v1/suggest: 1
- GET /v1/boundaries/{boundaryId}: 1
- GET /v1/market: 2
- GET /v1/market/snapshot: 2
- GET /v1/market/metrics: 1
- GET /v1/shapes: 1
- GET /v1/shapes/{shapeId}: 1
- GET /v1/collections: 1
- GET /v1/collections/{collectionId}: 1
- GET /v1/collections/{collectionId}/listings: 2
- GET /v1/render/listings: 2
- GET /v1/render/listing/{listingId}: 1
- GET /v1/changes: 5
- GET /v1/beacon: 0
- GET /v1/events: 0
- GET /v1/mortgage/estimate: 0
- GET /v1/usage: 0
- GET /v1/account/billing: 0
- GET /v1/public-records/lookup: 1
- GET /v1/public-records/market: 1
- GET /v1/public-records/{recordId}/history: 1
- GET /v1/sandbox/public-records/lookup: 1
- GET /v1/sandbox/public-records/{recordId}/history: 1

- Keep at most four calls in flight per key. Never prefetch pages.
- Suggest: wait for three characters and a 300 ms pause, and cancel the call in flight.
- Map: search 300 ms after the map stops moving, and cancel the call in flight.
- Build sitemaps from `/v1/listings/ids`, never from searches.

## 7. The server-rendering pattern

Every page that shows listings is rendered on the server:

1. In server code, call the API with the secret key from `IDX_SECRET_KEY`.
2. If the answer is 404, answer 404. If it is 410 `listing_removed`, answer 410 with a "no longer
   available" page. If it is 429 or 503, throw, so the cache keeps the last good page. Never render or
   cache an error as the page.
3. Render the listings with real `<a href>` links, each card's attribution and every board's disclaimer
   from `meta.mls`.
4. Put `data.head` in the page head (`idx.toMetadata(r.data.head)` in Next.js) and `data.jsonLd` in the
   page (`<JsonLd docs={r.data.jsonLd} />` in React, `data.jsonLdHtml` as is elsewhere).
5. Cache the page for about five minutes (`export const revalidate = 300` in Next.js), and re-render it
   when a webhook or `/v1/changes` says its listing changed.
6. In the browser, load the search box, the map and the gallery on top. They ask the API through the
   listings route, so the page carries no key.

Results pages send `pageHref` (their own URL without paging) and render page links with `Pagination`.
Pages with filters a visitor picked come back `noindex,follow`; keep it.

## 8. Listing pages, JSON-LD and sitemaps

- The listing URL is `/homes/{slug}`, where `slug` is `{address-slug}-{id}`, or the id alone when the
  address is hidden. Build it with `listingPath(listing)` and read the id back with
  `parseListingSlug(slug)`.
- Call `idx.get(id)`. When the URL's slug differs from `data.slug`, answer 301 to the current path. On
  410 answer 410, and on 404 answer 404. In the Next.js App Router, decide 301 and 410 in
  `middleware.ts`, because a page cannot set those statuses itself. The appendix has the whole file.
  Five details matter:
  1. Use `export const config = { matcher: ["/homes/:path*"] }` and check inside the function that
     the path has one segment. Never use `matcher: "/homes/:slug"`: Next.js 14 compiles it to match
     `/homes` alone, so the middleware never runs on a listing.
  2. Middleware runs in the edge runtime and can't import `lib/idx.ts` (it imports `server-only`).
     Create a second client in `middleware.ts` with `createClient` and the same `IDX_SECRET_KEY`,
     `IDX_BASE_URL` and `detailHref`.
  3. Keep each answer in a `Map` for 60 seconds. On 429, 503 or a network error, call
     `NextResponse.next()` and let the page decide.
  4. Build the 301 location from the API's answer:
     `listingPath({ id, slug: r.data.slug, mlsNumber: r.data.mlsNumber }, DETAIL_HREF)`.
     `listingPath` needs the id, the slug and the MLS number.
  5. Answer 410 with
     `NextResponse.rewrite(req.nextUrl, { status: 410, headers: { "X-Robots-Tag": "noindex" } })`.
     The page renders under that status, sees the API's 410 and shows the "no longer available" body.
     Next.js adds its own `noindex` robots tag to any page answered above 400, beside the page's own
     `noindex,follow`; both say `noindex`.
- On a 410 page, show homes like it from `idx.similar(id)`, which answers for 30 days after removal
  with `subjectRemoved` true (map each item to its `listing`). Link to the area page.
- Put `organization.jsonLdHtml` from `/v1/meta` in the site layout once.
- The listing sitemap walks `idx.ids({ cursor, limit })` until `nextCursor` is null, with `modifiedAt`
  as `lastmod`, split at 50,000 URLs. A second sitemap lists the area pages.
- `robots.txt` allows `/`, keeps `/api/` out and names both sitemaps.

## 9. Compliance details

- `meta.mls[]` holds, per board: `mlsName`, `disclaimer` (`text` and `html`), `logo` (`url`, `width`,
  `height`, `alt`), `attributionTemplate`, `required` (`element` and `placement`), `notices` and
  `displayType`.
- Elements: `listing_office`, `listing_agent`, `agent_contact`, `mls_logo`, `disclaimer`, `as_of`,
  `courtesy_line`, `dmca_notice`, `source_line`. Placements: `card`, `detail`, `page`, `map`.
- A listing page's `data.compliance` holds `attributionLine`, `courtesyLine`, `required`,
  `suppressedFields` and `asOf` for that listing.
- When you build cards yourself, call `assertDisplayable(listing, r.meta.mls, "card")` in a test; it
  throws when a required element is missing. `renderAttribution` returns the exact text.
- Hidden addresses: `address.hidden` true means `street`, `unit` and `geo` are null and the slug is the
  id. Searches inside a box, a polygon or a shape leave such listings out.
- Sold: only boards with `capabilities.sold[].allowed` true return closed listings, within
  `windowDays`.

## 10. What the person's site adds

The API supplies listings, photos, market numbers, compliance text, head tags and JSON-LD. The
person's site adds the rest, and you build it in their code:

- the pages, the design and the hosting;
- registration, tour, contact and question forms, with their own consent text;
- visitor accounts and favorites, stored in their own site or CRM. The Listings API has no saved
  searches and sends no listing alert emails in version 1, so do not build or promise either;
- chat, email and SMS, through their own tools;
- lead routing to their agents, in their CRM;
- analytics, with their own Google Tag Manager container.

## 11. The CRM loop

1. A form posts JSON (`LeadSubmission`) to a route on the person's own server, such as
   `/api/leads/fub`.
2. The route validates it (the honeypot, an email or a phone, and the contact consent box) and sends it
   to the person's CRM with the server-only senders in `@ruuster/idx/crm`: Follow Up Boss, Sierra
   Interactive or Sure Send. The CRM keys live in `FUB_API_KEY`, `FUB_SYSTEM`, `FUB_SYSTEM_KEY`,
   `SIERRA_API_KEY` and `SURESEND_API_KEY`. `FUB_COOKIE_SECRET` signs the `fub_person` cookie, and
   the listing-view route sends a view only for a cookie whose signature checks out.
3. The lead source is `SITE_NAME`, never "Ruuster".
4. Listing details in a CRM payload come from `crmProperty(listing, url)`, which leaves out a hidden
   street, and `url` is the listing's page on the person's site: `SITE_ORIGIN` plus
   `listingPath(listing)`. A URL the form sent counts only when it is on `SITE_ORIGIN`.
5. Alert tags are added only when the visitor checked the separate alerts box. Show that box only when
   the person says their CRM, or AI Nurture on the Ruuster Platform, sends listing emails. Otherwise
   leave `alertsConsentText` out.
6. Only for a brokerage that is also on the Ruuster Platform with its CRM connected to Ruuster:
   Ruuster picks up the person and their tags.
7. Before launch, the person submits a test lead from each form and finds it in their CRM.

The server-only helpers in `@ruuster/idx/crm` (`LeadSubmission` itself is exported from
`@ruuster/idx`):

- `assertSendable(lead)` throws `LeadRejected` with `reason` `honeypot`, `contact`, `consent` or
  `invalid` and a `message` to show. Answer a honeypot with 200 and send nothing; answer the others
  with 422 and the message.
- Follow Up Boss: `fub.eventFromLead(lead, { source, listing, listingUrl, tags })`, then
  `fub.sendEvent(event, { apiKey, system, systemKey }, { fetch })`. Its `id` is the person's Follow Up
  Boss id. A registered visitor's views: `fub.viewedPropertyEvent({ id }, listing, { source, listingUrl })`,
  at most once per person, listing and day, from the optional route `POST /api/activity/fub`.
- Sierra Interactive: `sierra.leadFromSubmission(lead, { source, listing, listingUrl, tags })`, then
  `sierra.createLead(body, { apiKey }, { fetch })`. Sierra needs an email.
- Sure Send: `suresend.personFromSubmission(lead, { source, listing, listingUrl, tags, stage })`, then
  `suresend.createPerson(person, { apiKey }, { fetch })`. `stage` is one of the person's Sure Send stage
  names, or null.
- Every sender answers `{ ok: true, status, id }` or `{ ok: false, status, error, retryAfterSec }` and
  never throws for an HTTP error. Pass a fake `fetch` in tests.
- The route answers the form with a sentence: 200 when sent, 403 from another site, 400 when it can't
  read the body, 422 for a missing contact or consent, 429 with `Retry-After` when the CRM asks to
  wait, 500 when a key or `SITE_NAME` is missing, and 502 when the CRM refuses. The appendix's
  `lib/crm.ts` has the sentences.

The exact requests, fields and tags for each CRM are on https://help.ruuster.com/idx/crm-overview and
the pages it links. Use only what those pages show.

## 12. Caching

- Publishable-key answers are cached at the edge for the time in section 3. Secret-key answers and
  errors are never cached at the edge.
- Cache server-rendered pages for about five minutes, market numbers for an hour or more, sitemaps for
  an hour.
- On 429 or 503, throw from the page's data function, so the cache keeps the last good page.
- Send a listing's `ETag` back as `If-None-Match`; a 304 costs no units.
- Keep listing data only in a cache, and purge a page when its listing changes or leaves the API.

## 13. Errors

Branch on `error.code`, never on the message. Retry only codes marked retryable, after `Retry-After`.

| Code | HTTP | Retry | What it means | What to show or do |
|---|---|---|---|---|
| `area_too_large` | 400 | No | The search area is too large. Use a smaller bbox, or a polygon with at most 200 vertices. | Ask the visitor to zoom in, or send a smaller map box or a simpler drawn area. |
| `invalid_cursor` | 400 | No | The cursor is malformed, or was issued for a different query or key. | Start again without a cursor, from the first page. |
| `invalid_parameter` | 400 | No | A parameter is missing, unknown or malformed. | Fix the request; the message names the parameter. On a page, show the results without the filter the visitor typed. |
| `location_required` | 400 | No | Search needs a location: where, near, bbox, polygon, boundariesId, zip, city, state or shape (or ownListings, agent, office, or a collection). | Add a location (where, bbox, polygon, boundariesId, zip, city, state or shape) before you search. |
| `page_depth_exceeded` | 400 | No | Paging is limited to page 40 and 50 results per page (2,000 results per query). Narrow the search. | Stop paging at this point and ask the visitor to narrow the search. |
| `secret_key_in_url` | 400 | No | Secret keys must be sent as Authorization: Bearer from your server, never in a URL. This key has been flagged; rotate it. | Create a new secret key in your console under Keys and domains now, then send the new one only as Authorization: Bearer from your server. |
| `sold_period_required` | 400 | No | Closed (sold) searches need soldPeriod (7d, 1m, 3m, 6m or 12m). | Add soldPeriod to every search that asks for closed listings. |
| `invalid_credentials` | 401 | No | The API key is not valid. | Check that the key was copied in full from your console and that it is the right kind for this code. |
| `missing_credentials` | 401 | No | Send a publishable key as ?key= or a secret key as Authorization: Bearer. | Send your publishable key as ?key= from the browser, or your secret key as Authorization: Bearer from your server. |
| `payment_required` | 402 | No | This account is paused for an unpaid invoice. Pay the invoice in your console's Billing page and the API answers again within a minute. GET /v1/account/billing shows the status. | Keep serving your cached pages, and pay the open invoice from your console's Billing page. The API answers again within a minute of the payment. Do not retry in a loop. |
| `access_revoked` | 403 | No | This API key has been revoked, has expired, or was flagged. Create a new key in your console, or email helpme@ruuster.com. | Create a new key in your console under Keys and domains, then update your environment variables. If the new key is refused too, email helpme@ruuster.com. |
| `addon_not_enabled` | 403 | No | This endpoint is part of an add-on that is not switched on for this account. Add it in your console's Billing page. | Hide the feature that needs the add-on, or add the add-on in your console under Billing, Add-ons. |
| `brokerage_not_enabled` | 403 | No | The Ruuster Listings API is not enabled for this brokerage, or no MLS is approved for it yet. | Open Go live in your console to see which step your account is on. Pages can show a short notice until then. |
| `origin_not_allowed` | 403 | No | This publishable key is not allowed on this site. Add the domain to the key's allowed origins. | Add this domain under Keys and domains in your console and request MLS approval for it there, or call from a domain that is already approved. |
| `origin_required` | 403 | No | Publishable keys work only from a browser on an allowed origin. From a server, use your secret key. | A publishable key with no Origin header is refused. Call with the publishable key from a browser page, or use your secret key from your server. |
| `secret_key_in_browser` | 403 | No | Secret keys must never be used in a browser. This key has been flagged; rotate it and use a publishable key on the page. | Create a new secret key in your console under Keys and domains now, and use your publishable key on the page. |
| `secret_key_required` | 403 | No | This endpoint needs your secret key, sent from your server as Authorization: Bearer. | Call this endpoint from your server with your secret key. |
| `agent_not_found` | 404 | No | No agent with that slug or id at this brokerage. | Check the agent's slug or id; show the brokerage's own listings in the meantime. |
| `boundary_not_found` | 404 | No | That boundary id is unknown. Search takes the ids /v1/suggest returns; /v1/boundaries/{id} answers outlines for neighborhood, county, ZIP and school boundaries from /v1/suggest and for boundary-library areas. | Look the place up again with /v1/suggest and save the new id. |
| `mls_not_in_scope` | 404 | No | This listing is not available to this key. | Answer your own page with 404; this key cannot show that listing. |
| `not_found` | 404 | No | No such resource. | Answer your own page with 404 and leave it out of your sitemap. |
| `shape_not_found` | 404 | No | No saved shape with that id for this key. /v1/shapes lists the shapes this key can use. | Pick a shape from /v1/shapes. To have a shape added, email helpme@ruuster.com. |
| `method_not_allowed` | 405 | No | This API is read-only: use GET. | Send a GET request. |
| `ambiguous_address` | 409 | No | More than one property matches that address. Be more specific: add the unit number, or look the property up by parcelNumber and postalCode. | Ask the person for the unit number or the full street name, or look the property up by parcel number. Never guess between properties. |
| `cursor_expired` | 410 | No | The cursor has expired. Start again without a cursor. | Start again without a cursor (for the changes feed, resync from /v1/listings/ids). |
| `listing_removed` | 410 | No | This listing is no longer available. Remove its page (410 Gone, noindex) and drop it from your sitemap. | Answer the listing's page with 410 Gone and noindex, show similar homes, and drop the URL from your sitemap. |
| `filter_not_supported` | 422 | No | That filter is not available through the API. | Use a filter key that /v1/filters lists. |
| `location_not_supported` | 422 | No | That kind of location can't be used here. Use a location returned by /v1/suggest, a bbox or a polygon. | Use a row from /v1/suggest, a map box or a drawn area instead. On a Public Records lookup it means Ruuster has no public records in that state: hide the lookup for that property. |
| `own_listings_unconfigured` | 422 | No | ownListings needs the brokerage's agent or office MLS ids on file. Email helpme@ruuster.com to have them set up. | Email helpme@ruuster.com to have your agents' or offices' MLS ids added, then try again. |
| `sold_not_permitted` | 422 | No | Sold listings can't be shown for the MLSs in this search. | Leave closed out of the status list, or narrow the search with filterByMls to boards that show sold listings. |
| `daily_quota_exceeded` | 429 | Yes, after Retry-After | This key's daily quota is used up. It resets at 00:00 America/Chicago. | Serve cached pages until the quota resets at midnight America/Chicago. To ask for a higher limit, email helpme@ruuster.com. |
| `rate_limited` | 429 | Yes, after Retry-After | Too many requests. Back off and retry after the Retry-After interval. | Wait Retry-After seconds, then try once more. In server rendering, throw so your cache keeps serving the last good page. |
| `internal_error` | 500 | Yes, after Retry-After | Something went wrong on our side. | Try once more after Retry-After seconds; if it keeps failing, contact support with the requestId. |
| `api_paused` | 503 | Yes, after Retry-After | The Ruuster Listings API is temporarily paused for maintenance. | Keep serving your cached pages and try again after Retry-After seconds. |
| `source_unavailable` | 503 | Yes, after Retry-After | Listing data is temporarily unavailable. Retry after the Retry-After interval. | Wait Retry-After seconds, then try once more. In server rendering, throw so your cache keeps serving the last good page. |

## 14. Capabilities and webhook events

`GET /v1/meta` answers `data.capabilities`. Check it before building sold pages, maps or the
brokerage's own listings.

| Field | Type | What it tells you |
|---|---|---|
| `capabilities.sold` | array of object | For each board in your key's scope: whether sold listings may be shown, and for how many days after closing. Check it before you build a sold page. |
| `capabilities.renderMode` | string (enum) | How Ruuster renders pages for this key: ssr, static or none. |
| `capabilities.surfaces` | array of string | The widget surfaces this key may use. |
| `capabilities.multiInstance` | boolean | True when one page may hold more than one listings block. |
| `capabilities.urlPaging` | boolean | True when results pages may carry the page number in the URL. |
| `capabilities.ownListings` | boolean | True when ownListings=1 works for this key (the brokerage's agents or offices are on file). |
| `capabilities.agentFilter` | boolean | True when the agent parameter works for this key. |
| `capabilities.maps` | boolean | True when the account has a Google Maps key (meta.maps returns it). |
| `capabilities.suggestSources` | array of string (enum) | The kinds of location /v1/suggest can return for this key. |

Sample listing-change webhooks are set up in the person's console, under Keys and domains, Sample
webhooks. A webhook for live listings is added by Ruuster on request (helpme@ruuster.com). Each delivery is a
`POST` with the headers `Ruuster-Event-Id`, `Ruuster-Event-Kind`, `Ruuster-Delivery-Id` and
`Ruuster-Signature` (`t=<unix>,v1=<hex>`, HMAC-SHA256 of `<t>.<raw body>`). The body is one event or
`{ "kind": "batch", "events": [ … ] }`. Verify it with `verifyWebhook({ body, headers, secret })` on the
raw body text, answer 2xx fast, and only re-render: deliveries are at least once and in no fixed order.

### Event kinds

| Kind | When it is sent |
|---|---|
| `listing.created` | A listing your key can show appeared (new to the market, or newly in your boards' scope). |
| `listing.price_changed` | The list price changed. `previous.price` holds the price before the change when the history has it. |
| `listing.status_changed` | The status changed, for example from active to pending. `previous.status` holds the earlier status when the history has it. |
| `listing.removed` | The listing can no longer be shown on your site. Answer its page with 410 Gone and drop it from your sitemap. |

### Headers

| Header | What it holds |
|---|---|
| `Ruuster-Event-Id` | The event id (the same as `id` in the body). A delivery can repeat: keep the ids you have handled and skip a repeat. |
| `Ruuster-Event-Kind` | The event kind, or `batch` for a body that holds several events. |
| `Ruuster-Delivery-Id` | This delivery attempt's id. Quote it when you contact support. |
| `Ruuster-Signature` | `t=<unix seconds>,v1=<hex>`. During a secret rotation there are two `v1` values; either may match. |

### Body

One event per delivery looks like this. A hidden-address listing has no street in its `slug`.

```json
{
  "id": "levt_aef04390d0666f2c405600aa",
  "kind": "listing.price_changed",
  "apiVersion": "v1",
  "occurredAt": "2026-11-03T14:20:00.000Z",
  "listing": {
    "id": "aaaaaaaa-0000-4000-8000-000000000001",
    "slug": "123-peachtree-st-ne-atlanta-ga-30308-aaaaaaaa-0000-4000-8000-000000000001",
    "mls": "FIXTURE",
    "mlsNumber": "FXSTD001",
    "status": "active",
    "price": 489000,
    "href": "https://idx.ruuster.com/v1/listings/aaaaaaaa-0000-4000-8000-000000000001"
  },
  "previous": {
    "price": 499000
  }
}
```

When several events are ready at once, one delivery carries them together:

```json
{
  "id": "bat_7d1e2f3a4b5c6d7e8f9a0b1c",
  "kind": "batch",
  "apiVersion": "v1",
  "count": 1,
  "events": [
    {
      "id": "levt_aef04390d0666f2c405600aa",
      "kind": "listing.price_changed",
      "apiVersion": "v1",
      "occurredAt": "2026-11-03T14:20:00.000Z",
      "listing": {
        "id": "aaaaaaaa-0000-4000-8000-000000000001",
        "slug": "123-peachtree-st-ne-atlanta-ga-30308-aaaaaaaa-0000-4000-8000-000000000001",
        "mls": "FIXTURE",
        "mlsNumber": "FXSTD001",
        "status": "active",
        "price": 489000,
        "href": "https://idx.ruuster.com/v1/listings/aaaaaaaa-0000-4000-8000-000000000001"
      },
      "previous": {
        "price": 499000
      }
    }
  ]
}
```

### Signature

Each delivery is signed. Read `Ruuster-Signature`, take `t` and every `v1`. Compute an HMAC-SHA256 with your signing secret over the text `<t>.<raw body>` and compare it, in constant time, with each `v1`. Accept the delivery when one matches and `t` is less than 300 seconds old. The SDK's `verifyWebhook` does all of this and gives you the events whether the body holds one event or a batch.

## 15. Recipes

Each recipe is a complete page with its code, its calls and its rules. Start from the matching recipe
and its prompt.

### Recipes for every page type

https://help.ruuster.com/idx/recipes: Complete, server-rendered page recipes for a real estate site on the Ruuster Listings API, each with the calls it makes, the exact steps, the full code, the rules it follows and a prompt for your AI coding assistant.

### Search page with map

https://help.ruuster.com/idx/recipe-search-page: A /search page whose first page of results is rendered on your server from the URL, with the search box, the filter bar and its More filters drawer, the results toolbar, listing cards, pagination, a map view with drawing tools, loading placeholders and the MLS disclaimers.

Prompt: https://help.ruuster.com/idx/prompt-search-page.md

### Neighborhood and area pages

https://help.ruuster.com/idx/recipe-neighborhood-page: An area page such as /neighborhoods/midtown that answers the questions people ask with dated market numbers, adds your own words, and lists the area's homes with pagination, the map and the MLS disclaimers.

Prompt: https://help.ruuster.com/idx/prompt-area-pages.md

### Listing detail page

https://help.ruuster.com/idx/recipe-listing-detail: One permanent, server-rendered page per listing at /homes/<slug> with every screen of the listing page (the header, photo grid, gallery, price block, agent information, open houses, details, mortgage calculator, location map, contact and tour cards, share, contact and tour screens), its loading and not-found states, and real 301, 404 and 410 status codes.

Prompt: https://help.ruuster.com/idx/prompt-detail-pages.md

### Photo gallery

https://help.ruuster.com/idx/recipe-gallery: The full-screen photo gallery of the listing page, with the Photos and Street view tabs, the photo mosaic, the lightbox, the sidebar and the mobile action bar, from FullGallery and Lightbox.

Prompt: https://help.ruuster.com/idx/prompt-detail-pages.md

### Share a listing

https://help.ruuster.com/idx/recipe-share: The listing page's share screen, from ShareModal, which shares your own listing URL through the device's share sheet or a modal with Copy link, Facebook, WhatsApp and email.

Prompt: https://help.ruuster.com/idx/prompt-detail-pages.md

### Contact the agent

https://help.ruuster.com/idx/recipe-contact-agent: The listing page's contact screen, from ContactAgentModal, which sends the visitor's question to your own route with their consent, then offers a tour time.

Prompt: https://help.ruuster.com/idx/prompt-detail-pages.md

### Book a tour

https://help.ruuster.com/idx/recipe-tour-booking: The listing page's tour screen, from RequestTourModal, with a 16-day picker, morning, afternoon and evening times, the visitor's details with consent, and the request your route receives.

Prompt: https://help.ruuster.com/idx/prompt-detail-pages.md

### Mortgage calculator

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.

Prompt: https://help.ruuster.com/idx/prompt-detail-pages.md

### Recently sold

https://help.ruuster.com/idx/recipe-recently-sold: A /neighborhoods/<area>/sold page listing homes sold in the last 6 months, published only where your boards show sold data, with a link to the area page everywhere else.

Prompt: https://help.ruuster.com/idx/prompt-recently-sold.md

### Our listings

https://help.ruuster.com/idx/recipe-our-listings: An /our-listings page with your brokerage's own listings, rendered on your server, each linking to its listing page and your tour form.

Prompt: https://help.ruuster.com/idx/prompt-our-listings.md

### Open houses this weekend

https://help.ruuster.com/idx/recipe-open-houses: An /open-houses page with every home in your market area that has an open house this weekend, rendered on your server and refreshed every 5 minutes.

Prompt: https://help.ruuster.com/idx/prompt-open-houses.md

### Homepage search bar

https://help.ruuster.com/idx/recipe-search-bar: A homepage search bar that suggests cities, neighborhoods, ZIP codes and schools as the visitor types, then hands off to your server-rendered search page.

Prompt: https://help.ruuster.com/idx/prompt-search-bar.md

### Featured listings strip

https://help.ruuster.com/idx/recipe-featured-strip: A strip of eight featured homes for your homepage, from a collection you curate in Ruuster or from your own listings, rendered on your server.

Prompt: https://help.ruuster.com/idx/prompt-our-listings.md

### One agent's listings

https://help.ruuster.com/idx/recipe-agent-listings: An /agents/<agent> page with one agent's listings, rendered on your server, and a contact form that sends to your CRM.

Prompt: https://help.ruuster.com/idx/prompt-agent-profile.md

### Area guide hub

https://help.ruuster.com/idx/recipe-area-guide-hub: A /neighborhoods hub that links every area page with today's count of homes for sale, plus the sitemap and llms.txt files that list your area pages.

Prompt: https://help.ruuster.com/idx/prompt-area-pages.md

### Price reduced

https://help.ruuster.com/idx/recipe-price-reduced: A /price-reduced page with the homes in your market area whose price dropped in the last 7 days, rendered on your server.

Prompt: https://help.ruuster.com/idx/prompt-search-page.md

### New listings this week

https://help.ruuster.com/idx/recipe-new-listings: This week's new listings in an area and price range, newest first, for a weekly report, a social post or a page, with your own listings by default and every board on request.

Prompt: https://help.ruuster.com/idx/prompt-our-listings.md

### New construction

https://help.ruuster.com/idx/recipe-new-construction: A /new-construction page with the newly built homes in your market area, on boards that carry the new-construction field.

Prompt: https://help.ruuster.com/idx/prompt-search-page.md

### Group photos by room with your own AI

https://help.ruuster.com/idx/recipe-photos-by-room: Group a listing's photos by room with your own AI, through the enrichment hook and your own photo field, and show them as tabs in your gallery.

Prompt: https://help.ruuster.com/idx/prompt-detail-pages.md

### Registration, tour and contact forms

https://help.ruuster.com/idx/recipe-forms: The tour, contact and registration forms for your listing, agent and sign-up pages, posting to your own server route, which sends each lead to Follow Up Boss, Sierra Interactive or Sure Send.

Prompt: https://help.ruuster.com/idx/prompt-crm-leads.md

### Email me new matches (save a search)

https://help.ruuster.com/idx/recipe-save-search: An "Email me new matches" box on your search page that saves the visitor's current search as a Listing Alerts saved search, through your own server route, with their consent.

Prompt: https://help.ruuster.com/idx/prompt-listing-alerts.md

### Listing alerts sign-up for an area

https://help.ruuster.com/idx/recipe-alerts-signup: A "Get listing alerts" sign-up box for one area, such as new listings in a ZIP code or neighborhood, for your neighborhood and area pages.

Prompt: https://help.ruuster.com/idx/prompt-listing-alerts.md

### Manage alerts and unsubscribe pages

https://help.ruuster.com/idx/recipe-manage-alerts: The manage-alerts and unsubscribe pages every alert links to, on your own site: read the link's token, list the buyer's saved searches, and let them change how often, pause, delete or stop everything.

Prompt: https://help.ruuster.com/idx/prompt-listing-alerts.md

### Recipe components

https://help.ruuster.com/idx/recipe-components: Every React component in @ruuster/idx-recipes, including every screen of the listing page and the search page, what it renders, its props, whether it runs on the server or in the browser, and the GA4 events it sends.

Prompt: https://help.ruuster.com/idx/prompt-own-ui.md

### Build without React: HTML, CSS and JavaScript

https://help.ruuster.com/idx/recipe-html-css: Build the same cards, listing page, search box, filters, forms and map as the React recipe components on any stack, with one stylesheet, the exact HTML of each widget and one small script.

Prompt: https://help.ruuster.com/idx/prompt-own-ui.md

### Match your brand

https://help.ruuster.com/idx/theming: The recipe components take their colors and fonts from your Ruuster brand kit through --rw- CSS variables, and you can change any of them in your own CSS.

Prompt: https://help.ruuster.com/idx/prompt-brand.md

## 16. Listing Alerts (saved searches and alerts)

With the Listing Alerts add-on, the site registers visitors who save a search as buyers, and the API
finds new listings, price drops, homes back on the market and sales for each saved search. The site
sends each alert through its own email provider. Guides: help.ruuster.com/idx/alerts-quickstart.

- MUST call every alerts endpoint from the server with the secret key; bodies are JSON.
- MUST send a consent record (`consent.text`, the words the buyer agreed to) with every new buyer, and
  never invent one.
- MUST copy each delivery's `headers` (List-Unsubscribe, List-Unsubscribe-Post) onto the email, show
  each listing's `attribution`, and put `postalAddress` in the footer.
- MUST report every delivery's result (`POST /v1/deliveries/{deliveryId}/result`) and never send a
  delivery that expired (410).
- MUST verify the alerts webhook's `Ruuster-Signature` and skip an event id already handled.
- NEVER put a buyer's email in a link: links carry the `token` the delivery gives them.
- `POST /v1/buyers` creates the buyer, the agent and the first saved search in one call and is safe to
  repeat. A saved search's `criteria` are the `GET /v1/listings` parameters as a JSON object (no sort,
  page, limit, view, format or modifiedSince). A buyer has at most 25 saved searches.
- Alerts are sent as the search's agent, else the buyer's, else the default agent. Cadence is
  `instant` (at most 3 a buyer a day, then the daily digest), `daily` or `weekly`, at the send hour in
  the buyer's time zone.
- SDK: `idx.alerts.*` on a client created with `secretKey`.

- `GET /v1/agents`: List agents. Secret key.
- `POST /v1/agents`: Add an agent. Secret key.
- `GET /v1/agents/{alertAgentId}`: Get an agent. Secret key.
- `PATCH /v1/agents/{alertAgentId}`: Change an agent. Secret key.
- `DELETE /v1/agents/{alertAgentId}`: Archive an agent. Secret key.
- `POST /v1/agents/{alertAgentId}/default`: Make an agent the default. Secret key.
- `GET /v1/buyers`: List buyers. Secret key.
- `POST /v1/buyers`: Add a buyer (one call). Secret key.
- `GET /v1/buyers/{buyerId}`: Get a buyer. Secret key.
- `PATCH /v1/buyers/{buyerId}`: Change a buyer. Secret key.
- `DELETE /v1/buyers/{buyerId}`: Delete a buyer. Secret key.
- `POST /v1/buyers/{buyerId}/unsubscribe`: Unsubscribe a buyer. Secret key.
- `POST /v1/buyers/{buyerId}/resubscribe`: Resubscribe a buyer. Secret key.
- `GET /v1/saved-searches`: List saved searches. Secret key.
- `POST /v1/saved-searches`: Add a saved search. Secret key.
- `GET /v1/saved-searches/{searchId}`: Get a saved search. Secret key.
- `PATCH /v1/saved-searches/{searchId}`: Change a saved search. Secret key.
- `DELETE /v1/saved-searches/{searchId}`: Delete a saved search. Secret key.
- `GET /v1/deliveries`: List deliveries. Secret key.
- `GET /v1/deliveries/{deliveryId}`: Get a delivery. Secret key.
- `POST /v1/deliveries/{deliveryId}/ack`: Take a delivery. Secret key.
- `POST /v1/deliveries/{deliveryId}/result`: Report the result. Secret key.
- `POST /v1/deliveries/{deliveryId}/events`: Report email events. Secret key.
- `GET /v1/links/{alertToken}`: Read a buyer link. Secret key.
- `POST /v1/unsubscribe/{alertToken}`: One-click unsubscribe. No key (the token is the credential).
- `GET /v1/alerts/settings`: Alert settings. Secret key.
- `PATCH /v1/alerts/settings`: Change alert settings. Secret key.
- `GET /v1/alerts/credits`: Email credits. Secret key.

## 17. Saved searches for Ruuster Platform brokerages

A brokerage already on the Ruuster Platform keeps its saved searches in Ruuster, not in the Listing
Alerts tables: searches made on its website or its agent portal appear on the client's page in the
Ruuster app, and alerts go out the way the brokerage already sends them. Guide:
help.ruuster.com/idx/guide-platform-saved-searches.

- MUST call the `/v1/platform/*` endpoints from the server with the secret key, plus the signed-in
  person's session in `X-Idx-Session`. NEVER put the key or the session in the browser.
- Get a session with `POST /v1/platform/session` from the one-time sign-in token Ruuster's sign-in
  hand-off gives the server. NEVER send a user id or a role: the session carries both.
- Buyers use `/v1/platform/me/searches` (their own searches). Agents use `/v1/platform/agent/*` and
  may set up one search for several clients at once. Ruuster decides which clients an agent reaches;
  one out of reach answers 404 like an unknown one.
- MUST send an `Idempotency-Key` with every create.
- `criteria` are the `GET /v1/listings` parameters as a JSON object, the account's `f.` filters
  included; a filter or location that can't be saved answers 422 with the field named.
- SDK: `idx.platform.*` on a client created with `secretKey`.

- `POST /v1/platform/session`: Start a session. Secret key.
- `GET /v1/platform/session`: Who the session is for. Secret key, plus the session.
- `POST /v1/platform/session/refresh`: Refresh a session. Secret key, plus the session.
- `DELETE /v1/platform/session`: Sign out. Secret key, plus the session.
- `GET /v1/platform/me/searches`: The buyer's saved searches. Secret key, plus the session.
- `POST /v1/platform/me/searches`: Save a search for the buyer. Secret key, plus the session and an Idempotency-Key.
- `GET /v1/platform/me/searches/{coreSearchId}`: One of the buyer's searches. Secret key, plus the session.
- `PATCH /v1/platform/me/searches/{coreSearchId}`: Change one of the buyer's searches. Secret key, plus the session.
- `POST /v1/platform/me/searches/{coreSearchId}/pause`: Pause one of the buyer's searches. Secret key, plus the session.
- `POST /v1/platform/me/searches/{coreSearchId}/resume`: Resume one of the buyer's searches. Secret key, plus the session.
- `DELETE /v1/platform/me/searches/{coreSearchId}`: Delete one of the buyer's searches. Secret key, plus the session.
- `POST /v1/platform/agent/searches`: Set up a search for clients. Secret key, plus the session and an Idempotency-Key.
- `GET /v1/platform/agent/clients/{coreClientId}/searches`: A client's saved searches. Secret key, plus the session.
- `GET /v1/platform/agent/searches/{coreSearchId}`: One search. Secret key, plus the session.
- `PATCH /v1/platform/agent/searches/{coreSearchId}`: Change a search. Secret key, plus the session.
- `POST /v1/platform/agent/searches/{coreSearchId}/pause`: Pause a search. Secret key, plus the session.
- `POST /v1/platform/agent/searches/{coreSearchId}/resume`: Resume a search. Secret key, plus the session.
- `DELETE /v1/platform/agent/searches/{coreSearchId}`: Delete a search. Secret key, plus the session.

## Appendix: the example site's code

The complete Next.js App Router example the recipes build on. Paths are relative to the site's root,
and `@/` is the site's root in `tsconfig.json` `paths`. Replace the example areas in
`content/areas.ts` with rows from the person's own `/v1/suggest` answers.

### package.json

The packages the site uses.

```json
{
  "name": "ruuster-idx-nextjs-example",
  "version": "0.1.0",
  "private": true,
  "description": "A complete Next.js App Router site on the Ruuster Listings API: search, area, sold and listing pages, sitemaps, webhooks and CRM lead routes.",
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@ruuster/idx": "0.2.0",
    "@ruuster/idx-recipes": "0.2.0",
    "next": "^14.2.0",
    "react": "^18.3.0",
    "react-dom": "^18.3.0"
  }
}
```

### next.config.mjs

Next.js settings.

```js
// Next.js settings for this site. Listing photos are plain <img> elements with their own width and
// height (the recipe components set them), so no image domains are needed here.
/** @type {import("next").NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  // Inside the Ruuster repository, tsconfig.json points both packages at their TypeScript sources,
  // so Next.js compiles them here. Installed from npm, they are plain JavaScript and need neither line.
  transpilePackages: ["@ruuster/idx", "@ruuster/idx-recipes"],
  // Inside the Ruuster repository, tsconfig.json points the packages at ../../packages, outside this
  // folder; this lets Next.js compile them there. A project that installs the packages from npm can
  // leave it out.
  experimental: { externalDir: true },
};

export default nextConfig;
```

### .env.example

Every environment variable, with no values.

```bash
# Ruuster Listings API. Copy this file to .env.local and fill in your values. Never commit .env.local.

# Your secret key (idx_sk_...). Server only: never in browser code, a URL, a log or a chat.
IDX_SECRET_KEY=
# Pages carry no key: the search box, the filters and the mortgage calculator call your own route at
# /api/idx (app/api/idx/[...path]/route.ts), which adds the secret key on the server.
# Not used: leave it unset. No page reads it, even when the setup command writes it.
NEXT_PUBLIC_IDX_KEY=
# Leave it unset, so the client and the route call the Ruuster Listings API itself.
IDX_BASE_URL=

# Your site's origin with no trailing slash, for canonical URLs and sitemaps, such as https://www.example.com
SITE_ORIGIN=
# Your brokerage's name. Visitors see it, and your CRM shows it as the lead source.
SITE_NAME=

# The agent or office your listing pages offer for questions and tours (yours, not the listing agent).
# The photo is an https URL of a square headshot or logo. The license number shows when you set it.
SITE_AGENT_NAME=
SITE_AGENT_PHOTO_URL=
SITE_AGENT_PHONE=
SITE_AGENT_EMAIL=
SITE_AGENT_LICENSE=

# Your own Google Maps JavaScript API key and Map ID, restricted to your domains.
NEXT_PUBLIC_GOOGLE_MAPS_KEY=
NEXT_PUBLIC_GOOGLE_MAP_ID=

# Your Google Tag Manager container ID (GTM-XXXXXXX), if you load the GA4 container.
NEXT_PUBLIC_GTM_ID=

# The signing secret of your listing-change webhook (two comma-separated values while you rotate it).
RUUSTER_WEBHOOK_SECRET=

# Your CRM. Fill in the one you use.
FUB_API_KEY=
FUB_SYSTEM=
FUB_SYSTEM_KEY=
# A long random string that signs the cookie linking listing views to a registered visitor.
# Make one with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
FUB_COOKIE_SECRET=
SIERRA_API_KEY=
SURESEND_API_KEY=
```

### lib/site.ts

Your site's name, origin, listing URL template, consent wording and where forms post.

```ts
// Your site's own settings. Every page, form and sitemap reads them from here.
import type { DetailAgent } from "@ruuster/idx-recipes";

/** Your brokerage's name as visitors see it. It is also the lead source your CRM shows. */
export const SITE_NAME = process.env.SITE_NAME || "Your Brokerage";

/** Your site's origin, with no trailing slash, for canonical URLs, sitemaps and pageHref. */
export const SITE_ORIGIN = (process.env.SITE_ORIGIN || "http://localhost:3000").replace(/\/+$/, "");

/** Where every form posts its lead: your own server route, which sends it to your CRM. */
export const LEADS_ACTION = "/api/leads/fub";

/** Your search page. The listing page's Back link and its X return here. */
export const SEARCH_PATH = "/search";

/** Your listing page URL template. The API builds each card's href from it. */
export const DETAIL_HREF = "/homes/{slug}";

/** A collection you curate in Ruuster for the homepage strip. Leave it null to show your own listings. */
export const FEATURED_COLLECTION_ID: string | null = null;

/** The consent sentence beside the contact box on every form. Edit it with your own wording. */
export const CONSENT_TEXT = `I agree that ${SITE_NAME} may contact me by phone, text or email about this request.`;

/** The consent sentence beside the separate listing-alerts box. */
export const ALERTS_CONSENT_TEXT = "Email me new listings like this one. I can unsubscribe at any time.";

/**
 * The agent or office your listing pages offer for questions and tours: the contact card, the
 * mobile action bar and the contact form are about this person. Use your own agent or your office's
 * team inbox, never the listing agent from the MLS. Leave a value unset and the page leaves that
 * line out; with no name, the buttons read "Contact an agent".
 */
export const SITE_AGENT: DetailAgent = {
  name: process.env.SITE_AGENT_NAME || null,
  photoUrl: process.env.SITE_AGENT_PHOTO_URL || null,
  phone: process.env.SITE_AGENT_PHONE || null,
  email: process.env.SITE_AGENT_EMAIL || null,
  license: process.env.SITE_AGENT_LICENSE || null,
  brokerage: SITE_NAME,
};

/** An absolute URL on your site for a path such as "/homes/123-main-st-…". */
export function absoluteUrl(path: string): string {
  if (/^https?:\/\//i.test(path)) return path;
  return `${SITE_ORIGIN}${path.startsWith("/") ? "" : "/"}${path}`;
}
```

### lib/idx.ts

The one API client for server code, with the secret key.

```ts
// The one Ruuster Listings API client this site uses on the server.
// IDX_SECRET_KEY never reaches the browser: only server components and route handlers import this file.
import "server-only";
import { createClient } from "@ruuster/idx";
import { DETAIL_HREF, SITE_ORIGIN } from "@/lib/site";

export const idx = createClient({
  secretKey: process.env.IDX_SECRET_KEY,
  // Leave IDX_BASE_URL unset, so the client calls the Ruuster Listings API itself.
  baseUrl: process.env.IDX_BASE_URL || undefined,
  detailHref: DETAIL_HREF,
  siteOrigin: SITE_ORIGIN,
  // Next.js keeps each answer for 5 minutes; the listing-change webhook refreshes pages sooner.
  next: { revalidate: 300 },
});

/**
 * GET /v1/meta: your brand variables, capabilities, compliance rules and organization block.
 * Next.js answers repeated identical requests in one render from memory, so every page may call it.
 */
export function getMeta() {
  return idx.meta();
}

export { fmt, listingPath, parseListingSlug, toMetadata } from "@ruuster/idx";
```

### lib/area-query.ts

The search each results page sends, built from the page's URL.

```ts
// Turns an area and the page's URL into the search the page sends.
// The area fixes the location; the visitor's URL may add filters, a sort order and a page.
import { fromSearchParams, type SearchParamsInput, type SearchQuery } from "@ruuster/idx";
import type { Area } from "@/content/areas";

/** A search that answers listing cards (the default view). */
export type CardQuery = Omit<SearchQuery, "view">;

/** URL names a visitor may not change on an area page: the location, the key-level options and the page size. */
const FIXED = ["where", "bbox", "polygon", "boundariesId", "zip", "city", "state", "shape", "ownListings", "agent", "office", "view", "detailHref", "pageHref", "indexable", "limit"] as const;

/** Results per page on every results page of this site. */
export const PAGE_SIZE = 24;

/** The visitor's filters, sort and page from the URL, without anything that would change the location. */
export function visitorQuery(searchParams: SearchParamsInput): CardQuery {
  const q: Record<string, unknown> = { ...fromSearchParams(searchParams) };
  for (const k of FIXED) delete q[k];
  return q as CardQuery;
}

/** The API's default order; there is no "newest" sort. */
/** /neighborhoods/<slug>: the area's active listings in the API's recommended order unless the visitor picked another. */
export function areaQuery(area: Area, searchParams: SearchParamsInput): CardQuery {
  return {
    ...visitorQuery(searchParams),
    status: "active",
    where: area.where,
    limit: PAGE_SIZE,
    pageHref: `/neighborhoods/${area.slug}`,
  };
}

/** /neighborhoods/<slug>/sold: homes sold in the last 6 months, most recent first. */
export function soldQuery(area: Area, searchParams: SearchParamsInput): CardQuery {
  const v = visitorQuery(searchParams);
  return {
    ...v,
    status: "closed",
    soldPeriod: "6m",
    sort: "close_date_desc",
    where: area.where,
    limit: PAGE_SIZE,
    pageHref: `/neighborhoods/${area.slug}/sold`,
  };
}

/** True when the query names a location (or own, agent or office listings), which every search needs. */
export function hasLocation(q: SearchQuery): boolean {
  const where = Array.isArray(q.where) ? q.where.length > 0 : Boolean(q.where);
  return where || Boolean(q.bbox || q.polygon || q.boundariesId || q.zip || q.city || q.state || q.shape || q.ownListings || q.agent || q.office);
}

/**
 * True when at least one of your boards shows sold data (GET /v1/meta capabilities.sold).
 * Sold pages are published only then.
 */
export function showsSoldData(capabilities: Readonly<Record<string, unknown>> | null | undefined): boolean {
  const sold = capabilities?.sold;
  return Array.isArray(sold) && sold.some((b) => typeof b === "object" && b !== null && (b as { allowed?: unknown }).allowed === true);
}
```

### lib/results.ts

What a results page does with each failure, and its metadata.

```ts
// What a page does with an API answer that is not a success, and the head tags of a results page.
import { toMetadata, type IdxFailure, type PageHead } from "@ruuster/idx";

/** The error codes after which the page should not exist at all (HTTP 404). */
const PAGE_DOES_NOT_EXIST = new Set(["not_found", "boundary_not_found", "agent_not_found", "shape_not_found", "mls_not_in_scope", "location_not_supported", "filter_not_supported", "sold_not_permitted", "own_listings_unconfigured"]);

/**
 * "not_found": answer 404 (call notFound()).
 * "throw": throw, so Next.js keeps serving the last good page and tries again later (429, 503, network).
 * "empty": render the page with no listings (a filter value the visitor typed was refused).
 */
export function failureAction(r: Pick<IdxFailure, "status" | "error">): "not_found" | "throw" | "empty" {
  if (r.status === 404 || PAGE_DOES_NOT_EXIST.has(r.error.code)) return "not_found";
  if (r.error.retryable || r.status === 0 || r.status === 429 || r.status >= 500) return "throw";
  return "empty";
}

/** The number of result pages: the API's own `pages` when the answer carries it. */
export function pageCount(data: { total: number; limit: number; pages?: number }): number {
  if (typeof data.pages === "number") return data.pages;
  if (data.total <= 0 || data.limit <= 0) return 0;
  // The API pages through the first 2,000 results of a search.
  return Math.min(Math.ceil(data.total / data.limit), Math.floor(2000 / data.limit));
}

/** Next.js metadata for a results page: the head the API built, or a plain title until it has one. */
export function resultsMetadata(head: PageHead | undefined, fallbackTitle: string) {
  return head ? toMetadata(head) : { title: fallbackTitle };
}
```

### components/results.tsx

The cards, page links, map, disclaimers and JSON-LD of every results page.

```tsx
// The body of every results page: cards, pagination, the map, the MLS disclaimers and the JSON-LD.
import type { IdxSuccess, ListingCard, SearchResult } from "@ruuster/idx";
import { AreaMap, JsonLd, ListingGrid, MlsDisclaimers, Pagination } from "@ruuster/idx-recipes";
import { idx } from "@/lib/idx";
import { pageCount } from "@/lib/results";

type Props = {
  r: IdxSuccess<SearchResult<ListingCard>>;
  /** The page's own path, for the pagination links. */
  basePath: string;
  searchParams?: Readonly<Record<string, string | readonly string[] | undefined>>;
  /** GA4 item_list_name for the cards. */
  listName: string;
  emptyText?: string;
  /** Draw the map (needs NEXT_PUBLIC_GOOGLE_MAPS_KEY). */
  map?: boolean;
  /** The page's own path and query, which the map's "Search this area" and drawing tools start from. */
  searchHref?: string;
};

export async function Results({ r, basePath, searchParams, listName, emptyText, map = true, searchHref }: Props) {
  const mls = r.meta.mls;
  const mapsKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_KEY;
  // The outline of the searched area, when the search was a boundary and the map is on.
  const b = map && mapsKey && r.data.boundary ? await idx.boundary(r.data.boundary.id) : null;
  const boundary = b?.ok ? b.data.geometry : null;
  return (
    <>
      <ListingGrid listings={r.data.listings} mls={mls} ga4ListName={listName} emptyText={emptyText ?? "No homes match this search right now."} />
      <Pagination page={r.data.page} pages={pageCount(r.data)} basePath={basePath} searchParams={searchParams} />
      {map && mapsKey && r.data.listings.length > 0 ? (
        <AreaMap googleMapsKey={mapsKey} mapId={process.env.NEXT_PUBLIC_GOOGLE_MAP_ID || null} viewport={r.data.viewport} boundary={boundary} boundaryKind={b?.ok ? b.data.kind : null} listings={r.data.listings} mls={mls} searchHref={searchHref} drawing={Boolean(searchHref)} />
      ) : null}
      <MlsDisclaimers mls={mls} asOf={r.meta.freshness.asOf} />
      <JsonLd docs={r.data.jsonLd ?? []} />
    </>
  );
}
```

### content/areas.ts

Your area pages, each with the `where` row stored exactly as /v1/suggest returned it.

```ts
// The places you sell in: one entry per area page. This file is your own content.
//
// `where` is the row GET /v1/suggest answered for the place, copied in once and never edited by
// hand. To get one, run (with your secret key in your shell, never in a chat):
//   curl -s "https://idx.ruuster.com/v1/suggest?q=Midtown&groups=neighborhood" -H "Authorization: Bearer $IDX_SECRET_KEY"
// and paste the `where` object of the row you want.
// The two areas below are example rows; replace them with your own.
import type { WhereObject } from "@ruuster/idx";

export type AreaQuestion = { question: string; answer: string };

export type Area = {
  /** The URL segment: /neighborhoods/<slug>. */
  slug: string;
  /** The name you show in headings and links. */
  name: string;
  /** The /v1/suggest row for this place, unchanged. */
  where: WhereObject;
  /** Publish /neighborhoods/<slug>/sold. The page also checks that your boards show sold data. */
  soldPage: boolean;
  /** Your agents' own words about the area: the streets, the housing, what buyers ask about. */
  ownWords: readonly string[];
  /** Questions you answer yourself, shown after the market questions. Each answer starts with the answer. */
  questions: readonly AreaQuestion[];
};

export const AREAS: readonly Area[] = [
  {
    slug: "midtown",
    name: "Midtown",
    where: { label: "Atlanta, GA Midtown", value: "a0000000-0000-4000-8000-000000000001", source: "neighborhood", data: { state: "GA" } },
    soldPage: true,
    ownWords: [
      "Midtown mixes high-rise condos along Peachtree Street with brick bungalows on the quieter side streets east of the park.",
      "Most condo buildings here have a monthly association fee that covers the pool, the gym and building insurance, so ask for the budget early.",
    ],
    questions: [
      {
        question: "What kinds of homes are in Midtown?",
        answer: "Mostly condos in mid-rise and high-rise buildings, with single-family homes and townhomes on the side streets.",
      },
    ],
  },
  {
    slug: "atlanta",
    name: "Atlanta",
    where: { label: "Atlanta, GA", value: "Atlanta", source: "crm-system", data: { state: "GA", city: "Atlanta" }, city: "Atlanta", state: "GA" },
    soldPage: true,
    ownWords: ["Atlanta's listings range from downtown lofts to wooded lots inside the Perimeter, and every neighborhood has its own page on this site."],
    questions: [],
  },
];

/** The area the site-wide pages (open houses, price reduced, new construction) search in. */
export const MARKET_AREA: Area = AREAS[AREAS.length - 1];

export function areaBySlug(slug: string): Area | null {
  return AREAS.find((a) => a.slug === slug) ?? null;
}
```

### content/answer.ts

The dated answer sentence at the top of an area page, from /v1/market.

```ts
// The answer at the top of an area page: one sentence with today's numbers and the date, then the
// questions people ask about the area, each answered in its first sentence (plain market facts only).
import type { MarketData, MarketSeries } from "@ruuster/idx";
import { fmt, idx } from "@/lib/idx";
import type { Area, AreaQuestion } from "@/content/areas";

export type AreaAnswer = {
  /** The lead sentence: homes for sale, prices, days on market, the date. */
  lead: string;
  /** Market questions with their answers (a question whose number is missing is left out). */
  questions: AreaQuestion[];
  /** The date the numbers are from (ISO). */
  asOf: string;
};

const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

/** "2026-10" → "October 2026". */
export function monthName(month: string): string {
  const m = /^(\d{4})-(\d{2})$/.exec(month);
  if (!m) return month;
  return `${MONTHS[Number(m[2]) - 1] ?? m[2]} ${m[1]}`;
}

/** The latest month of a series that has a value, or null. */
export function latestPoint(s: MarketSeries | undefined): { month: string; value: number } | null {
  if (!s) return null;
  for (let i = s.series.length - 1; i >= 0; i--) {
    const p = s.series[i];
    if (p.value !== null) return { month: p.month, value: p.value };
  }
  return null;
}

/** Builds the answer from a GET /v1/market answer. Pure: the page passes the data in. */
export function answerFromMarket(market: MarketData, areaName: string): AreaAnswer {
  const m = market.measures;
  const updated = `Updated ${fmt.date(market.asOf)}.`;
  const sentences: string[] = [];

  const inventory = m.activeInventory?.current ?? null;
  const asking = m.medianListPrice?.current ?? null;
  if (inventory !== null && asking !== null) {
    sentences.push(`${areaName} has ${fmt.count(inventory)} ${inventory === 1 ? "home" : "homes"} for sale today, at a median asking price of ${fmt.usd(asking)}.`);
  } else if (inventory !== null) {
    sentences.push(`${areaName} has ${fmt.count(inventory)} ${inventory === 1 ? "home" : "homes"} for sale today.`);
  }

  const sold = latestPoint(m.medianSoldPrice);
  const ratio = m.listToSaleRatio?.current ?? null;
  const dom = m.medianDaysOnMarket?.current ?? null;
  if (sold) {
    let s = `Homes that sold in ${monthName(sold.month)} closed at a median of ${fmt.usd(sold.value)}`;
    if (ratio !== null) s += `, or ${(ratio * 100).toFixed(1)}% of asking`;
    if (dom !== null) s += `, after ${fmt.count(dom)} days on market`;
    sentences.push(`${s}.`);
  }
  sentences.push(updated);

  const questions: AreaQuestion[] = [];
  if (sold) {
    const change = fmt.change(m.medianSoldPrice, 12);
    const year = Number(sold.month.slice(0, 4)) - 1;
    const since = change ? ` That is a change of ${change} from ${monthName(`${year}${sold.month.slice(4)}`)}.` : "";
    questions.push({ question: `What is the median home price in ${areaName}?`, answer: `${fmt.usd(sold.value)} for homes sold in ${monthName(sold.month)}.${since}` });
  } else if (asking !== null) {
    questions.push({ question: `What is the median home price in ${areaName}?`, answer: `The median asking price of the homes for sale today is ${fmt.usd(asking)}.` });
  }
  const supply = m.monthsOfSupply?.current ?? null;
  if (dom !== null || supply !== null) {
    const parts: string[] = [];
    if (dom !== null && sold) parts.push(`The median home sold in ${fmt.count(dom)} days in ${monthName(sold.month)}.`);
    else if (dom !== null) parts.push(`The median home sold in ${fmt.count(dom)} days.`);
    if (supply !== null) parts.push(`At the current pace of sales, the homes for sale today would sell in ${fmt.count(supply)} months.`);
    questions.push({ question: `How fast are homes selling in ${areaName}?`, answer: parts.join(" ") });
  }
  const fresh = latestPoint(m.newListings);
  if (inventory !== null) {
    let a = `${fmt.count(inventory)} ${inventory === 1 ? "home is" : "homes are"} for sale today.`;
    if (fresh) a += ` ${fmt.count(fresh.value)} new ${fresh.value === 1 ? "listing" : "listings"} came on the market in ${monthName(fresh.month)}.`;
    questions.push({ question: `How many homes are for sale in ${areaName}?`, answer: a });
  }

  return { lead: sentences.join(" "), questions, asOf: market.asOf };
}

/** GET /v1/market for the area (13 months, so the change against a year earlier has both ends), then the answer. */
export async function areaAnswer(area: Area): Promise<{ answer: AreaAnswer; market: MarketData } | null> {
  const r = await idx.market({ where: area.where, months: 13 });
  if (!r.ok) return null;
  return { answer: answerFromMarket(r.data, area.name), market: r.data };
}
```

### app/layout.tsx

The layout: brand styles, the organization JSON-LD and the Equal Housing Opportunity notice.

```tsx
// The site shell: the recipes' stylesheet in your brand colors, your organization's JSON-LD, the
// header and footer. app/site.css lays out the page around the components in the same brand colors.
import type { ReactNode } from "react";
import Link from "next/link";
import { JsonLd, RecipesStyles } from "@ruuster/idx-recipes";
import { getMeta } from "@/lib/idx";
import { SITE_NAME, SITE_ORIGIN } from "@/lib/site";
import "./site.css";

export const metadata = {
  metadataBase: new URL(SITE_ORIGIN),
  title: SITE_NAME,
};

export default async function RootLayout({ children }: { children: ReactNode }) {
  const meta = await getMeta();
  return (
    <html lang="en">
      <head>
        <link rel="preconnect" href="https://photos.ruuster.com" />
      </head>
      <body>
        <RecipesStyles themeVars={meta.ok ? meta.data.themeVars : undefined} />
        {meta.ok && meta.data.organization?.jsonLd ? <JsonLd docs={meta.data.organization.jsonLd} /> : null}
        <div className="rw-recipes site">
        <header className="site-header">
          <div className="site-header__inner">
            <Link href="/" className="site-brand">
              {SITE_NAME}
            </Link>
            <nav aria-label="Main" className="site-nav">
              <Link href="/search">Search</Link>
              <Link href="/neighborhoods">Neighborhoods</Link>
              <Link href="/our-listings">Our listings</Link>
              <Link href="/open-houses">Open houses</Link>
              <Link href="/search" className="site-cta">
                Find a home
              </Link>
            </nav>
          </div>
        </header>
        <div className="site-main">{children}</div>
        <footer className="site-footer">
          <div className="site-footer__inner">
            <span className="site-footer__brand">{SITE_NAME}</span>
            <p>
              Equal Housing Opportunity. {SITE_NAME} follows the Fair Housing Act and does not discriminate on the basis of race, color, religion,
              sex, disability, familial status or national origin.
            </p>
          </div>
        </footer>
        </div>
      </body>
    </html>
  );
}
```

### app/search/page.tsx

The search page: the filter bar with its drawer, the results toolbar, and the grid or the map.

```tsx
// /search: the first page of results is rendered on the server from the URL. The search box and the
// filters write the API's own parameter names into the URL, so every search has a shareable link.
// The API marks searches with visitor-picked filters noindex,follow, so your area pages are the ones that rank.
// Above the results: the filter bar (quick filters on wide screens, then "More filters" with the
// drawer, which lists every filter your account offers from GET /v1/filters) and the toolbar (the count, the sort order and the Grid and Map switch). `?view=map` swaps
// the grid for a full-width map; loading.tsx shows the card outlines while a search runs.
import { notFound } from "next/navigation";
import { fromSearchParams } from "@ruuster/idx";
import { Filters, ResultsToolbar, SearchBox } from "@ruuster/idx-recipes";
import Link from "next/link";
import { FeaturedStrip } from "@/components/featured-strip";
import { MapResults } from "@/components/map-results";
import { Results } from "@/components/results";
import { AREAS } from "@/content/areas";
import { idx } from "@/lib/idx";
import { hasLocation, PAGE_SIZE, type CardQuery } from "@/lib/area-query";
import { failureAction, resultsMetadata } from "@/lib/results";
import { currentHref, filterValue, SEARCH_KEEP, searchView } from "@/lib/search-view";

type Props = { searchParams: Record<string, string | string[] | undefined> };

function searchQuery(searchParams: Props["searchParams"]): CardQuery {
  return { ...fromSearchParams(searchParams), limit: PAGE_SIZE, pageHref: "/search" };
}

export async function generateMetadata({ searchParams }: Props) {
  const q = searchQuery(searchParams);
  if (!hasLocation(q)) return { title: "Search homes for sale", robots: "noindex,follow" };
  const r = await idx.search(q);
  return r.ok ? resultsMetadata(r.data.head, "Homes for sale") : { title: "Search homes for sale", robots: "noindex,follow" };
}

export default async function SearchPage({ searchParams }: Props) {
  const q = searchQuery(searchParams);
  const box = <SearchBox action="/search" baseUrl="/api/idx" />;
  if (!hasLocation(q)) {
    return (
      <main>
        <h1>Search homes for sale</h1>
        {box}
        <p>Type a city, neighborhood, ZIP code or school, then pick it from the list.</p>
        {/* Before a place is picked: your area pages and your own listings, server-rendered with real links. */}
        <section aria-labelledby="popular-areas">
          <h2 id="popular-areas">Popular areas</h2>
          <ul className="site-chips">
            {AREAS.map((a) => (
              <li key={a.slug}>
                <Link href={`/neighborhoods/${a.slug}`}>{a.name}</Link>
              </li>
            ))}
          </ul>
        </section>
        <FeaturedStrip title="Homes we're listing now" />
      </main>
    );
  }
  const view = searchView(searchParams);
  // The grid asks for one page of cards; the map view asks for up to 200 price pins instead.
  const cards = view === "list" ? await idx.search(q) : null;
  const pins = view === "map" ? await idx.search({ ...q, view: "map", limit: undefined, pageHref: undefined }) : null;
  const r = cards ?? pins!;
  if (!r.ok) {
    const action = failureAction(r);
    if (action === "not_found") notFound();
    if (action === "throw") throw new Error(`Listings API ${r.status} ${r.error.code}`);
    return (
      <main>
        <h1>Search homes for sale</h1>
        {box}
        <p>We could not run that search. Try another place or fewer filters.</p>
      </main>
    );
  }
  const here = currentHref("/search", searchParams);
  // Your account's own filters, in the order your panel shows them. If the call fails, the drawer
  // keeps the basic controls (price, beds, baths, type, status, sort).
  const filters = await idx.filters();
  return (
    <main>
      <h1>{r.data.location?.label ? `Homes for sale in ${r.data.location.label}` : "Homes for sale"}</h1>
      <Filters
        value={filterValue(q, searchParams)}
        action="/search"
        layout="bar"
        keep={SEARCH_KEEP}
        search={box}
        filters={filters.ok ? filters.data : undefined}
        baseUrl="/api/idx"
      />
      <ResultsToolbar total={r.data.total} view={view} basePath="/search" searchParams={searchParams} />
      {pins?.ok ? <MapResults r={pins} searchHref={here} /> : null}
      {cards?.ok ? <Results r={cards} basePath="/search" searchParams={searchParams} listName="Search results" searchHref={here} /> : null}
    </main>
  );
}
```

### app/search/loading.tsx

The search page while it loads: the counter and card placeholders.

```tsx
// What the search page shows while a search runs: the count's outline and eight card outlines in the
// grid's own columns, with a soft shimmer that appears only when the wait passes 200 milliseconds.
import { ListingGridSkeleton, ResultsCountSkeleton } from "@ruuster/idx-recipes";

export default function SearchLoading() {
  return (
    <main>
      <h1>Search homes for sale</h1>
      <ResultsCountSkeleton />
      <ListingGridSkeleton count={8} />
    </main>
  );
}
```

### lib/search-view.ts

Reads the grid or map view and the filter values from the search page's URL.

```ts
// The search page's two views and the parts of its URL the filters and the map keep.
import type { SearchParamsInput, SearchQuery } from "@ruuster/idx";

/** The grid of cards (the default) or the full-width map (`?view=map`). */
export type SearchView = "list" | "map";

/** `view=map` shows the map; anything else shows the grid. */
export function searchView(searchParams: SearchParamsInput): SearchView {
  const raw = searchParams instanceof URLSearchParams ? searchParams.get("view") : searchParams.view;
  const v = Array.isArray(raw) ? raw[0] : raw;
  return v === "map" ? "map" : "list";
}

/**
 * The parameters the filter forms carry as hidden fields: the location the visitor picked, the area
 * they drew or moved the map to, and the view, so a filter change keeps the same place and view.
 */
export const SEARCH_KEEP: readonly string[] = ["where", "boundariesId", "zip", "city", "state", "shape", "bbox", "polygon", "view"];

/**
 * The query the filter forms start from: the search itself, plus the two things a filter change must
 * keep that the search does not hold as text, the map view and the map box as the URL wrote it.
 */
export function filterValue(q: SearchQuery, searchParams: SearchParamsInput): SearchQuery {
  const out: SearchQuery = { ...q };
  if (searchView(searchParams) === "map") out.view = "map";
  const raw = searchParams instanceof URLSearchParams ? searchParams.get("bbox") : searchParams.bbox;
  const bbox = Array.isArray(raw) ? raw[0] : raw;
  if (typeof bbox === "string" && q.bbox) out.bbox = bbox;
  return out;
}

/** The page's own path and query, which the map's "Search this area" and drawing tools start from. */
export function currentHref(basePath: string, searchParams: SearchParamsInput): string {
  const q = new URLSearchParams();
  const pairs: [string, string][] =
    searchParams instanceof URLSearchParams
      ? Array.from(searchParams.entries())
      : Object.entries(searchParams).flatMap(([k, v]) => (v === undefined ? [] : (Array.isArray(v) ? v : [v]).map((one): [string, string] => [k, String(one)])));
  for (const [k, v] of pairs) q.append(k, v);
  const s = q.toString();
  return s ? `${basePath}?${s}` : basePath;
}
```

### components/map-results.tsx

The full-width map view of a search, with up to 200 pins.

```tsx
// The search page's map view: up to 200 price pins over the full width, the area's outline, the map's
// drawing tools and "Search this area", then every board's disclaimer. The grid view is results.tsx.
import type { IdxSuccess, ListingPin, SearchResult } from "@ruuster/idx";
import { AreaMap, MlsDisclaimers } from "@ruuster/idx-recipes";
import { idx } from "@/lib/idx";

type Props = {
  r: IdxSuccess<SearchResult<ListingPin>>;
  /** The page's own path and query (lib/search-view.ts currentHref), which the map tools start from. */
  searchHref: string;
};

export async function MapResults({ r, searchHref }: Props) {
  const mls = r.meta.mls;
  const mapsKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_KEY;
  const b = mapsKey && r.data.boundary ? await idx.boundary(r.data.boundary.id) : null;
  return (
    <>
      {/* Without NEXT_PUBLIC_GOOGLE_MAPS_KEY the frame asks for the key, so a missing key shows in development. */}
      <AreaMap
        googleMapsKey={mapsKey ?? ""}
        mapId={process.env.NEXT_PUBLIC_GOOGLE_MAP_ID || null}
        viewport={r.data.viewport}
        boundary={b?.ok ? b.data.geometry : null}
        boundaryKind={b?.ok ? b.data.kind : null}
        listings={r.data.listings}
        mls={mls}
        searchHref={searchHref}
      />
      <MlsDisclaimers mls={mls} asOf={r.meta.freshness.asOf} />
    </>
  );
}
```

### app/neighborhoods/[area]/page.tsx

An area page.

```tsx
// /neighborhoods/<area>: an area page built to rank and to be quoted by AI assistants.
// Top to bottom: the one-sentence answer with today's numbers and the date, the market tiles, the
// questions people ask (each an <h2> answered in its first sentence), your own words, then the
// listings, pagination, the map, the MLS disclaimers and the JSON-LD.
import Link from "next/link";
import { notFound } from "next/navigation";
import { Filters, MarketStats } from "@ruuster/idx-recipes";
import { Results } from "@/components/results";
import { areaAnswer } from "@/content/answer";
import { AREAS, areaBySlug } from "@/content/areas";
import { getMeta, idx } from "@/lib/idx";
import { areaQuery, showsSoldData } from "@/lib/area-query";
import { failureAction, resultsMetadata } from "@/lib/results";

export const revalidate = 300;

type Props = { params: { area: string }; searchParams: Record<string, string | string[] | undefined> };

export function generateStaticParams() {
  return AREAS.map((a) => ({ area: a.slug }));
}

export async function generateMetadata({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area) return {};
  const r = await idx.search(areaQuery(area, searchParams));
  return r.ok ? resultsMetadata(r.data.head, `Homes for sale in ${area.name}`) : {};
}

export default async function AreaPage({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area) notFound();
  const q = areaQuery(area, searchParams);
  const [r, answer, meta] = await Promise.all([idx.search(q), areaAnswer(area), getMeta()]);
  if (!r.ok) {
    const action = failureAction(r);
    if (action === "not_found") notFound();
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  const sold = area.soldPage && meta.ok && showsSoldData(meta.data.capabilities);
  return (
    <main>
      <nav aria-label="Breadcrumb">
        <Link href="/neighborhoods">Neighborhoods</Link> › {area.name}
      </nav>
      <h1>{`Homes for sale in ${area.name}`}</h1>
      {answer ? <p>{answer.answer.lead}</p> : null}
      {answer ? <MarketStats market={answer.market} /> : null}
      {answer?.answer.questions.map((x) => (
        <section key={x.question}>
          <h2>{x.question}</h2>
          <p>{x.answer}</p>
        </section>
      ))}
      {area.questions.map((x) => (
        <section key={x.question}>
          <h2>{x.question}</h2>
          <p>{x.answer}</p>
        </section>
      ))}
      <section aria-labelledby="our-take">
        <h2 id="our-take">Our take on {area.name}</h2>
        {area.ownWords.map((p) => (
          <p key={p}>{p}</p>
        ))}
      </section>
      <h2>Listings in {area.name}</h2>
      <Filters value={q} action={`/neighborhoods/${area.slug}`} fields={["price", "beds", "baths", "type", "sort"]} keep={[]} />
      <Results r={r} basePath={`/neighborhoods/${area.slug}`} searchParams={searchParams} listName={`Homes for sale in ${area.name}`} />
      {sold ? (
        <p>
          <Link href={`/neighborhoods/${area.slug}/sold`}>Recently sold homes in {area.name}</Link>
        </p>
      ) : null}
    </main>
  );
}
```

### app/neighborhoods/[area]/sold/page.tsx

An area's recently sold homes, on boards that show sold data.

```tsx
// /neighborhoods/<area>/sold: homes sold in the last 6 months. Published only when at least one of
// your boards shows sold data (GET /v1/meta capabilities.sold); otherwise it links to the area page.
import Link from "next/link";
import { notFound } from "next/navigation";
import { Results } from "@/components/results";
import { AREAS, areaBySlug } from "@/content/areas";
import { getMeta, idx } from "@/lib/idx";
import { showsSoldData, soldQuery } from "@/lib/area-query";
import { failureAction, resultsMetadata } from "@/lib/results";

export const revalidate = 300;

type Props = { params: { area: string }; searchParams: Record<string, string | string[] | undefined> };

export function generateStaticParams() {
  return AREAS.filter((a) => a.soldPage).map((a) => ({ area: a.slug }));
}

async function soldAllowed(): Promise<boolean> {
  const meta = await getMeta();
  return meta.ok && showsSoldData(meta.data.capabilities);
}

export async function generateMetadata({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area?.soldPage) return {};
  if (!(await soldAllowed())) return { title: `Homes in ${area.name}`, robots: "noindex,follow" };
  const r = await idx.search(soldQuery(area, searchParams));
  return r.ok ? resultsMetadata(r.data.head, `Recently sold homes in ${area.name}`) : {};
}

export default async function SoldPage({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area?.soldPage) notFound();
  if (!(await soldAllowed())) {
    return (
      <main>
        <h1>{`Homes in ${area.name}`}</h1>
        <p>
          <Link href={`/neighborhoods/${area.slug}`}>See the homes for sale in {area.name}</Link>
        </p>
      </main>
    );
  }
  const r = await idx.search(soldQuery(area, searchParams));
  if (!r.ok) {
    const action = failureAction(r);
    if (action === "not_found") notFound();
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  return (
    <main>
      <nav aria-label="Breadcrumb">
        <Link href="/neighborhoods">Neighborhoods</Link> › <Link href={`/neighborhoods/${area.slug}`}>{area.name}</Link> › Recently sold
      </nav>
      <h1>{`Recently sold homes in ${area.name}`}</h1>
      <p>Homes that sold in the last 6 months, most recent first. Each card shows the sold price and date.</p>
      <Results r={r} basePath={`/neighborhoods/${area.slug}/sold`} searchParams={searchParams} listName={`Recently sold in ${area.name}`} />
    </main>
  );
}
```

### app/our-listings/page.tsx

Your brokerage's own listings.

```tsx
// /our-listings: your brokerage's own listings (your agents' and your confirmed offices').
// ownListings needs no location. Each card links to its listing page, where the tour form is.
import { notFound } from "next/navigation";
import { Results } from "@/components/results";
import { idx } from "@/lib/idx";
import { PAGE_SIZE, visitorQuery, type CardQuery } from "@/lib/area-query";
import { failureAction, resultsMetadata } from "@/lib/results";
import { SITE_NAME } from "@/lib/site";

export const revalidate = 300;

type Props = { searchParams: Record<string, string | string[] | undefined> };

function query(searchParams: Props["searchParams"]): CardQuery {
  return { ...visitorQuery(searchParams), ownListings: true, status: ["active", "coming_soon", "pending"], limit: PAGE_SIZE, pageHref: "/our-listings" };
}

export async function generateMetadata({ searchParams }: Props) {
  const r = await idx.search(query(searchParams));
  return r.ok ? resultsMetadata(r.data.head, `Listings from ${SITE_NAME}`) : {};
}

export default async function OurListings({ searchParams }: Props) {
  const r = await idx.search(query(searchParams));
  if (!r.ok) {
    if (failureAction(r) === "not_found") notFound();
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  return (
    <main>
      <h1>{`Listings from ${SITE_NAME}`}</h1>
      <Results r={r} basePath="/our-listings" searchParams={searchParams} listName="Our listings" emptyText="We have no listings on the market right now." />
    </main>
  );
}
```

### app/homes/[slug]/page.tsx

The listing page with every screen: the gallery, share, contact, tour booking and the mortgage calculator.

```tsx
// /homes/<slug>: one permanent page per listing, rendered on the server so the listing text, photos
// and links are in the first HTML. middleware.ts answers the status codes: 301 for an outdated slug
// and 410 for a listing that left the market; this page renders the 200, the 404 and the 410 body.
// loading.tsx shows the page's skeleton while the answer arrives, and not-found.tsx the 404.
import { notFound, permanentRedirect } from "next/navigation";
import { JsonLd, ListingDetail } from "@ruuster/idx-recipes";
import { ReportListingView } from "@/app/api/activity/fub/report-view";
import { Gone } from "@/components/gone";
import { idx, listingPath, parseListingSlug, toMetadata } from "@/lib/idx";
import { ALERTS_CONSENT_TEXT, CONSENT_TEXT, DETAIL_HREF, LEADS_ACTION, SEARCH_PATH, SITE_AGENT, absoluteUrl } from "@/lib/site";

export const revalidate = 300;

type Props = { params: { slug: string } };

export async function generateMetadata({ params }: Props) {
  const p = parseListingSlug(params.slug);
  if (!p) return {};
  const r = await idx.get(p.id);
  if (r.ok) return toMetadata(r.data.head);
  if (r.status === 410) return { title: "This home is no longer available", robots: "noindex,follow" };
  return {};
}

export default async function ListingPage({ params }: Props) {
  const p = parseListingSlug(params.slug);
  if (!p) notFound();
  const r = await idx.get(p.id);
  if (!r.ok) {
    if (r.status === 410) return <Gone listingId={p.id} />;
    if (r.status === 404) notFound();
    // 429, 503 or a network error: throw, so Next.js keeps serving the last good page.
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  // The address in the slug changed: send visitors and search engines to the current URL.
  // middleware.ts answers this with a 301 first; this line covers a request that skipped it.
  if (r.data.slug !== p.slug) permanentRedirect(listingPath(r.data, DETAIL_HREF));
  const pageUrl = absoluteUrl(listingPath(r.data, DETAIL_HREF));
  return (
    <main>
      <ListingDetail
        listing={r.data}
        mls={r.meta.mls}
        // The header's Back link and its X once the visitor scrolls: your search page.
        backHref={SEARCH_PATH}
        // Your agent or office for the contact card, the mobile bar and the contact form.
        agent={SITE_AGENT}
        // With both set, the page shows the contact and tour cards, the mobile action bar, the
        // open-house tour row and the contact and tour forms, which post to your own route.
        leadAction={LEADS_ACTION}
        consentText={CONSENT_TEXT}
        alertsConsentText={ALERTS_CONSENT_TEXT}
        // The link the share button shares: this page on your own domain.
        shareUrl={pageUrl}
        // Your own Google Maps key and Map ID turn on the location map, the Street view pill and
        // the gallery's Street view tab.
        googleMapsKey={process.env.NEXT_PUBLIC_GOOGLE_MAPS_KEY || null}
        mapId={process.env.NEXT_PUBLIC_GOOGLE_MAP_ID || null}
        // Your own listings route (app/api/idx): the mortgage calculator under the property details
        // asks it for every figure it shows (GET /v1/mortgage/estimate). The page carries no key.
        apiBaseUrl="/api/idx"
        mortgage
      />
      {/* ListingDetail prints the listing's attribution and its board's disclaimer: no second copy here. */}
      <JsonLd docs={r.data.jsonLd} />
      {/* Follow Up Boss only: reports a registered visitor's view of this listing (crm-follow-up-boss). */}
      <ReportListingView listingId={r.data.id} url={pageUrl} />
    </main>
  );
}
```

### app/homes/[slug]/loading.tsx

The listing page while it loads.

```tsx
// What a listing page shows while its answer arrives: the page's own outline with a soft shimmer,
// which appears only when the wait passes 200 milliseconds. Next.js streams it first.
import { ListingDetailSkeleton } from "@ruuster/idx-recipes";
import { SEARCH_PATH } from "@/lib/site";

export default function ListingLoading() {
  return (
    <main>
      <ListingDetailSkeleton backHref={SEARCH_PATH} />
    </main>
  );
}
```

### app/homes/[slug]/not-found.tsx

The page for a listing that is no longer available.

```tsx
// The 404 body of a listing page: a link that is not a listing, or a listing the API does not know.
// A listing that left the market answers 410 with similar homes instead (components/gone.tsx).
import { ListingUnavailable } from "@ruuster/idx-recipes";
import { SEARCH_PATH } from "@/lib/site";

export const metadata = { title: "Home not found", robots: "noindex,follow" };

export default function ListingNotFound() {
  return (
    <main>
      <ListingUnavailable backHref={SEARCH_PATH} />
    </main>
  );
}
```

### middleware.ts

The real 301 and 410 for listing pages (its own client: middleware never imports lib/idx.ts).

```ts
// Real status codes for listing pages. A Next.js App Router page cannot answer 410 or a 301 by itself,
// so this middleware asks the API about the listing first:
//   the slug is outdated (the address was corrected) → 301 to the current URL;
//   the listing left the market → the page renders its "no longer available" body with HTTP 410 and noindex;
//   anything else → the page renders as usual (200, or 404 through notFound()).
// One GET /v1/listings/{id} per listing view (1 unit), remembered for 60 seconds per
// server instance, is the cheapest correct way; the page's own call is cached by Next.js for 5 minutes.
import { NextResponse, type NextRequest } from "next/server";
import { createClient, listingPath, parseListingSlug } from "@ruuster/idx";
import { DETAIL_HREF, SITE_ORIGIN } from "@/lib/site";

// Use "/homes/:path*" here: Next.js 14 turns a matcher that ends in a single named segment, such as
// "/homes/:slug", into one that matches "/homes" only.
export const config = { matcher: ["/homes/:path*"] };

export type ListingStatusAnswer = { status: number; slug: string | null; mlsNumber: string | null };
export type HomesDecision = { kind: "next" } | { kind: "redirect"; location: string } | { kind: "gone" };

/** What /homes/<pathSlug> answers, given the API's answer for its listing id (null when the API could not be reached). */
export function homesDecision(id: string, pathSlug: string, answer: ListingStatusAnswer | null): HomesDecision {
  if (!answer) return { kind: "next" };
  if (answer.status === 410) return { kind: "gone" };
  if (answer.status === 200 && answer.slug && answer.slug !== pathSlug) {
    return { kind: "redirect", location: listingPath({ id, slug: answer.slug, mlsNumber: answer.mlsNumber }, DETAIL_HREF) };
  }
  return { kind: "next" };
}

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY, baseUrl: process.env.IDX_BASE_URL || undefined, detailHref: DETAIL_HREF, siteOrigin: SITE_ORIGIN });
const remembered = new Map<string, { at: number; answer: ListingStatusAnswer }>();
const REMEMBER_MS = 60_000;

async function listingStatus(id: string): Promise<ListingStatusAnswer | null> {
  const hit = remembered.get(id);
  if (hit && Date.now() - hit.at < REMEMBER_MS) return hit.answer;
  const r = await idx.get(id);
  // 429, 503 and network errors: let the page decide (it keeps serving its last good render).
  if (r.status === 0 || r.status === 429 || r.status >= 500) return null;
  const answer: ListingStatusAnswer = r.ok ? { status: 200, slug: r.data.slug, mlsNumber: r.data.mlsNumber } : { status: r.status, slug: null, mlsNumber: null };
  if (remembered.size > 1000) remembered.clear();
  remembered.set(id, { at: Date.now(), answer });
  return answer;
}

export async function middleware(req: NextRequest) {
  const pathSlug = req.nextUrl.pathname.slice("/homes/".length);
  // Not a listing URL (for example /homes/sitemap/0.xml): nothing to decide.
  const p = pathSlug.includes("/") ? null : parseListingSlug(pathSlug);
  if (!p) return NextResponse.next();
  const d = homesDecision(p.id, pathSlug, await listingStatus(p.id));
  if (d.kind === "redirect") return NextResponse.redirect(new URL(d.location, req.url), 301);
  if (d.kind === "gone") return NextResponse.rewrite(req.nextUrl, { status: 410, headers: { "X-Robots-Tag": "noindex" } });
  return NextResponse.next();
}
```

### components/gone.tsx

The page a removed listing shows with HTTP 410, with similar homes.

```tsx
// The page a removed listing shows. middleware.ts sends it with HTTP 410 and noindex; this
// component gives the visitor somewhere to go: similar homes (the API answers them for 30 days after
// a listing leaves the market) and your area pages. Each similar item is { listing, why }: the grid
// takes the listings. Next.js adds its own <meta name="robots" content="noindex"> to any page answered
// with a status above 400, beside the page's own noindex,follow; both say noindex.
import Link from "next/link";
import { ListingGrid, MlsDisclaimers } from "@ruuster/idx-recipes";
import { AREAS } from "@/content/areas";
import { idx } from "@/lib/idx";

export async function Gone({ listingId }: { listingId: string }) {
  const similar = await idx.similar(listingId, { limit: 6 });
  const cards = similar.ok ? similar.data.listings.map((s) => s.listing) : [];
  return (
    <main>
      <h1>This home is no longer available</h1>
      <p>The listing has left the market. Here are similar homes for sale, and our area pages.</p>
      {cards.length > 0 ? (
        <section aria-labelledby="similar-homes">
          <h2 id="similar-homes">Similar homes</h2>
          <ListingGrid listings={cards} mls={similar.ok ? similar.meta.mls : []} ga4ListName="Similar homes" />
          {similar.ok ? <MlsDisclaimers mls={similar.meta.mls} asOf={similar.meta.freshness.asOf} /> : null}
        </section>
      ) : null}
      <nav aria-label="Area pages">
        <h2>Browse by area</h2>
        <ul>
          {AREAS.map((a) => (
            <li key={a.slug}>
              <Link href={`/neighborhoods/${a.slug}`}>Homes for sale in {a.name}</Link>
            </li>
          ))}
        </ul>
      </nav>
    </main>
  );
}
```

### lib/listing-ids.ts

Every listing URL for the sitemap.

```ts
// Every listing your key can show, for the listing sitemaps, in chunks of at most 50,000 URLs
// (the sitemap protocol's limit per file).
import "server-only";
import { idx, listingPath } from "@/lib/idx";
import { absoluteUrl, DETAIL_HREF } from "@/lib/site";

export const URLS_PER_SITEMAP = 50_000;

export type SitemapEntry = { url: string; lastModified: string };

/** Splits entries into sitemap files of at most `size` URLs. Pure. */
export function chunk<T>(rows: readonly T[], size: number = URLS_PER_SITEMAP): T[][] {
  const out: T[][] = [];
  for (let i = 0; i < rows.length; i += size) out.push(rows.slice(i, i + size));
  return out;
}

/**
 * Pages through GET /v1/listings/ids (1,000 per call, secret key) and answers one entry per
 * listing: your listing page URL and when the listing last changed. Throws on a failed page, so the
 * last good sitemap keeps being served.
 */
export async function listingSitemapEntries(): Promise<SitemapEntry[]> {
  const out: SitemapEntry[] = [];
  let cursor: string | undefined;
  do {
    const r = await idx.ids({ cursor, limit: 1000 });
    if (!r.ok) throw new Error(`Listings API ${r.status} ${r.error.code}`);
    for (const row of r.data.listings) out.push({ url: absoluteUrl(listingPath(row, DETAIL_HREF)), lastModified: row.updatedAt });
    cursor = r.data.nextCursor ?? undefined;
  } while (cursor);
  return out;
}
```

### app/homes/sitemap.ts

The listing sitemaps.

```ts
// /homes/sitemap/<n>.xml: every listing page, with lastmod, split into files of 50,000 URLs.
// A listing that left the market is gone from GET /v1/listings/ids, so it leaves the sitemap on the
// next rebuild (once an hour).
import type { MetadataRoute } from "next";
import { chunk, listingSitemapEntries } from "@/lib/listing-ids";

export const revalidate = 3600;

export async function generateSitemaps() {
  const files = chunk(await listingSitemapEntries());
  // Always publish file 0, even when it is empty, so the URL in robots.txt answers.
  return Array.from({ length: Math.max(files.length, 1) }, (_, id) => ({ id }));
}

export default async function sitemap({ id }: { id: number }): Promise<MetadataRoute.Sitemap> {
  const files = chunk(await listingSitemapEntries());
  return (files[id] ?? []).map((e) => ({ url: e.url, lastModified: e.lastModified, changeFrequency: "daily" }));
}
```

### app/sitemap.ts

The sitemap of your own pages.

```ts
// /sitemap.xml: your own pages (home, the area hub, every area page and its sold page, the list pages).
// The listing pages are in /homes/sitemap/<n>.xml (app/homes/sitemap.ts).
import type { MetadataRoute } from "next";
import { AREAS } from "@/content/areas";
import { showsSoldData } from "@/lib/area-query";
import { getMeta } from "@/lib/idx";
import { absoluteUrl } from "@/lib/site";

export const revalidate = 3600;

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const meta = await getMeta();
  const caps = meta.ok ? meta.data.capabilities : null;
  const pages: MetadataRoute.Sitemap = [
    { url: absoluteUrl("/"), changeFrequency: "daily" },
    { url: absoluteUrl("/neighborhoods"), changeFrequency: "weekly" },
    { url: absoluteUrl("/open-houses"), changeFrequency: "daily" },
    { url: absoluteUrl("/price-reduced"), changeFrequency: "daily" },
  ];
  // Your own listings page exists once Ruuster has your agents' and offices' MLS ids.
  if (caps?.ownListings === true) pages.push({ url: absoluteUrl("/our-listings"), changeFrequency: "daily" });
  // Add /new-construction here once that page shows listings on your boards.
  const sold = showsSoldData(caps);
  for (const a of AREAS) {
    pages.push({ url: absoluteUrl(`/neighborhoods/${a.slug}`), changeFrequency: "daily" });
    if (a.soldPage && sold) pages.push({ url: absoluteUrl(`/neighborhoods/${a.slug}/sold`), changeFrequency: "weekly" });
  }
  return pages;
}
```

### app/robots.ts

robots.txt.

```ts
// /robots.txt: search engines and AI answer engines are allowed everywhere except your API routes and
// account pages. Model-training crawlers are your choice (see the commented rule).
// Search pages with visitor filters stay crawlable on purpose: each one sends `noindex,follow`, and a
// crawler has to fetch the page to read that and follow its links to your listings.
import type { MetadataRoute } from "next";
import { chunk, listingSitemapEntries } from "@/lib/listing-ids";
import { absoluteUrl } from "@/lib/site";

export const revalidate = 3600;

export default async function robots(): Promise<MetadataRoute.Robots> {
  // One URL per listing sitemap file (app/homes/sitemap.ts splits at 50,000 listings).
  const files = Math.max(chunk(await listingSitemapEntries().catch(() => [])).length, 1);
  return {
    rules: [
      // Search and answer engines read your pages through this rule: Googlebot, Bingbot,
      // OAI-SearchBot and ChatGPT-User (ChatGPT search), Claude-SearchBot and Claude-User (Claude),
      // PerplexityBot and Perplexity-User. Keep them allowed so assistants can find and cite you.
      { userAgent: "*", allow: "/", disallow: ["/api/", "/account/"] },
      // Model-training crawlers only affect model training; blocking them keeps you in search and AI answers.
      // To block them, uncomment this rule:
      // { userAgent: ["GPTBot", "ClaudeBot", "Google-Extended", "Applebot-Extended"], disallow: "/" },
    ],
    sitemap: [absoluteUrl("/sitemap.xml"), ...Array.from({ length: files }, (_, n) => absoluteUrl(`/homes/sitemap/${n}.xml`))],
  };
}
```

### lib/revalidate.ts

Re-renders pages when a listing-change webhook arrives.

```ts
// The listing-change webhook: verify the signature, re-render the pages the change touches, answer fast.
// Deliveries arrive at least once and in any order, so the handler only re-renders: doing it twice is harmless.
import { verifyWebhook, type ListingEvent } from "@ruuster/idx";

/** The list pages any listing change can touch (re-rendered once per delivery). */
export const LIST_PAGES: readonly { path: string; type?: "page" | "layout" }[] = [
  { path: "/" },
  { path: "/neighborhoods/[area]", type: "page" },
  { path: "/neighborhoods/[area]/sold", type: "page" },
  { path: "/our-listings" },
  { path: "/open-houses" },
  { path: "/price-reduced" },
  { path: "/new-construction" },
  { path: "/agents/[agent]", type: "page" },
];

/** The listing page paths one event touches: its href's path, and /homes/<slug>. */
export function listingPathsOf(event: ListingEvent): string[] {
  const out = new Set<string>();
  const href = event.listing.href;
  if (href) {
    try {
      out.add(new URL(href, "http://localhost").pathname);
    } catch {
      // An href that is not a URL is skipped; the slug path below still covers the page.
    }
  }
  if (event.listing.slug) out.add(`/homes/${event.listing.slug}`);
  return [...out];
}

export type WebhookDeps = {
  /** RUUSTER_WEBHOOK_SECRET; two comma-separated values while you rotate it. */
  secret: string | undefined;
  revalidatePath: (path: string, type?: "page" | "layout") => void;
  now?: Date;
};

export async function handleRuusterWebhook(req: Request, deps: WebhookDeps): Promise<Response> {
  if (!deps.secret) return Response.json({ ok: false, error: "RUUSTER_WEBHOOK_SECRET is not set on this server." }, { status: 500 });
  const body = await req.text();
  const secrets = deps.secret.split(",").map((s) => s.trim()).filter(Boolean);
  const v = await verifyWebhook({ body, headers: req.headers, secret: secrets, now: deps.now });
  if (!v.ok) return Response.json({ ok: false, error: v.reason }, { status: 401 });
  const paths = new Set<string>();
  for (const e of v.events) for (const p of listingPathsOf(e)) paths.add(p);
  for (const p of paths) deps.revalidatePath(p);
  for (const l of LIST_PAGES) deps.revalidatePath(l.path, l.type);
  return Response.json({ ok: true, events: v.events.length, deliveryId: v.deliveryId });
}
```

### app/api/ruuster-webhook/route.ts

The webhook route.

```ts
// POST /api/ruuster-webhook: Ruuster calls it when a listing in your boards is created, changes price
// or status, or is removed. Add this URL under Webhooks in Settings > Ruuster Listings API, and
// put the signing secret in RUUSTER_WEBHOOK_SECRET.
import { revalidatePath } from "next/cache";
import { handleRuusterWebhook } from "@/lib/revalidate";

export const dynamic = "force-dynamic";

export function POST(req: Request) {
  return handleRuusterWebhook(req, { secret: process.env.RUUSTER_WEBHOOK_SECRET, revalidatePath });
}
```

### lib/crm.ts

The lead handler every CRM route shares: origin check, validation, messages and the listing-view count.

```ts
// Your site's lead routes: the forms post here, and this file sends each lead to your own CRM.
// The route files under app/api/leads and app/api/activity are one line each and call these handlers.
// Your CRM keys stay on your server. The browser only ever talks to your own site.
import { createHmac, timingSafeEqual } from "node:crypto";
import { assertSendable, fub, LeadRejected, sierra, suresend, type CrmSendResult } from "@ruuster/idx/crm";
import type { CampaignIds, CampaignTouch, LeadAgent, LeadAttribution, LeadSubmission, ListingCard, ListingDetail } from "@ruuster/idx";

export type CrmName = "fub" | "sierra" | "suresend";

export type CrmDeps = {
  /** process.env in the routes; a plain object in tests. */
  env: Readonly<Record<string, string | undefined>>;
  /** The listing the form was about, from the Listings API (null when it is gone or the call failed). */
  getListing: (listingId: string) => Promise<ListingCard | ListingDetail | null>;
  /** fetch for the CRM call. Tests pass a fake. */
  fetch?: typeof fetch;
  now?: () => Date;
};

// #region messages
/** What the form shows. Every answer is a full sentence. */
export const MESSAGES = {
  sent: "Thanks. We got your request and will be in touch soon.",
  wrongOrigin: "Please send this form from our website.",
  unreadable: "We couldn't read this form. Please refresh the page and try again.",
  notSetUp: "This form isn't set up yet. Please call or email us instead.",
  failed: "We couldn't send your request just now. Please try again in a minute.",
  busy: (sec: number | null) => `We're getting a lot of requests right now. Please try again in ${sec && sec > 0 ? `${sec} seconds` : "a minute"}.`,
  sierraNeedsEmail: "Please enter your email address.",
} as const;
// #endregion messages

const json = (status: number, body: unknown, headers: Record<string, string> = {}): Response =>
  new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...headers } });

const fail = (status: number, error: string, headers?: Record<string, string>) => json(status, { ok: false, error }, headers);

// #region origin
/** Only your own pages may post leads: the browser's Origin header must be exactly SITE_ORIGIN. */
export function sameOrigin(request: Request, siteOrigin: string | undefined): boolean {
  if (!siteOrigin) return false;
  const origin = request.headers.get("origin");
  if (!origin) return false;
  try {
    return new URL(origin).origin === new URL(siteOrigin).origin;
  } catch {
    return false;
  }
}

/** A listing URL from the form counts only when it is a page on your own site. */
export function ownUrl(url: string | null | undefined, siteOrigin: string | undefined): string | null {
  if (!url || !siteOrigin) return null;
  try {
    const u = new URL(url);
    return u.origin === new URL(siteOrigin).origin ? u.toString() : null;
  } catch {
    return null;
  }
}
// #endregion origin

const str = (v: unknown, max = 500): string => (typeof v === "string" ? v.trim().slice(0, max) : "");
const strOrNull = (v: unknown, max = 500): string | null => str(v, max) || null;

// #region parse
/** The JSON the recipe forms post (LeadSubmission), checked field by field. Null when it is not one. */
export function parseLead(body: unknown): LeadSubmission | null {
  if (!body || typeof body !== "object") return null;
  const b = body as Record<string, unknown>;
  if (b.kind !== "registration" && b.kind !== "tour" && b.kind !== "contact") return null;
  const consent = (b.consent ?? {}) as Record<string, unknown>;
  const page = (b.page ?? {}) as Record<string, unknown>;
  const tour = b.tour && typeof b.tour === "object" ? (b.tour as Record<string, unknown>) : null;
  const listing = b.listing && typeof b.listing === "object" ? (b.listing as Record<string, unknown>) : null;
  const listingId = listing ? str(listing.id, 100) : "";
  return {
    kind: b.kind,
    firstName: str(b.firstName, 100),
    lastName: str(b.lastName, 100),
    email: str(b.email, 200),
    phone: strOrNull(b.phone, 40),
    message: strOrNull(b.message, 2000),
    tour: tour ? { date: strOrNull(tour.date, 40), time: strOrNull(tour.time, 40) } : null,
    listing: listingId ? { id: listingId, mlsNumber: strOrNull(listing?.mlsNumber, 40), url: strOrNull(listing?.url, 1000) } : null,
    consent: { contact: consent.contact === true, alerts: consent.alerts === true, text: str(consent.text, 1000) },
    page: { url: str(page.url, 1000), referrer: strOrNull(page.referrer, 1000) },
    attribution: parseAttribution(b.attribution),
    // The agent and lead type a form names (for example a form on one agent's own page). Set or drop
    // them here if you'd rather decide on your server; left out, your CRM's lead routing assigns the lead.
    agent: parseAgent(b.agent),
    leadType: b.leadType === "buyer" || b.leadType === "seller" || b.leadType === "both" ? b.leadType : null,
    website: str(b.website, 200),
  };
}

function campaignIds(a: Record<string, unknown>): CampaignIds {
  return {
    utmSource: strOrNull(a.utmSource, 200),
    utmMedium: strOrNull(a.utmMedium, 200),
    utmCampaign: strOrNull(a.utmCampaign, 200),
    utmTerm: strOrNull(a.utmTerm, 200),
    utmContent: strOrNull(a.utmContent, 200),
    gclid: strOrNull(a.gclid, 200),
    fbclid: strOrNull(a.fbclid, 200),
    msclkid: strOrNull(a.msclkid, 200),
  };
}

function touch(raw: unknown): CampaignTouch | null {
  if (!raw || typeof raw !== "object") return null;
  const t = raw as Record<string, unknown>;
  return { ...campaignIds(t), landingPage: strOrNull(t.landingPage, 1000), referrer: strOrNull(t.referrer, 1000), at: strOrNull(t.at, 40) };
}

/** Where the visitor came from: this visit's campaign ids, landing page and referrer, the form page, and the first and last touch. */
export function parseAttribution(raw: unknown): LeadAttribution {
  const a = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
  return {
    ...campaignIds(a),
    referrer: strOrNull(a.referrer, 1000),
    landingPage: strOrNull(a.landingPage, 1000),
    formPage: strOrNull(a.formPage, 1000),
    firstTouch: touch(a.firstTouch),
    lastTouch: touch(a.lastTouch),
  };
}

function parseAgent(raw: unknown): LeadAgent | null {
  if (!raw || typeof raw !== "object") return null;
  const a = raw as Record<string, unknown>;
  const agent = { id: strOrNull(typeof a.id === "number" ? String(a.id) : a.id, 100), email: strOrNull(a.email, 200), name: strOrNull(a.name, 200) };
  return agent.id || agent.email || agent.name ? agent : null;
}
// #endregion parse

// #region personCookie
/**
 * The cookie that remembers a registered visitor's Follow Up Boss person id, for Viewed Property events.
 * Its value is `<id>.<signature>`: an HMAC-SHA256 of the id made with FUB_COOKIE_SECRET, a long random
 * string only your server knows. The listing-view route trusts an id only when its signature checks
 * out, so nobody can add views to another person by editing the cookie. Without FUB_COOKIE_SECRET the
 * registration sets no cookie and listing views send nothing.
 */
export const FUB_PERSON_COOKIE = "fub_person";

function signId(id: string, secret: string): string {
  return createHmac("sha256", secret).update(`fub_person:${id}`).digest("hex");
}

/** The cookie value for a person id: `<id>.<signature>`. */
export function signPersonId(id: string, secret: string): string {
  return `${id}.${signId(id, secret)}`;
}

/** The person id in a signed cookie value, or null when it is missing, unsigned or edited. */
export function verifyPersonId(value: string | null, secret: string | undefined): string | null {
  if (!value || !secret) return null;
  const dot = value.indexOf(".");
  if (dot <= 0) return null;
  const id = value.slice(0, dot);
  const sig = value.slice(dot + 1);
  if (!/^\d+$/.test(id) || !/^[0-9a-f]{64}$/.test(sig)) return null;
  const expected = Buffer.from(signId(id, secret), "hex");
  return timingSafeEqual(Buffer.from(sig, "hex"), expected) ? id : null;
}

function personCookie(id: string, siteOrigin: string, secret: string): string {
  const secure = siteOrigin.startsWith("https://") ? "; Secure" : "";
  return `${FUB_PERSON_COOKIE}=${signPersonId(id, secret)}; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`;
}
// #endregion personCookie

function answer(result: CrmSendResult, extraHeaders: Record<string, string> = {}): Response {
  if (result.ok) return json(200, { ok: true, message: MESSAGES.sent }, extraHeaders);
  if (result.status === 429 || result.retryAfterSec != null) {
    const sec = result.retryAfterSec;
    return fail(429, MESSAGES.busy(sec), sec != null ? { "Retry-After": String(sec) } : {});
  }
  // The CRM's own error stays in your server log. It never contains your key.
  console.error(`CRM send failed (${result.status}): ${result.error}`);
  return fail(502, MESSAGES.failed);
}

// #region handleLead
/**
 * POST /api/leads/{fub|sierra|suresend}: check the origin and the form, look up the listing, build
 * the CRM payload and send it. Answers { ok: true } or { ok: false, error } with a sentence the form
 * shows: 400 unreadable, 403 another site, 422 missing contact or consent, 429 the CRM asked us to
 * wait, 500 not set up, 502 the CRM refused.
 */
export async function handleLead(request: Request, crm: CrmName, deps: CrmDeps): Promise<Response> {
  const env = deps.env;
  if (!sameOrigin(request, env.SITE_ORIGIN)) return fail(403, MESSAGES.wrongOrigin);
  let lead: LeadSubmission | null = null;
  try {
    lead = parseLead(await request.json());
  } catch {
    lead = null;
  }
  if (!lead) return fail(400, MESSAGES.unreadable);
  try {
    assertSendable(lead);
  } catch (err) {
    if (err instanceof LeadRejected) {
      // A filled honeypot is a bot: answer as if it worked and send nothing.
      if (err.reason === "honeypot") return json(200, { ok: true, message: MESSAGES.sent });
      return fail(422, err.message);
    }
    throw err;
  }
  if (crm === "sierra" && !lead.email) return fail(422, MESSAGES.sierraNeedsEmail);

  const source = env.SITE_NAME ?? "";
  const listing = lead.listing ? await deps.getListing(lead.listing.id).catch(() => null) : null;
  const listingUrl = ownUrl(lead.listing?.url, env.SITE_ORIGIN);
  const init = { fetch: deps.fetch };

  try {
    if (crm === "fub") {
      const creds = { apiKey: env.FUB_API_KEY ?? "", system: env.FUB_SYSTEM ?? "", systemKey: env.FUB_SYSTEM_KEY ?? "" };
      const event = fub.eventFromLead(lead, { source, listing, listingUrl });
      const result = await fub.sendEvent(event, creds, init);
      // Remember who registered, so their listing views can follow (app/api/activity/fub).
      const secret = env.FUB_COOKIE_SECRET;
      const cookie: Record<string, string> =
        result.ok && result.id && secret ? { "Set-Cookie": personCookie(result.id, env.SITE_ORIGIN ?? "", secret) } : {};
      return answer(result, cookie);
    }
    const now = (deps.now ?? (() => new Date()))();
    if (crm === "sierra") {
      const creds = { apiKey: env.SIERRA_API_KEY ?? "" };
      const body = sierra.leadFromSubmission(lead, { source, listing, listingUrl });
      const result = await sierra.createLead(body, creds, init);
      // Then the visit that brought the lead. A failed visit doesn't undo the lead: log it and answer the form.
      const visit = result.ok && result.id ? sierra.siteVisitFromSubmission(lead, now) : null;
      if (result.ok && result.id && visit) {
        const v = await sierra.addSiteVisit(result.id, visit, creds, init);
        if (!v.ok) console.error(`Sierra site visit not added (${v.status}): ${v.error}`);
      }
      return answer(result);
    }
    // Put one of your Sure Send person stage names here (for example the stage new website leads start in), or leave it null.
    const SURESEND_STAGE: string | null = null;
    const creds = { apiKey: env.SURESEND_API_KEY ?? "" };
    const person = suresend.personFromSubmission(lead, { source, listing, listingUrl, stage: SURESEND_STAGE });
    const result = await suresend.createPerson(person, creds, init);
    // Then the request as a note on the person. A failed note doesn't undo the person: log it and answer the form.
    if (result.ok && result.id) {
      const n = await suresend.createNote(suresend.noteFromSubmission(lead, result.id, { source, listing, listingUrl }), creds, init);
      if (!n.ok) console.error(`Sure Send note not added (${n.status}): ${n.error}`);
    }
    return answer(result);
  } catch (err) {
    // A missing key or SITE_NAME throws before any call. Say so in your log, and give the visitor a plain answer.
    console.error(`CRM route not set up: ${err instanceof Error ? err.message : String(err)}`);
    return fail(500, MESSAGES.notSetUp);
  }
}
// #endregion handleLead

// An in-memory count per server process, by UTC day.
// #region dedupe
/**
 * One Viewed Property per person, listing and day. This keeps the count in memory, which is right
 * for one server process (next start, a single container). On serverless hosts each instance keeps
 * its own count, so a person can get a second event for the same listing on the same day; move this
 * to your own store (Redis, your database) if that matters to you.
 */
export class ViewDedupe {
  private seen = new Map<string, number>();
  constructor(private readonly max = 50_000) {}
  /** True the first time this person, listing and UTC day is seen; false after that. */
  firstToday(personId: string, listingId: string, now: Date): boolean {
    const day = now.toISOString().slice(0, 10);
    const key = `${personId}|${listingId}|${day}`;
    if (this.seen.has(key)) return false;
    if (this.seen.size >= this.max) this.prune(day);
    this.seen.set(key, now.getTime());
    return true;
  }
  /** Undo firstToday after a failed send, so the next view tries again. */
  forget(personId: string, listingId: string, now: Date): void {
    this.seen.delete(`${personId}|${listingId}|${now.toISOString().slice(0, 10)}`);
  }
  private prune(today: string): void {
    for (const k of Array.from(this.seen.keys())) if (!k.endsWith(`|${today}`)) this.seen.delete(k);
    if (this.seen.size >= this.max) this.seen.clear();
  }
}

export const viewedToday = new ViewDedupe();
// #endregion dedupe

function cookieValue(request: Request, name: string): string | null {
  const raw = request.headers.get("cookie") ?? "";
  for (const part of raw.split(";")) {
    const [k, ...v] = part.trim().split("=");
    if (k === name) {
      try {
        return decodeURIComponent(v.join("="));
      } catch {
        return null;
      }
    }
  }
  return null;
}

// #region handleFubActivity
/**
 * POST /api/activity/fub with { listingId, url }: sends Follow Up Boss "Viewed Property" for a
 * visitor who registered on this site (the signed fub_person cookie the registration set), at most
 * once per person, listing and day. Anonymous visitors, and a cookie whose signature doesn't check
 * out, send nothing: { ok: true, sent: false }.
 */
export async function handleFubActivity(request: Request, deps: CrmDeps, dedupe: ViewDedupe = viewedToday): Promise<Response> {
  const env = deps.env;
  if (!sameOrigin(request, env.SITE_ORIGIN)) return fail(403, MESSAGES.wrongOrigin);
  let body: Record<string, unknown> | null = null;
  try {
    const parsed: unknown = await request.json();
    body = parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : null;
  } catch {
    body = null;
  }
  const listingId = body ? str(body.listingId, 100) : "";
  if (!listingId) return fail(400, MESSAGES.unreadable);
  const personId = verifyPersonId(cookieValue(request, FUB_PERSON_COOKIE), env.FUB_COOKIE_SECRET);
  if (!personId) return json(200, { ok: true, sent: false });
  const now = (deps.now ?? (() => new Date()))();
  if (!dedupe.firstToday(personId, listingId, now)) return json(200, { ok: true, sent: false });

  const listing = await deps.getListing(listingId).catch(() => null);
  if (!listing) {
    dedupe.forget(personId, listingId, now);
    return json(200, { ok: true, sent: false });
  }
  const listingUrl = ownUrl(body ? str(body.url, 1000) : null, env.SITE_ORIGIN) ?? "";
  try {
    const event = fub.viewedPropertyEvent({ id: personId }, listing, { source: env.SITE_NAME ?? "", listingUrl });
    const creds = { apiKey: env.FUB_API_KEY ?? "", system: env.FUB_SYSTEM ?? "", systemKey: env.FUB_SYSTEM_KEY ?? "" };
    const result = await fub.sendEvent(event, creds, { fetch: deps.fetch });
    if (result.ok) return json(200, { ok: true, sent: true });
    dedupe.forget(personId, listingId, now);
    return answer(result);
  } catch (err) {
    dedupe.forget(personId, listingId, now);
    console.error(`CRM route not set up: ${err instanceof Error ? err.message : String(err)}`);
    return fail(500, MESSAGES.notSetUp);
  }
}
// #endregion handleFubActivity
```

### app/api/leads/fub/route.ts

Leads to Follow Up Boss.

```ts
// POST /api/leads/fub: the registration, tour and contact forms post here. lib/crm.ts does the work.
import { idx } from "@/lib/idx";
import { handleLead } from "@/lib/crm";

export const runtime = "nodejs";

export async function POST(request: Request): Promise<Response> {
  return handleLead(request, "fub", {
    env: process.env,
    getListing: async (listingId) => {
      const r = await idx.get(listingId);
      return r.ok ? r.data : null;
    },
  });
}
```

### app/api/leads/sierra/route.ts

Leads to Sierra Interactive.

```ts
// POST /api/leads/sierra: the registration, tour and contact forms post here. lib/crm.ts does the work.
import { idx } from "@/lib/idx";
import { handleLead } from "@/lib/crm";

export const runtime = "nodejs";

export async function POST(request: Request): Promise<Response> {
  return handleLead(request, "sierra", {
    env: process.env,
    getListing: async (listingId) => {
      const r = await idx.get(listingId);
      return r.ok ? r.data : null;
    },
  });
}
```

### app/api/leads/suresend/route.ts

Leads to Sure Send.

```ts
// POST /api/leads/suresend: the registration, tour and contact forms post here. lib/crm.ts does the work.
import { idx } from "@/lib/idx";
import { handleLead } from "@/lib/crm";

export const runtime = "nodejs";

export async function POST(request: Request): Promise<Response> {
  return handleLead(request, "suresend", {
    env: process.env,
    getListing: async (listingId) => {
      const r = await idx.get(listingId);
      return r.ok ? r.data : null;
    },
  });
}
```

### app/api/activity/fub/route.ts

A registered visitor's listing views to Follow Up Boss.

```ts
// POST /api/activity/fub: your listing page calls this when a registered visitor opens a listing.
// lib/crm.ts sends one Follow Up Boss "Viewed Property" per person, listing and day.
import { idx } from "@/lib/idx";
import { handleFubActivity } from "@/lib/crm";

export const runtime = "nodejs";

export async function POST(request: Request): Promise<Response> {
  return handleFubActivity(request, {
    env: process.env,
    getListing: async (listingId) => {
      const r = await idx.get(listingId);
      return r.ok ? r.data : null;
    },
  });
}
```

### app/api/activity/fub/report-view.tsx

The listing page's part of the listing-view report.

```tsx
"use client";
// Put <ReportListingView listingId={r.data.id} url={pageUrl} /> on your listing page.
// It tells your own server once per page view; app/api/activity/fub/route.ts decides whether to send
// Follow Up Boss a "Viewed Property" (only for a visitor who registered, once per listing and day).
import { useEffect } from "react";

export function ReportListingView({ listingId, url }: { listingId: string; url: string }) {
  useEffect(() => {
    void fetch("/api/activity/fub", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ listingId, url }),
      keepalive: true,
    }).catch(() => undefined);
  }, [listingId, url]);
  return null;
}
```

## Appendix: response schemas

The `data` of each endpoint's successful answer. Fields marked nullable can be null. Fields not listed
never appear.

### GET /v1/status

```ts
type Data = {
  status: "ok";
  version: string;
  paused: boolean;
};
```

### GET /v1/meta

```ts
type Data = {
  brokerage: {
    id: string;
    name: string | null;
    lang: "en";
    isNewDesignEnabled: boolean;
  };
  site: {
    label: string;
    keyKind: "pk" | "sk";
  };
  capabilities: {
    sold: {
      mlsId: string;
      allowed: boolean;
      windowDays: number | null;
    }[];
    renderMode: "ssr" | "static" | "none";
    surfaces: string[];
    multiInstance: boolean;
    urlPaging: boolean;
    ownListings: boolean;
    agentFilter: boolean;
    maps: boolean;
    suggestSources: ("googleAutocomplete" | "school" | "neighborhood" | "county" | "subdivision" | "area" | "community" | "crm-system" | "subdivisionAndCity" | "addressByOpenSearch" | "listingId" | "countyOrParish" | "customPolygon" | "library")[];
  };
  theme: {
    common?: {
      backgroundAttachment?: string;
      backgroundImage?: string;
      backgroundPosition?: string;
      backgroundRepeat?: string;
      backgroundSize?: string;
      colorAccent?: string;
      colorAccentHover?: string;
      colorAccentRgb?: string;
      colorAccentText?: string;
      colorBackground?: string;
      colorBorder?: string;
      colorChrome?: string;
      colorChromeText?: string;
      colorSubAccent?: string;
      colorText?: string;
      colorTextSecondary?: string;
      fontMain?: string;
      fontSecondary?: string;
      mobileBackgroundAttachment?: string;
      mobileBackgroundImage?: string;
      mobileBackgroundPosition?: string;
      mobileBackgroundRepeat?: string;
      mobileBackgroundSize?: string;
      mobileColorBackground?: string;
    };
    buttons?: {
      colorButton?: string;
      colorButtonDarken1?: string;
      colorButtonLighten1?: string;
      colorButtonText?: string;
      savedSearchColorButton?: string;
      savedSearchColorButtonShadow?: string;
      savedSearchColorButtonText?: string;
    };
    links?: {
      colorLink?: string;
      colorLinkDarken1?: string;
    };
    tokens?: {
      "font.family.sans"?: string;
      "font.family.serif"?: string;
      "interactive.accent"?: string;
      "interactive.accentHover"?: string;
      "interactive.accentSubtle"?: string;
      "interactive.primary"?: string;
      "link.default"?: string;
      "stroke.light"?: string;
      "surface.chrome"?: string;
      "surface.page"?: string;
      "text.onChrome"?: string;
      "text.onPrimary"?: string;
      "text.primary"?: string;
      "text.secondary"?: string;
    };
  } | null;
  themeVars: {
    "--rw-colors-accent": string;
    "--rw-colors-accent-light": string;
    "--rw-colors-black": string;
    "--rw-colors-blue": string;
    "--rw-colors-cream-accent": string;
    "--rw-colors-cream-background": string;
    "--rw-colors-cream-border": string;
    "--rw-colors-danger": string;
    "--rw-colors-focus-ring": string;
    "--rw-colors-green": string;
    "--rw-colors-green2": string;
    "--rw-colors-grey": string;
    "--rw-colors-grey2": string;
    "--rw-colors-grey3": string;
    "--rw-colors-hovers-accent": string;
    "--rw-colors-hovers-primary": string;
    "--rw-colors-icon-grey": string;
    "--rw-colors-icon-on-card": string;
    "--rw-colors-interactive-accent": string;
    "--rw-colors-interactive-accent-hover": string;
    "--rw-colors-interactive-accent-subtle": string;
    "--rw-colors-interactive-grey-hover": string;
    "--rw-colors-interactive-primary": string;
    "--rw-colors-interactive-primary-hover": string;
    "--rw-colors-link-default": string;
    "--rw-colors-link-hover": string;
    "--rw-colors-overlays-card": string;
    "--rw-colors-overlays-card-hover": string;
    "--rw-colors-overlays-light-card": string;
    "--rw-colors-overlays-light-card-hover": string;
    "--rw-colors-overlays-scrim": string;
    "--rw-colors-primary": string;
    "--rw-colors-secondary": string;
    "--rw-colors-status-danger": string;
    "--rw-colors-status-info": string;
    "--rw-colors-status-pending": string;
    "--rw-colors-status-success": string;
    "--rw-colors-stroke-card-line": string;
    "--rw-colors-stroke-cream": string;
    "--rw-colors-stroke-light": string;
    "--rw-colors-stroke-medium": string;
    "--rw-colors-surface-base": string;
    "--rw-colors-surface-black": string;
    "--rw-colors-surface-card": string;
    "--rw-colors-surface-chrome": string;
    "--rw-colors-surface-cream": string;
    "--rw-colors-surface-gold": string;
    "--rw-colors-surface-gold-subtle": string;
    "--rw-colors-surface-grey": string;
    "--rw-colors-surface-page": string;
    "--rw-colors-tertiary": string;
    "--rw-colors-text-inverse": string;
    "--rw-colors-text-on-chrome": string;
    "--rw-colors-text-on-cream": string;
    "--rw-colors-text-on-gold": string;
    "--rw-colors-text-on-primary": string;
    "--rw-colors-text-primary": string;
    "--rw-colors-text-secondary": string;
    "--rw-colors-text-tertiary": string;
    "--rw-colors-type-ai-accent": string;
    "--rw-colors-type-ai-tile": string;
    "--rw-colors-type-custom-accent": string;
    "--rw-colors-type-custom-tile": string;
    "--rw-colors-type-template-accent": string;
    "--rw-colors-white": string;
    "--rw-fonts-inter": string;
    "--rw-fonts-marcellus": string;
    "--rw-fonts-sans": string;
    "--rw-fonts-serif": string;
  };
  compliance: {
    mlsId: string;
    mlsName: string;
    displayType: "IDX" | "VOW";
    disclaimer: {
      text: string;
      html: string | null;
    } | null;
    logo: {
      url: string;
      width: number;
      height: number;
      alt: string;
    } | null;
    attributionTemplate: string | null;
    required: {
      element: "listing_office" | "listing_agent" | "agent_contact" | "mls_logo" | "disclaimer" | "as_of" | "courtesy_line" | "dmca_notice" | "source_line";
      placement: "card" | "detail" | "page" | "map";
    }[];
    notices: {
      kind: "dmca" | "source" | "copyright" | "other";
      text: string;
      html: string | null;
    }[];
    draft: boolean;
  }[];
  mls: {
    id: string;
    name: string;
    searchName: string | null;
    states: string[];
    displayType: "IDX" | "VOW";
  }[];
  supportedStates: string[];
  widget: {
    version: string;
    loaderUrl: string;
  };
  maps: {
    apiKey: string;
    mapId: string | null;
  } | null;
  ctas: {
    label: string;
    hrefTemplate: string | null;
    event: string | null;
  }[];
  detailHrefTemplate: string | null;
  organization: {
    jsonLd: {
      "@context": "https://schema.org";
      "@type": "RealEstateAgent";
      name: string;
      url?: string;
      logo?: string;
      image?: string;
      telephone?: string;
      areaServed?: {
        "@type": "State";
        name: string;
      }[];
    } | null;
    jsonLdHtml: string;
  };
};
```

### GET /v1/filters

```ts
type Data = {
  key: string;
  label: string;
  type: string | null;
  group: "based" | "advanced";
  mlsIds: string[];
  operators: ("and" | "or" | "not" | "zbyes" | "zbno")[];
}[];
```

### GET /v1/filters/options

```ts
type Data = {
  key: string;
  options: {
    value: string;
    label: string;
    count: number;
  }[];
  truncated: boolean;
};
```

### GET /v1/listings

```ts
type Data = {
  listings: {
    id: string;
    slug: string;
    href: string | null;
    mls: {
      id: string;
      name: string;
    };
    mlsNumber: string | null;
    status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
    statusLabel: string;
    price: number | null;
    closePrice: number | null;
    listPrice: number | null;
    closeDate: string | null;
    beds: number | null;
    baths: number | null;
    sqft: number | null;
    lotAcres: number | null;
    yearBuilt: number | null;
    type: string | null;
    subtype: string | null;
    address: {
      display: string;
      street: string | null;
      unit: string | null;
      city: string | null;
      state: string;
      postalCode: string | null;
      hidden: boolean;
    };
    geo: {
      lat: number;
      lng: number;
      precision: "exact" | "approximate";
    } | null;
    photos: {
      url: string;
      width: number | null;
      height: number | null;
      order: number;
      alt: string;
    }[];
    photoCount: number;
    openHouses: {
      start: string;
      end: string;
      timeZone: string | null;
      kind: "in_person" | "virtual";
      remarks: string | null;
    }[];
    badges: {
      kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
      since: string | null;
    }[];
    listedAt: string | null;
    updatedAt: string;
    modifiedAt?: string | null;
    attribution: {
      listOfficeName: string | null;
      listAgentName: string | null;
      contact: {
        agentEmail?: string;
        agentPhone?: string;
        officeEmail?: string;
        officePhone?: string;
      };
      line: string | null;
      courtesy: string | null;
    };
  } | {
    id: string;
    slug: string;
    href: string | null;
    mls: {
      id: string;
      name: string;
    };
    mlsNumber: string | null;
    status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
    statusLabel: string;
    price: number | null;
    closePrice: number | null;
    listPrice: number | null;
    closeDate: string | null;
    beds: number | null;
    baths: number | null;
    sqft: number | null;
    lotAcres: number | null;
    yearBuilt: number | null;
    type: string | null;
    subtype: string | null;
    address: {
      display: string;
      street: string | null;
      unit: string | null;
      city: string | null;
      state: string;
      postalCode: string | null;
      hidden: boolean;
    };
    geo: {
      lat: number;
      lng: number;
      precision: "exact" | "approximate";
    } | null;
    photos: {
      url: string;
      width: number | null;
      height: number | null;
      order: number;
      alt: string;
    }[];
    photoCount: number;
    openHouses: {
      start: string;
      end: string;
      timeZone: string | null;
      kind: "in_person" | "virtual";
      remarks: string | null;
    }[];
    badges: {
      kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
      since: string | null;
    }[];
    listedAt: string | null;
    updatedAt: string;
    modifiedAt?: string | null;
    attribution: {
      listOfficeName: string | null;
      listAgentName: string | null;
      contact: {
        agentEmail?: string;
        agentPhone?: string;
        officeEmail?: string;
        officePhone?: string;
      };
      line: string | null;
      courtesy: string | null;
    };
    description: string | null;
    details: {
      categoryId: string;
      label: string;
      items: {
        key: string;
        label: string;
        value: string | number | boolean | string[];
      }[];
    }[];
    virtualTourUrl: string | null;
  } | {
    id: string;
    slug: string;
    href: string | null;
    mls: {
      id: string;
      name: string;
    };
    status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
    price: number | null;
    geo: {
      lat: number;
      lng: number;
      precision: "exact" | "approximate";
    };
    address: string;
    badges: {
      kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
      since: string | null;
    }[];
  }[];
  total: number;
  page: number;
  limit: number;
  nextCursor: string | null;
  viewport: {
    south: number;
    west: number;
    north: number;
    east: number;
  } | null;
  viewportSource: "boundary" | "library" | "drawn" | "results" | "shape" | null;
  boundary: {
    id: string;
    href: string;
  } | null;
  head: {
    title: string;
    description: string;
    canonical: string | null;
    robots: string;
    og: {
      title: string;
      description: string;
      url: string | null;
      image: string | null;
      type: "website";
    };
    twitter: {
      card: "summary_large_image" | "summary";
      title: string;
      description: string;
      image: string | null;
    };
  };
  jsonLd: {
    "@context": "https://schema.org";
    "@type": "ItemList";
    name: string;
    numberOfItems: number;
    itemListElement: {
      "@type": "ListItem";
      position: number;
      url: string;
    }[];
  } | {
    "@context": "https://schema.org";
    "@type": "BreadcrumbList";
    itemListElement: {
      "@type": "ListItem";
      position: number;
      name: string;
      item: string;
    }[];
  }[];
  jsonLdHtml: string;
  location: {
    label: string | null;
  };
  pages: number;
};
```

### GET /v1/listings/ids

```ts
type Data = {
  listings: {
    id: string;
    slug: string;
    updatedAt: string;
    mlsNumber: string | null;
    mls: string;
    modifiedAt: string | null;
  }[];
  nextCursor: string | null;
  asOf: string;
};
```

### GET /v1/listings/{listingId}

```ts
type Data = {
  id: string;
  slug: string;
  href: string | null;
  mls: {
    id: string;
    name: string;
  };
  mlsNumber: string | null;
  status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
  statusLabel: string;
  price: number | null;
  closePrice: number | null;
  listPrice: number | null;
  closeDate: string | null;
  beds: number | null;
  baths: number | null;
  sqft: number | null;
  lotAcres: number | null;
  yearBuilt: number | null;
  type: string | null;
  subtype: string | null;
  address: {
    display: string;
    street: string | null;
    unit: string | null;
    city: string | null;
    state: string;
    postalCode: string | null;
    hidden: boolean;
  };
  geo: {
    lat: number;
    lng: number;
    precision: "exact" | "approximate";
  } | null;
  photos: {
    url: string;
    width: number | null;
    height: number | null;
    order: number;
    alt: string;
    id?: string;
    sizes?: {
      width: number;
      url: string;
    }[];
    caption?: string | null;
    room?: string | null;
  }[];
  photoCount: number;
  openHouses: {
    start: string;
    end: string;
    timeZone: string | null;
    kind: "in_person" | "virtual";
    remarks: string | null;
  }[];
  badges: {
    kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
    since: string | null;
  }[];
  listedAt: string | null;
  updatedAt: string;
  modifiedAt?: string | null;
  attribution: {
    listOfficeName: string | null;
    listAgentName: string | null;
    contact: {
      agentEmail?: string;
      agentPhone?: string;
      officeEmail?: string;
      officePhone?: string;
    };
    line: string | null;
    courtesy: string | null;
  };
  description: string | null;
  details: {
    categoryId: string;
    label: string;
    items: {
      key: string;
      label: string;
      value: string | number | boolean | string[];
    }[];
  }[];
  virtualTourUrl: string | null;
  custom?: {
    listing: {
      key: string;
      value: string | number | boolean;
    }[];
    photos: {
      photoId: string;
      key: string;
      value: string | number | boolean;
    }[];
  };
  compliance: {
    mlsId: string;
    attributionLine: string | null;
    courtesyLine: string | null;
    required: {
      element: "listing_office" | "listing_agent" | "agent_contact" | "mls_logo" | "disclaimer" | "as_of" | "courtesy_line" | "dmca_notice" | "source_line";
      placement: "card" | "detail" | "page" | "map";
    }[];
    suppressedFields: string[];
    asOf: string;
  };
  head: {
    title: string;
    description: string;
    canonical: string | null;
    robots: string;
    og: {
      title: string;
      description: string;
      url: string | null;
      image: string | null;
      type: "website";
    };
    twitter: {
      card: "summary_large_image" | "summary";
      title: string;
      description: string;
      image: string | null;
    };
  };
  jsonLd: {
    "@context": "https://schema.org";
    "@type": "RealEstateListing";
    name: string;
    description?: string;
    url?: string;
    datePosted?: string;
    dateModified?: string;
    image?: string[];
    offers: {
      "@type": "Offer";
      price?: number;
      priceCurrency?: "USD" | "CAD";
      availability?: string;
      url?: string;
      itemOffered: {
        "@type": string;
        numberOfBedrooms?: number;
        numberOfBathroomsTotal?: number;
        floorSize?: {
          "@type": "QuantitativeValue";
          value: number;
          unitCode: "FTK";
        };
        yearBuilt?: number;
        address?: {
          "@type": "PostalAddress";
          streetAddress?: string;
          addressLocality?: string;
          addressRegion?: string;
          postalCode?: string;
          addressCountry?: "US" | "CA";
        };
        geo?: {
          "@type": "GeoCoordinates";
          latitude: number;
          longitude: number;
        };
      };
      offeredBy?: {
        "@type": "RealEstateAgent";
        name: string;
      };
    };
  };
  jsonLdHtml: string;
  etag: string;
};
```

### GET /v1/listings/{listingId}/photos

```ts
type Data = {
  photos: {
    url: string;
    width: number | null;
    height: number | null;
    order: number;
    alt: string;
    id?: string;
    sizes?: {
      width: number;
      url: string;
    }[];
    caption?: string | null;
    room?: string | null;
  }[];
  photoCount: number;
  custom?: {
    listing: {
      key: string;
      value: string | number | boolean;
    }[];
    photos: {
      photoId: string;
      key: string;
      value: string | number | boolean;
    }[];
  };
};
```

### GET /v1/listings/{listingId}/similar

```ts
type Data = {
  subjectId: string;
  listings: {
    listing: {
      id: string;
      slug: string;
      href: string | null;
      mls: {
        id: string;
        name: string;
      };
      mlsNumber: string | null;
      status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
      statusLabel: string;
      price: number | null;
      closePrice: number | null;
      listPrice: number | null;
      closeDate: string | null;
      beds: number | null;
      baths: number | null;
      sqft: number | null;
      lotAcres: number | null;
      yearBuilt: number | null;
      type: string | null;
      subtype: string | null;
      address: {
        display: string;
        street: string | null;
        unit: string | null;
        city: string | null;
        state: string;
        postalCode: string | null;
        hidden: boolean;
      };
      geo: {
        lat: number;
        lng: number;
        precision: "exact" | "approximate";
      } | null;
      photos: {
        url: string;
        width: number | null;
        height: number | null;
        order: number;
        alt: string;
      }[];
      photoCount: number;
      openHouses: {
        start: string;
        end: string;
        timeZone: string | null;
        kind: "in_person" | "virtual";
        remarks: string | null;
      }[];
      badges: {
        kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
        since: string | null;
      }[];
      listedAt: string | null;
      updatedAt: string;
      modifiedAt?: string | null;
      attribution: {
        listOfficeName: string | null;
        listAgentName: string | null;
        contact: {
          agentEmail?: string;
          agentPhone?: string;
          officeEmail?: string;
          officePhone?: string;
        };
        line: string | null;
        courtesy: string | null;
      };
    };
    why: {
      distanceMiles: number | null;
      priceGapPct: number | null;
      sqftGapPct: number | null;
      bedsDiff: number | null;
      bathsDiff: number | null;
      sameSubtype: boolean;
      ageDays: number | null;
      score: number;
    };
  }[];
  area: "box" | "zip" | "shape";
  widened: boolean;
  include: "active" | "active_and_sold" | "sold";
  subjectRemoved: boolean;
};
```

### GET /v1/listings/{listingId}/history

```ts
type Data = {
  listingId: string;
  events: {
    date: string;
    event: "listed" | "price_change" | "status_change" | "sold" | "back_on_market";
    price: number | null;
    status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
    previousPrice: number | null;
    previousStatus: "active" | "coming_soon" | "pending" | "under_contract" | "closed" | null;
  }[];
  truncated: boolean;
};
```

### GET /v1/agents/{agentMlsId}/production

```ts
type Data = {
  agent: {
    memberId: string;
    mlsIds: string[];
    via: "agent" | "office";
  };
  boardsLeftOut: {
    mlsId: string;
    why: "market_stats_off";
  }[];
  period: {
    months: number;
    from: string;
    through: string;
    soldFrom: string | null;
  };
  current: {
    count: number;
    byStatus: {
      active?: number;
      coming_soon?: number;
      pending?: number;
      under_contract?: number;
    };
    listingIds: string[];
  };
  sold: {
    count: number;
    volume: number | null;
    byCity: {
      key: string;
      label: string;
      count: number;
      volume: number | null;
    }[];
    byPostalCode: {
      key: string;
      label: string;
      count: number;
      volume: number | null;
    }[];
    listingIds: string[];
    soldHiddenMlsIds: string[];
    bySide: {
      listing: {
        count: number;
        volume: number | null;
      };
      buyer: {
        count: number;
        volume: number | null;
      };
    };
    buyerSideMlsIds: string[];
    buyerSideSkippedMlsIds: string[];
    truncated: boolean;
  };
};
```

### GET /v1/suggest

```ts
type Data = {
  group: "address" | "listing" | "city" | "zip" | "neighborhood" | "county" | "countyOrParish" | "school" | "subdivision" | "area" | "community" | "mlsArea" | "agent" | "office" | "place";
  label: string;
  where: {
    label: string;
    value: string;
    source: "googleAutocomplete" | "school" | "neighborhood" | "county" | "subdivision" | "area" | "community" | "crm-system" | "subdivisionAndCity" | "addressByOpenSearch" | "listingId" | "countyOrParish" | "customPolygon" | "library";
    data?: {
      type?: string;
      state?: string;
      city?: string;
      postalCode?: string;
      country?: string;
      mlsId?: string;
      address?: string;
      kind?: string;
    };
    city?: string;
    state?: string;
    postalCode?: string;
  };
}[];
```

### GET /v1/boundaries/{boundaryId}

```ts
type Data = {
  id: string;
  kind: "neighborhood" | "county" | "postalCode" | "school" | "schoolDistrict" | "place" | "subdivision";
  name: string;
  state: string | null;
  geometry: {
    type: "Polygon";
    coordinates: number[][][];
  } | {
    type: "MultiPolygon";
    coordinates: number[][][][];
  };
  viewport: {
    south: number;
    west: number;
    north: number;
    east: number;
  };
  source: "platform" | "library";
};
```

### GET /v1/market

```ts
type Data = {
  location: {
    kind: "crm" | "countyOrParish" | "boundary" | "library" | "shape" | "bbox" | "polygon" | "circle";
    label: string;
    viewport: {
      south: number;
      west: number;
      north: number;
      east: number;
    } | null;
    boundary: {
      id: string;
      href: string;
    } | null;
  };
  months: number;
  from: string;
  through: string;
  measures: {
    medianListPrice: {
      measure: "medianListPrice";
      unit: "usd";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    medianSoldPrice: {
      measure: "medianSoldPrice";
      unit: "usd";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    medianPricePerSqft: {
      measure: "medianPricePerSqft";
      unit: "usd_per_sqft";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    medianDaysOnMarket: {
      measure: "medianDaysOnMarket";
      unit: "days";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    listToSaleRatio: {
      measure: "listToSaleRatio";
      unit: "ratio";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    activeInventory: {
      measure: "activeInventory";
      unit: "count";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    newListings: {
      measure: "newListings";
      unit: "count";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    closings: {
      measure: "closings";
      unit: "count";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    monthsOfSupply: {
      measure: "monthsOfSupply";
      unit: "months";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    absorptionRate: {
      measure: "absorptionRate";
      unit: "percent";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    wentUnderContract: {
      measure: "wentUnderContract";
      unit: "count";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    salesVolume: {
      measure: "salesVolume";
      unit: "usd";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    averageSoldPrice: {
      measure: "averageSoldPrice";
      unit: "usd";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    monthsOfInventory: {
      measure: "monthsOfInventory";
      unit: "months";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
    monthsOfInventoryMls: {
      measure: "monthsOfInventoryMls";
      unit: "months";
      current: number | null;
      currentCount: number;
      series: {
        month: string;
        value: number | null;
        count: number;
      }[];
      boards: number;
      partial: boolean;
      partialReason: string | null;
    };
  };
  boards: {
    total: number;
    sold: number;
  };
  coverage: {
    soldFrom: string | null;
    monthsWithoutHistory: number;
  };
  listingType: "sale" | "lease";
  currency: "USD" | "CAD" | null;
  groups: {
    by: "zip" | "city" | "subdivision" | "type" | "beds" | "priceBand" | "month";
    truncated: boolean;
    rows: {
      key: string;
      label: string;
      listings: number;
      measures: {
        medianListPrice: {
          measure: "medianListPrice";
          unit: "usd";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        medianSoldPrice: {
          measure: "medianSoldPrice";
          unit: "usd";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        medianPricePerSqft: {
          measure: "medianPricePerSqft";
          unit: "usd_per_sqft";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        medianDaysOnMarket: {
          measure: "medianDaysOnMarket";
          unit: "days";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        listToSaleRatio: {
          measure: "listToSaleRatio";
          unit: "ratio";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        activeInventory: {
          measure: "activeInventory";
          unit: "count";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        newListings: {
          measure: "newListings";
          unit: "count";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        closings: {
          measure: "closings";
          unit: "count";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        monthsOfSupply: {
          measure: "monthsOfSupply";
          unit: "months";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        absorptionRate: {
          measure: "absorptionRate";
          unit: "percent";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        wentUnderContract: {
          measure: "wentUnderContract";
          unit: "count";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        salesVolume: {
          measure: "salesVolume";
          unit: "usd";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        averageSoldPrice: {
          measure: "averageSoldPrice";
          unit: "usd";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        monthsOfInventory: {
          measure: "monthsOfInventory";
          unit: "months";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
        monthsOfInventoryMls: {
          measure: "monthsOfInventoryMls";
          unit: "months";
          current: number | null;
          currentCount: number;
          series: {
            month: string;
            value: number | null;
            count: number;
          }[];
          boards: number;
          partial: boolean;
          partialReason: string | null;
        };
      };
    }[];
  } | null;
  definitions: {
    name: string;
    label: string;
    definition: string;
    formula: string;
  }[];
  attribution: {
    mls: string;
    mlsName: string;
    from: string;
    through: string;
    line: string;
  }[];
  asOf: string;
};
```

### GET /v1/market/snapshot

```ts
type Data = {
  location: {
    kind: "crm" | "countyOrParish" | "boundary" | "library" | "shape" | "bbox" | "polygon" | "circle";
    label: string;
    viewport: {
      south: number;
      west: number;
      north: number;
      east: number;
    } | null;
    boundary: {
      id: string;
      href: string;
    } | null;
  };
  window: {
    days: 7 | 30 | 60 | 90 | 180 | 365;
    current: {
      from: string;
      through: string;
    };
    prior: {
      from: string;
      through: string;
    };
    yearAgo: {
      from: string;
      through: string;
    };
  };
  listingType: "sale" | "lease";
  currency: "USD" | "CAD" | null;
  metrics: {
    name: "activeListings" | "comingSoon" | "underContractNow" | "newListings" | "backOnMarket" | "priceReductions" | "wentUnderContract" | "daysToContract" | "closings" | "closings12m" | "monthsOfInventory" | "monthsOfInventoryMls" | "absorptionRate" | "pendingRatio" | "marketType" | "listPriceActive" | "listPriceNew" | "soldPrice" | "pricePerSqftSold" | "pricePerSqftActive" | "salesVolume" | "priceBands" | "daysOnMarketSold" | "daysOnMarketActive" | "cumulativeDaysOnMarket" | "saleToList" | "saleToOriginalList" | "overAtUnderList" | "concessions" | "cashShare" | "mixByType" | "mixByBeds";
    label: string;
    unit: "usd" | "usd_per_sqft" | "days" | "ratio" | "count" | "months" | "percent" | "category";
    current: {
      value: number | null;
      average: number | null;
      share: number | null;
      category: "seller" | "balanced" | "buyer" | null;
      count: number;
      breakdown: {
        key: string;
        label: string;
        active: number | null;
        activeShare: number | null;
        contracts: number | null;
        contractsShare: number | null;
        closings: number | null;
        closingsShare: number | null;
      }[] | null;
    };
    prior: {
      value: number | null;
      average: number | null;
      share: number | null;
      category: "seller" | "balanced" | "buyer" | null;
      count: number;
      breakdown: {
        key: string;
        label: string;
        active: number | null;
        activeShare: number | null;
        contracts: number | null;
        contractsShare: number | null;
        closings: number | null;
        closingsShare: number | null;
      }[] | null;
    } | null;
    priorReason: string | null;
    yearAgo: {
      value: number | null;
      average: number | null;
      share: number | null;
      category: "seller" | "balanced" | "buyer" | null;
      count: number;
      breakdown: {
        key: string;
        label: string;
        active: number | null;
        activeShare: number | null;
        contracts: number | null;
        contractsShare: number | null;
        closings: number | null;
        closingsShare: number | null;
      }[] | null;
    } | null;
    yearAgoReason: string | null;
    boards: number;
    partial: boolean;
    partialReason: string | null;
    basis: "monthsOfInventory" | "monthsOfInventoryMls" | null;
  }[];
  groups: {
    by: "zip" | "city" | "subdivision" | "type" | "beds" | "priceBand";
    truncated: boolean;
    rows: {
      key: string;
      label: string;
      listings: number;
      metrics: {
        name: "activeListings" | "comingSoon" | "underContractNow" | "newListings" | "backOnMarket" | "priceReductions" | "wentUnderContract" | "daysToContract" | "closings" | "closings12m" | "monthsOfInventory" | "monthsOfInventoryMls" | "absorptionRate" | "pendingRatio" | "marketType" | "listPriceActive" | "listPriceNew" | "soldPrice" | "pricePerSqftSold" | "pricePerSqftActive" | "salesVolume" | "priceBands" | "daysOnMarketSold" | "daysOnMarketActive" | "cumulativeDaysOnMarket" | "saleToList" | "saleToOriginalList" | "overAtUnderList" | "concessions" | "cashShare" | "mixByType" | "mixByBeds";
        label: string;
        unit: "usd" | "usd_per_sqft" | "days" | "ratio" | "count" | "months" | "percent" | "category";
        current: {
          value: number | null;
          average: number | null;
          share: number | null;
          category: "seller" | "balanced" | "buyer" | null;
          count: number;
          breakdown: {
            key: string;
            label: string;
            active: number | null;
            activeShare: number | null;
            contracts: number | null;
            contractsShare: number | null;
            closings: number | null;
            closingsShare: number | null;
          }[] | null;
        };
        prior: {
          value: number | null;
          average: number | null;
          share: number | null;
          category: "seller" | "balanced" | "buyer" | null;
          count: number;
          breakdown: {
            key: string;
            label: string;
            active: number | null;
            activeShare: number | null;
            contracts: number | null;
            contractsShare: number | null;
            closings: number | null;
            closingsShare: number | null;
          }[] | null;
        } | null;
        priorReason: string | null;
        yearAgo: {
          value: number | null;
          average: number | null;
          share: number | null;
          category: "seller" | "balanced" | "buyer" | null;
          count: number;
          breakdown: {
            key: string;
            label: string;
            active: number | null;
            activeShare: number | null;
            contracts: number | null;
            contractsShare: number | null;
            closings: number | null;
            closingsShare: number | null;
          }[] | null;
        } | null;
        yearAgoReason: string | null;
        boards: number;
        partial: boolean;
        partialReason: string | null;
        basis: "monthsOfInventory" | "monthsOfInventoryMls" | null;
      }[];
    }[];
  } | null;
  boards: {
    total: number;
    sold: number;
    contractDate: number;
  };
  definitions: {
    name: string;
    label: string;
    definition: string;
    formula: string;
  }[];
  attribution: {
    mls: string;
    mlsName: string;
    from: string;
    through: string;
    line: string;
  }[];
  asOf: string;
};
```

### GET /v1/market/metrics

```ts
type Data = {
  metrics: {
    name: "activeListings" | "comingSoon" | "underContractNow" | "newListings" | "backOnMarket" | "priceReductions" | "wentUnderContract" | "daysToContract" | "closings" | "closings12m" | "monthsOfInventory" | "monthsOfInventoryMls" | "absorptionRate" | "pendingRatio" | "marketType" | "listPriceActive" | "listPriceNew" | "soldPrice" | "pricePerSqftSold" | "pricePerSqftActive" | "salesVolume" | "priceBands" | "daysOnMarketSold" | "daysOnMarketActive" | "cumulativeDaysOnMarket" | "saleToList" | "saleToOriginalList" | "overAtUnderList" | "concessions" | "cashShare" | "mixByType" | "mixByBeds";
    label: string;
    group: "inventory" | "pace" | "price" | "time" | "negotiation" | "mix";
    definition: string;
    formula: string;
    unit: "usd" | "usd_per_sqft" | "days" | "ratio" | "count" | "months" | "percent" | "category";
    medianAndAverage: boolean;
    fields: string[];
    statuses: string[];
    windowed: boolean;
    boards: {
      mls: string;
      mlsName: string;
      available: boolean;
      reason: string | null;
    }[];
  }[];
  definitions: {
    name: string;
    label: string;
    definition: string;
    formula: string;
  }[];
  boards: {
    mls: string;
    mlsName: string;
    soldData: boolean;
    contractDateFill: number | null;
  }[];
  windowDays: (7 | 30 | 60 | 90 | 180 | 365)[];
  groupBy: ("zip" | "city" | "subdivision" | "type" | "beds" | "priceBand" | "month")[];
};
```

### GET /v1/shapes

```ts
type Data = {
  shapes: {
    id: string;
    name: string;
    slug: string;
    vertexCount: number;
    viewport: {
      south: number;
      west: number;
      north: number;
      east: number;
    };
    href: string;
    siteId: string | null;
    updatedAt: string;
  }[];
};
```

### GET /v1/shapes/{shapeId}

```ts
type Data = {
  id: string;
  name: string;
  slug: string;
  vertexCount: number;
  viewport: {
    south: number;
    west: number;
    north: number;
    east: number;
  };
  href: string;
  siteId: string | null;
  updatedAt: string;
  geometry: {
    type: "Polygon";
    coordinates: number[][][];
  } | {
    type: "MultiPolygon";
    coordinates: number[][][][];
  };
};
```

### GET /v1/collections

```ts
type Data = {
  collections: {
    id: string;
    name: string;
    query: string;
    handPicked: boolean;
    options: {
      hideBackground?: boolean;
      hideSearchbar?: boolean;
      hideButtons?: boolean;
      newTab?: boolean;
      forceRegistration?: boolean;
      limit?: number;
      listingsPerPage?: number;
      iframeTopMargin?: number;
      registrationPopupAfter?: number;
      customCrmTags?: string;
      menuPlacement?: "bottom" | "top" | "auto";
      nextButtonPosition?: "left" | "center" | "right";
    };
    updatedAt: string;
  }[];
  nextCursor: string | null;
};
```

### GET /v1/collections/{collectionId}

```ts
type Data = {
  id: string;
  name: string;
  query: string;
  handPicked: boolean;
  options: {
    hideBackground?: boolean;
    hideSearchbar?: boolean;
    hideButtons?: boolean;
    newTab?: boolean;
    forceRegistration?: boolean;
    limit?: number;
    listingsPerPage?: number;
    iframeTopMargin?: number;
    registrationPopupAfter?: number;
    customCrmTags?: string;
    menuPlacement?: "bottom" | "top" | "auto";
    nextButtonPosition?: "left" | "center" | "right";
  };
  updatedAt: string;
};
```

### GET /v1/collections/{collectionId}/listings

```ts
type Data = {
  listings: {
    id: string;
    slug: string;
    href: string | null;
    mls: {
      id: string;
      name: string;
    };
    mlsNumber: string | null;
    status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
    statusLabel: string;
    price: number | null;
    closePrice: number | null;
    listPrice: number | null;
    closeDate: string | null;
    beds: number | null;
    baths: number | null;
    sqft: number | null;
    lotAcres: number | null;
    yearBuilt: number | null;
    type: string | null;
    subtype: string | null;
    address: {
      display: string;
      street: string | null;
      unit: string | null;
      city: string | null;
      state: string;
      postalCode: string | null;
      hidden: boolean;
    };
    geo: {
      lat: number;
      lng: number;
      precision: "exact" | "approximate";
    } | null;
    photos: {
      url: string;
      width: number | null;
      height: number | null;
      order: number;
      alt: string;
    }[];
    photoCount: number;
    openHouses: {
      start: string;
      end: string;
      timeZone: string | null;
      kind: "in_person" | "virtual";
      remarks: string | null;
    }[];
    badges: {
      kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
      since: string | null;
    }[];
    listedAt: string | null;
    updatedAt: string;
    modifiedAt?: string | null;
    attribution: {
      listOfficeName: string | null;
      listAgentName: string | null;
      contact: {
        agentEmail?: string;
        agentPhone?: string;
        officeEmail?: string;
        officePhone?: string;
      };
      line: string | null;
      courtesy: string | null;
    };
  } | {
    id: string;
    slug: string;
    href: string | null;
    mls: {
      id: string;
      name: string;
    };
    mlsNumber: string | null;
    status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
    statusLabel: string;
    price: number | null;
    closePrice: number | null;
    listPrice: number | null;
    closeDate: string | null;
    beds: number | null;
    baths: number | null;
    sqft: number | null;
    lotAcres: number | null;
    yearBuilt: number | null;
    type: string | null;
    subtype: string | null;
    address: {
      display: string;
      street: string | null;
      unit: string | null;
      city: string | null;
      state: string;
      postalCode: string | null;
      hidden: boolean;
    };
    geo: {
      lat: number;
      lng: number;
      precision: "exact" | "approximate";
    } | null;
    photos: {
      url: string;
      width: number | null;
      height: number | null;
      order: number;
      alt: string;
    }[];
    photoCount: number;
    openHouses: {
      start: string;
      end: string;
      timeZone: string | null;
      kind: "in_person" | "virtual";
      remarks: string | null;
    }[];
    badges: {
      kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
      since: string | null;
    }[];
    listedAt: string | null;
    updatedAt: string;
    modifiedAt?: string | null;
    attribution: {
      listOfficeName: string | null;
      listAgentName: string | null;
      contact: {
        agentEmail?: string;
        agentPhone?: string;
        officeEmail?: string;
        officePhone?: string;
      };
      line: string | null;
      courtesy: string | null;
    };
    description: string | null;
    details: {
      categoryId: string;
      label: string;
      items: {
        key: string;
        label: string;
        value: string | number | boolean | string[];
      }[];
    }[];
    virtualTourUrl: string | null;
  } | {
    id: string;
    slug: string;
    href: string | null;
    mls: {
      id: string;
      name: string;
    };
    status: "active" | "coming_soon" | "pending" | "under_contract" | "closed";
    price: number | null;
    geo: {
      lat: number;
      lng: number;
      precision: "exact" | "approximate";
    };
    address: string;
    badges: {
      kind: "new" | "back_on_market" | "price_change" | "coming_soon" | "open_house" | "sold";
      since: string | null;
    }[];
  }[];
  total: number;
  page: number;
  limit: number;
  nextCursor: string | null;
  viewport: {
    south: number;
    west: number;
    north: number;
    east: number;
  } | null;
  viewportSource: "boundary" | "library" | "drawn" | "results" | "shape" | null;
  boundary: {
    id: string;
    href: string;
  } | null;
  head: {
    title: string;
    description: string;
    canonical: string | null;
    robots: string;
    og: {
      title: string;
      description: string;
      url: string | null;
      image: string | null;
      type: "website";
    };
    twitter: {
      card: "summary_large_image" | "summary";
      title: string;
      description: string;
      image: string | null;
    };
  };
  jsonLd: {
    "@context": "https://schema.org";
    "@type": "ItemList";
    name: string;
    numberOfItems: number;
    itemListElement: {
      "@type": "ListItem";
      position: number;
      url: string;
    }[];
  } | {
    "@context": "https://schema.org";
    "@type": "BreadcrumbList";
    itemListElement: {
      "@type": "ListItem";
      position: number;
      name: string;
      item: string;
    }[];
  }[];
  jsonLdHtml: string;
  location: {
    label: string | null;
  };
  pages: number;
};
```

### GET /v1/render/listings

```ts
type Data = {
  html: string;
  head: {
    css: string;
    jsonLd: {
      "@context": "https://schema.org";
      "@type": "RealEstateListing";
      name: string;
      description?: string;
      url?: string;
      datePosted?: string;
      dateModified?: string;
      image?: string[];
      offers: {
        "@type": "Offer";
        price?: number;
        priceCurrency?: "USD" | "CAD";
        availability?: string;
        url?: string;
        itemOffered: {
          "@type": string;
          numberOfBedrooms?: number;
          numberOfBathroomsTotal?: number;
          floorSize?: {
            "@type": "QuantitativeValue";
            value: number;
            unitCode: "FTK";
          };
          yearBuilt?: number;
          address?: {
            "@type": "PostalAddress";
            streetAddress?: string;
            addressLocality?: string;
            addressRegion?: string;
            postalCode?: string;
            addressCountry?: "US" | "CA";
          };
          geo?: {
            "@type": "GeoCoordinates";
            latitude: number;
            longitude: number;
          };
        };
        offeredBy?: {
          "@type": "RealEstateAgent";
          name: string;
        };
      };
    } | {
      "@context": "https://schema.org";
      "@type": "ItemList";
      name: string;
      numberOfItems: number;
      itemListElement: {
        "@type": "ListItem";
        position: number;
        url: string;
      }[];
    } | {
      "@context": "https://schema.org";
      "@type": "BreadcrumbList";
      itemListElement: {
        "@type": "ListItem";
        position: number;
        name: string;
        item: string;
      }[];
    }[];
    jsonLdHtml: string;
    meta: {
      title: string;
      description: string;
      canonical: string | null;
      robots: string;
      og: {
        title: string;
        description: string;
        url: string | null;
        image: string | null;
        type: "website";
      };
      twitter: {
        card: "summary_large_image" | "summary";
        title: string;
        description: string;
        image: string | null;
      };
    } | {
      title: string;
      description: string;
      canonical: string | null;
      robots: string;
      og: {
        title: string;
        description: string;
        url: string | null;
        image: string | null;
        type: "website";
      };
      twitter: {
        card: "summary_large_image" | "summary";
        title: string;
        description: string;
        image: string | null;
      };
    };
  };
  widgetVersion: string;
};
```

### GET /v1/render/listing/{listingId}

```ts
type Data = {
  html: string;
  head: {
    css: string;
    jsonLd: {
      "@context": "https://schema.org";
      "@type": "RealEstateListing";
      name: string;
      description?: string;
      url?: string;
      datePosted?: string;
      dateModified?: string;
      image?: string[];
      offers: {
        "@type": "Offer";
        price?: number;
        priceCurrency?: "USD" | "CAD";
        availability?: string;
        url?: string;
        itemOffered: {
          "@type": string;
          numberOfBedrooms?: number;
          numberOfBathroomsTotal?: number;
          floorSize?: {
            "@type": "QuantitativeValue";
            value: number;
            unitCode: "FTK";
          };
          yearBuilt?: number;
          address?: {
            "@type": "PostalAddress";
            streetAddress?: string;
            addressLocality?: string;
            addressRegion?: string;
            postalCode?: string;
            addressCountry?: "US" | "CA";
          };
          geo?: {
            "@type": "GeoCoordinates";
            latitude: number;
            longitude: number;
          };
        };
        offeredBy?: {
          "@type": "RealEstateAgent";
          name: string;
        };
      };
    } | {
      "@context": "https://schema.org";
      "@type": "ItemList";
      name: string;
      numberOfItems: number;
      itemListElement: {
        "@type": "ListItem";
        position: number;
        url: string;
      }[];
    } | {
      "@context": "https://schema.org";
      "@type": "BreadcrumbList";
      itemListElement: {
        "@type": "ListItem";
        position: number;
        name: string;
        item: string;
      }[];
    }[];
    jsonLdHtml: string;
    meta: {
      title: string;
      description: string;
      canonical: string | null;
      robots: string;
      og: {
        title: string;
        description: string;
        url: string | null;
        image: string | null;
        type: "website";
      };
      twitter: {
        card: "summary_large_image" | "summary";
        title: string;
        description: string;
        image: string | null;
      };
    } | {
      title: string;
      description: string;
      canonical: string | null;
      robots: string;
      og: {
        title: string;
        description: string;
        url: string | null;
        image: string | null;
        type: "website";
      };
      twitter: {
        card: "summary_large_image" | "summary";
        title: string;
        description: string;
        image: string | null;
      };
    };
  };
  widgetVersion: string;
};
```

### GET /v1/changes

```ts
type Data = {
  changes: {
    kind: "upsert" | "removed" | "scope_removed";
    id: string;
    slug: string | null;
    updatedAt: string;
    modifiedAt?: string | null;
    change?: "created" | "price_changed" | "status_changed" | "removed" | "updated" | "photos_changed";
    previous?: {
      price: number | null;
      status: "active" | "coming_soon" | "pending" | "under_contract" | "closed" | null;
    };
    current?: {
      price: number | null;
      status: "active" | "coming_soon" | "pending" | "under_contract" | "closed" | null;
    };
  }[];
  nextCursor: string;
  asOf: string;
  hasMore: boolean;
};
```

### GET /v1/beacon

```ts
type Data = {
  recorded: boolean;
};
```

### GET /v1/events

```ts
type Data = {
  accepted: number;
  dropped: number;
};
```

### GET /v1/mortgage/estimate

```ts
type Data = {
  country: "US" | "CA";
  currency: "USD" | "CAD";
  inputs: {
    price: number;
    downPayment: number;
    downPaymentPercent: number;
    loanType: "conventional" | "fha" | "va" | "usda" | "jumbo" | "fixed" | "variable" | "adjustable";
    termYears: number;
    rateType: "fixed" | "arm";
    amortizationYears: number | null;
    creditScore: "760+" | "740-759" | "720-739" | "700-719" | "680-699" | "660-679" | "640-659" | "620-639" | "<620";
    state: string;
    zip: string | null;
  };
  options: {
    loanTypes: {
      value: string;
      label: string;
    }[];
    terms: {
      value: string;
      label: string;
    }[];
  };
  eligible: boolean;
  ineligibleReasons: string[];
  rate: {
    annualPercent: number;
    asOf: string;
    isEstimated: boolean;
    isOverride: boolean;
  };
  loan: {
    amount: number;
    ltvPercent: number;
    cashAtClosing: number;
  };
  monthly: {
    principalAndInterest: number;
    propertyTax: number;
    homeInsurance: number;
    mortgageInsurance: number;
    hoa: number;
    total: number;
    provenance: {
      propertyTax: "actual" | "estimated";
      homeInsurance: "actual" | "estimated";
      hoa: "actual" | "estimated";
    };
  };
  mortgageInsuranceNote: string | null;
  requiredDisclosures: string[];
  stale: boolean;
};
```

### GET /v1/usage

```ts
type Data = {
  site: {
    id: string;
    label: string;
  } | null;
  keys: {
    id: string;
    kind: "pk" | "sk";
    hint: string;
    status: "active" | "rotating";
    expiresAt: string | null;
    caller: boolean;
    quota: {
      dailyUnits: number;
      used: number;
      remaining: number;
      resetsAt: string;
    };
    limits: {
      searchPerMin: number;
      searchPer5s: number;
      suggestPerMin: number;
      suggestPer5s: number;
      detailPerMin: number;
      feedPerMin: number;
      idsPerMin: number;
      telemetryPerMin: number;
      perIpPerMin: number;
      dailyUnits: number;
    };
    rateWindows: {
      search: {
        per5Seconds: number | null;
        perMinute: number;
      };
      suggest: {
        per5Seconds: number | null;
        perMinute: number;
      };
      detail: {
        per5Seconds: number | null;
        perMinute: number;
      };
      feed: {
        per5Seconds: number | null;
        perMinute: number;
      };
    };
  }[];
  addons: {
    key: string;
    name: string;
    enabled: boolean;
    perMinute: number;
    daily: {
      limit: number;
      used: number;
      remaining: number;
      resetsAt: string;
    };
    market?: {
      perMinute: number;
      daily: {
        limit: number;
        used: number;
        remaining: number;
        resetsAt: string;
      };
    };
  }[];
  dailyRequestCaps: {
    opClass: "telemetry" | "free";
    limit: number;
    used: number;
    remaining: number;
    resetsAt: string;
  }[];
  days: {
    day: string;
    keyId: string;
    requests: number;
    errors: number;
    rateLimited: number;
    units: number;
    byOp: {
      status?: number;
      meta?: number;
      filters?: number;
      "filters.options"?: number;
      "listings.search"?: number;
      "listings.ids"?: number;
      "listings.get"?: number;
      "listings.photos"?: number;
      "listings.similar"?: number;
      "listings.history"?: number;
      "agents.production"?: number;
      suggest?: number;
      "boundaries.get"?: number;
      market?: number;
      "market.snapshot"?: number;
      "market.metrics"?: number;
      "shapes.list"?: number;
      "shapes.get"?: number;
      "collections.list"?: number;
      "collections.get"?: number;
      "collections.listings"?: number;
      "render.listings"?: number;
      "render.listing"?: number;
      changes?: number;
      beacon?: number;
      events?: number;
      "mortgage.estimate"?: number;
      usage?: number;
      "account.billing"?: number;
      "publicRecords.lookup"?: number;
      "publicRecords.market"?: number;
      "publicRecords.history"?: number;
      "sandbox.publicRecords.lookup"?: number;
      "sandbox.publicRecords.history"?: number;
    };
  }[];
  totals: {
    requests: number;
    errors: number;
    rateLimited: number;
    units: number;
  };
  rolledUpThrough: string | null;
};
```

### GET /v1/account/billing

```ts
type Data = {
  plan: "starter" | "standard" | "pro";
  status: "none" | "trialing" | "active" | "past_due" | "paused" | "canceled";
  paymentMethod: "card" | "invoice";
  interval: "month" | "year";
  billingStartedAt: string | null;
  nextInvoiceAt: string | null;
  graceUntil: string | null;
  cancelAtPeriodEnd: boolean;
  accessEndsAt: string | null;
  pricingModel: "flat" | "per_board";
  boards: {
    billed: number;
    included: number | null;
  };
  lines: {
    kind: "plan" | "board" | "addon" | "fee";
    label: string;
    quantity: number;
    unitAmountCents: number | null;
    amountCents: number | null;
    currency: string | null;
    interval: "month" | "year" | "one_time";
    mlsId: string | null;
    waived: boolean;
  }[];
  addons: {
    key: string;
    name: string;
    enabled: boolean;
    enabledAt: string | null;
    endsAt: string | null;
    limits: {
      perMinute: number;
      perDay: number;
    } | null;
  }[];
};
```

### GET /v1/public-records/lookup

```ts
type Data = {
  resolvedBy: "address" | "parcelNumber";
  purpose: "cma" | "listing_presentation";
  record: {
    recordId: string;
    parcelNumber: string | null;
    address: string | null;
    unit: string | null;
    city: string | null;
    state: string | null;
    postalCode: string | null;
    lat: number | null;
    lng: number | null;
    propertySubType: string | null;
    bedrooms: number | null;
    bathrooms: number | null;
    livingArea: number | null;
    lotSizeAcres: number | null;
    yearBuilt: number | null;
    yearBuiltEffective: number | null;
    stories: number | null;
    garageSpaces: number | null;
    pool: boolean | null;
    basement: string | null;
    condition: string | null;
    tax: {
      year: number | null;
      annualAmount: number | null;
      assessedYear: number | null;
      assessedValue: number | null;
      marketValue: number | null;
    };
    lastSale: {
      price: number | null;
      recordingDate: string | null;
      documentType: string | null;
    } | null;
    occupancy: "owner" | "absentee" | null;
    loans: {
      totalOriginal: number | null;
      estimatedBalance: number | null;
      first: {
        amount: number | null;
        rate: number | null;
        type: string | null;
        recordingDate: string | null;
        lenderType: string | null;
      } | null;
      second: {
        amount: number | null;
        recordingDate: string | null;
      } | null;
    };
    asOf: string | null;
    owner?: {
      names: string[];
      mailingAddress: {
        line1: string | null;
        unit: string | null;
        city: string | null;
        state: string | null;
        postalCode: string | null;
      } | null;
      careOf: string | null;
      occupancy: "owner" | "absentee" | null;
    };
  };
};
```

### GET /v1/public-records/market

```ts
type Data = {
  area: {
    kind: "zip" | "city" | "county";
    label: string;
    postalCodes: string[];
  };
  filters: {
    type: "single_family" | "condo" | "townhouse" | "multi_family" | null;
    yearMin: number | null;
    yearMax: number | null;
  };
  period: {
    months: number;
    from: string;
    through: string;
  };
  minimumProperties: number;
  measures: {
    homes: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    ownerOccupiedShare: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    absenteeOwnerShare: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    medianYearsOwned: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    sales12m: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    medianLastSalePrice12m: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    medianSalePricePerSqft12m: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    openMortgageShare: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
    medianEquityShare: {
      value: number | null;
      properties: number | null;
      reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
    };
  };
  salesByMonth: {
    month: string;
    sales: number | null;
    reason: "fewer_than_10_properties" | "fewer_than_10_on_one_side" | null;
  }[];
  definitions: {
    homes: string;
    ownerOccupiedShare: string;
    absenteeOwnerShare: string;
    medianYearsOwned: string;
    sales12m: string;
    medianLastSalePrice12m: string;
    medianSalePricePerSqft12m: string;
    openMortgageShare: string;
    medianEquityShare: string;
    salesByMonth: string;
  };
};
```

### GET /v1/public-records/{recordId}/history

```ts
type Data = {
  recordId: string;
  purpose: "cma" | "listing_presentation";
  asOf: string | null;
  transfers: {
    recordingDate: string | null;
    contractDate: string | null;
    documentType: string | null;
    price: number | null;
    pricePerSqft: number | null;
    cashPurchase: boolean | null;
    intraFamily: boolean | null;
    distressed: boolean | null;
    reo: string | null;
    titleCompany: string | null;
    documentNumber: string | null;
    buyers?: {
      names: string[];
      vesting: string | null;
      mailingAddress: {
        line1: string | null;
        city: string | null;
        state: string | null;
        postalCode: string | null;
      } | null;
    };
    sellers?: {
      names: string[];
      mailingAddress: {
        line1: string | null;
        city: string | null;
        state: string | null;
        postalCode: string | null;
      } | null;
    };
  }[];
  mortgages: {
    recordingDate: string | null;
    amount: number | null;
    purpose: string | null;
    type: string | null;
    rate: number | null;
    termMonths: number | null;
    dueDate: string | null;
    heloc: boolean;
    purchaseMoney: boolean | null;
    lender: string | null;
    lenderType: string | null;
    titleCompany: string | null;
    documentNumber: string | null;
    status: "open" | "released" | "paid_off";
    closedBy: "release" | "sale" | "refinance" | null;
    closedOn: string | null;
    borrowers?: string[];
  }[];
};
```

### GET /v1/sandbox/public-records/lookup

```ts
type Data = {
  found: boolean;
  resolvedBy: "address" | "parcelNumber" | "propertyId";
  propertyId: string | null;
  record: {
    recordId: string;
    parcelNumber: string | null;
    address: string | null;
    unit: string | null;
    city: string | null;
    state: string | null;
    postalCode: string | null;
    lat: number | null;
    lng: number | null;
    propertySubType: string | null;
    bedrooms: number | null;
    bathrooms: number | null;
    livingArea: number | null;
    lotSizeAcres: number | null;
    yearBuilt: number | null;
    yearBuiltEffective: number | null;
    stories: number | null;
    garageSpaces: number | null;
    pool: boolean | null;
    basement: string | null;
    condition: string | null;
    tax: {
      year: number | null;
      annualAmount: number | null;
      assessedYear: number | null;
      assessedValue: number | null;
      marketValue: number | null;
    };
    lastSale: {
      price: number | null;
      recordingDate: string | null;
      documentType: string | null;
    } | null;
    occupancy: "owner" | "absentee" | null;
    loans: {
      totalOriginal: number | null;
      estimatedBalance: number | null;
      first: {
        amount: number | null;
        rate: number | null;
        type: string | null;
        recordingDate: string | null;
        lenderType: string | null;
      } | null;
      second: {
        amount: number | null;
        recordingDate: string | null;
      } | null;
    };
    avm: {
      value: number | null;
      low: number | null;
      high: number | null;
      confidence: number | null;
      asOf: string | null;
    } | null;
    asOf: string | null;
    owner?: {
      names: string[];
      mailingAddress: {
        line1: string | null;
        unit: string | null;
        city: string | null;
        state: string | null;
        postalCode: string | null;
      } | null;
      careOf: string | null;
      occupancy: "owner" | "absentee" | null;
    };
  } | null;
};
```

### GET /v1/sandbox/public-records/{recordId}/history

```ts
type Data = {
  recordId: string;
  asOf: string | null;
  transfers: {
    recordingDate: string | null;
    contractDate: string | null;
    documentType: string | null;
    price: number | null;
    pricePerSqft: number | null;
    cashPurchase: boolean | null;
    intraFamily: boolean | null;
    distressed: boolean | null;
    reo: string | null;
    titleCompany: string | null;
    documentNumber: string | null;
    buyers?: {
      names: string[];
      vesting: string | null;
      mailingAddress: {
        line1: string | null;
        city: string | null;
        state: string | null;
        postalCode: string | null;
      } | null;
    };
    sellers?: {
      names: string[];
      mailingAddress: {
        line1: string | null;
        city: string | null;
        state: string | null;
        postalCode: string | null;
      } | null;
    };
  }[];
  mortgages: {
    recordingDate: string | null;
    amount: number | null;
    purpose: string | null;
    type: string | null;
    rate: number | null;
    termMonths: number | null;
    dueDate: string | null;
    heloc: boolean;
    purchaseMoney: boolean | null;
    lender: string | null;
    lenderType: string | null;
    titleCompany: string | null;
    documentNumber: string | null;
    status: "open" | "released" | "paid_off";
    closedBy: "release" | "sale" | "refinance" | null;
    closedOn: string | null;
    borrowers?: string[];
  }[];
};
```
