# The TypeScript SDK

Source: https://help.ruuster.com/idx/guide-sdk

> Install @ruuster/idx, create the client with your secret key on your server, add the ready-made listings route your pages call, call every endpoint with typed results, handle errors and retries, and use the page, formatting and webhook helpers.

`@ruuster/idx` is the TypeScript client for the Ruuster Listings API. It calls the API with `fetch`,
types every answer from the API's own response schemas, and adds the helpers a listing site needs:
head tags, listing URLs, JSON-LD, photo attributes, number and date formatting, display rules and
webhook verification. It has no dependencies and runs on Node.js 18.17 or later and on edge
runtimes. It also ships `@ruuster/idx/route`, the ready-made listings route your web pages call, so
no key is ever in a page.

## Install

```sh
npm install @ruuster/idx
```

The package is plain JavaScript (ES modules) with its own TypeScript types, so it works as installed
in Next.js, Astro, Remix, SvelteKit, Nuxt, Vite and plain Node.js 18.17 or later, with no settings to
add. It has no dependencies.

The CRM helpers for your lead forms are in the same package under `@ruuster/idx/crm` (see
[Send leads to your CRM](#send-leads-to-your-crm) below and [Your CRM](https://help.ruuster.com/idx/crm-overview)).

## Create the client

Make one client for your server and import it wherever you call the API. In Next.js this file lives
in `lib/idx.ts`:

<p class="code-title"><code>lib/idx.ts</code></p>

```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";
```

The client reads these settings:

| Option | What it does |
|---|---|
| `secretKey` | Your `idx_sk_…` key, from `IDX_SECRET_KEY`. Sent as `Authorization: Bearer`. Server only. |
| `detailHref` | Your listing page template, such as `/homes/{slug}`. Sent on every call that takes it, so each listing's `href` and canonical URL point at your own page. A call can send its own. |
| `siteOrigin` | Your site's origin from `SITE_ORIGIN`, such as `https://www.example.com`. `idx.toMetadata` uses it to make a relative canonical URL absolute. It never changes an absolute URL the API sent (see below). |
| `baseUrl` | Leave it unset. It defaults to the production API. |
| `next` | Next.js fetch cache options passed on every request, such as `{ revalidate: 300 }`. |
| `retries`, `maxRetryAfterSec` | How rate limits are retried (below). Defaults: 2 retries, at most 10 seconds of waiting. |
| `fetch` | Your own `fetch`, for a runtime without a global one. |

Canonical URLs, card `href`s and the URLs in JSON-LD come from the API. A relative `detailHref` or
`pageHref` is made absolute with your live domain: the first domain on your account's allowed list that is
not `localhost`, which is also the domain of the detail-page template you set in your console. So on
`localhost` and on staging the canonical URL still names your live site, which is what search engines
should see. Your sitemaps and `robots.txt` use `SITE_ORIGIN`, so they follow the server they run on.

The secret key stays on your server. Creating a client with `secretKey` in a browser throws "Keep
IDX_SECRET_KEY on your server."

## Your listings route

Your web pages carry no key. Code that runs in the browser (a search box, filter choices, the
mortgage calculator) calls your own listings route, and the route calls the Listings API from your
server with your secret key. The SDK ships the route ready-made:

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

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

It reads `IDX_SECRET_KEY` from your server's environment and takes these options:

| Option | What it does |
|---|---|
| `basePath` | The path the route answers on, such as `/api/idx`. Everything after it is the API path. |
| `secretKey` | Your secret key. Default `process.env.IDX_SECRET_KEY`. |
| `perVisitorPerMinute` | Requests a minute one visitor (by IP address) may make. Default 120. |
| `cacheSeconds` | How long your CDN may keep a successful answer. Default 60; 0 turns it off. |
| `apiBaseUrl` | Leave it unset. It defaults to the production API. |

The route passes on only what a page may ask for (search, a listing and its photos, history and
similar homes, suggestions, filters and their choices, `meta`, boundaries and shapes, collections,
rendered HTML, market numbers, the mortgage estimate, agent production, page events and the page
beacon), answers 404 for everything only a secret key may do (the listing ids, the change feed,
usage, billing and public records), and never forwards a key from the page. It runs on any platform
that hands you a standard `Request` and takes a `Response` back: Next.js, Astro, SvelteKit, Remix,
Hono, Cloudflare Workers, and Vercel or Netlify functions. Always use it rather than writing your own
pass-through route, which can pass on calls only your secret key should make.

In the browser, ask the route with `fetch`. This component fills a list as the visitor types:

```tsx
"use client";
import { useState } from "react";
import type { SuggestRow } from "@ruuster/idx";

export function PlacePicker() {
  const [rows, setRows] = useState<readonly SuggestRow[]>([]);
  return (
    <div>
      <input
        aria-label="City, neighborhood or ZIP code"
        onChange={async (e) => {
          const q = e.target.value;
          if (q.length < 3) return setRows([]);
          const res = await fetch(`/api/idx/suggest?${new URLSearchParams({ q, limit: "5" })}`);
          const body = await res.json();
          setRows(body.ok ? body.data : []);
        }}
      />
      <ul>
        {rows.map((row) => (
          <li key={`${row.group}:${row.where.value}`}>{row.label}</li>
        ))}
      </ul>
    </div>
  );
}
```

The `SearchBox` recipe component does the same with keyboard and screen-reader support: give it
`baseUrl="/api/idx"` (see [Recipe components](https://help.ruuster.com/idx/recipe-components)).

## Every answer is a result

Each method answers an `IdxResult`. It never throws for an HTTP error, so you decide what each
status means on your page:

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

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const r = await idx.search({ zip: "30308", status: "active", limit: 12 });
if (r.ok) {
  console.log(r.data.total, r.data.listings.length, r.meta.mls.length);
} else {
  console.error(r.status, r.error.code, r.error.message, r.requestId);
}
```

| Field | On success | On failure |
|---|---|---|
| `ok` | `true` | `false` |
| `status` | The HTTP status (200) | The HTTP status, or 0 when the request did not complete |
| `data` | The answer's data, typed per method | |
| `meta` | `freshness.asOf` and `mls`, the display rules of every board in the answer. Always there after `r.ok` (only `idx.status()` answers `meta: null`), so `r.meta.mls` needs no check | |
| `etag` | The answer's ETag | |
| `error` | | `code`, `message`, `retryable`, and `mls` when the error carries display rules |
| `requestId` | | The id to quote to support |
| `headers` | The response headers (rate-limit headers included) | The response headers, or null |

A network failure or a body that is not JSON answers `{ ok: false, status: 0, error: { code:
"network_error", … } }`. Calling `ids` or `changes` without a secret key answers
`secret_key_required`, and a client with no key at all answers `missing_credentials`, both without a
request. Every other `code` is the API's own (see [Errors](https://help.ruuster.com/idx/reference-errors)).

## Retries

When the API answers 429 (rate limited) or 503 (briefly unavailable) with a `Retry-After` header, the
client waits that many seconds and tries again, up to `retries` times (2 by default). It waits only
when `Retry-After` is at most `maxRetryAfterSec` (10 by default); a longer wait comes back to you as
the failure. Other statuses are never retried, and neither is a 429 or 503 without `Retry-After`.

On a server-rendered page, throw on a 429 or 503 that is still failing. Next.js then keeps serving
the last good page from its cache instead of an error:

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

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY, retries: 1, maxRetryAfterSec: 5 });
const r = await idx.market({ city: "Atlanta", state: "GA", months: 12 });
if (!r.ok && (r.status === 429 || r.status === 503 || r.status === 0)) throw new Error(`Listings API ${r.status} ${r.error.code}`);
console.log(r.ok ? r.data.measures.medianSoldPrice.current : r.error.message);
```

## The methods

| Method | Endpoint | Key |
|---|---|---|
| `idx.search(query)` | GET /listings | secret, or a page through your listings route |
| `idx.get(listingId)` | GET /listings/{listingId} | secret, or a page through your listings route |
| `idx.similar(listingId, query)` | GET /listings/{listingId}/similar | secret, or a page through your listings route |
| `idx.suggest(query)` | GET /suggest | secret, or a page through your listings route |
| `idx.filters()` | GET /filters | secret, or a page through your listings route |
| `idx.filterOptions(query)` | GET /filters/options | secret, or a page through your listings route |
| `idx.boundary(boundaryId)` | GET /boundaries/{boundaryId} | secret, or a page through your listings route |
| `idx.market(query)` | GET /market | secret, or a page through your listings route |
| `idx.collectionListings(collectionId, query)` | GET /collections/{collectionId}/listings | secret, or a page through your listings route |
| `idx.mortgage(query)` | GET /mortgage/estimate | secret, or a page through your listings route |
| `idx.meta()` | GET /meta | secret, or a page through your listings route |
| `idx.ids(query)` | GET /listings/ids | secret |
| `idx.changes(query)` | GET /changes | secret |
| `idx.publicRecords.lookup(query)` | GET /public-records/lookup | secret, with the Public Records add-on |
| `idx.publicRecords.history(recordId, query)` | GET /public-records/{recordId}/history | secret, with the Public Records add-on |
| `idx.publicRecords.market(query)` | GET /public-records/market | secret, with the Public Records add-on |
| `idx.status()` | GET /status | none |
| `idx.request(path, query)` | any other endpoint | as the endpoint needs |

Query objects use the API's own parameter names, typed from the parameter table: enums such as
`status` and `sort` only accept their values. Arrays become repeated parameters (or one comma list
where the API takes one, such as `filterByMls` and `groups`), `where` objects are sent as JSON, a
`bbox` object `{ south, west, north, east }` becomes `south,west,north,east`, booleans become `1` or
`0`, and `f: { garageSpacesMin: 2 }` becomes `f.garageSpacesMin=2`. `toQueryString(query)` gives
the same string, if you build URLs yourself.

### Search by a place

Look the place up with `suggest`, then pass its `where` object to `search` unchanged:

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

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY, detailHref: "/homes/{slug}" });
const s = await idx.suggest({ q: "Midtown Atlanta", groups: ["neighborhood", "place"], limit: 3 });
if (!s.ok || !s.data.length) throw new Error("No place found");
const r = await idx.search({ where: s.data[0].where, status: "active", bedsMin: 2, sort: "price_asc", limit: 12 });
if (!r.ok) throw new Error(r.error.code);
for (const l of r.data.listings) console.log(l.href, l.price, l.address.display);
```

A query without `view` answers cards (`SearchResult<ListingCard>`), which `ListingGrid` and `AreaMap`
take. On a page that reads its URL, spread `fromSearchParams` into the call, or type your query
variable as `Omit<SearchQuery, "view">`. A variable typed as plain `SearchQuery` may hold any
`view`, so its result is the union of all three listing shapes:

```ts
import { createClient, fromSearchParams, type SearchQuery } from "@ruuster/idx";

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

export async function cards(searchParams: Record<string, string | string[] | undefined>) {
  const q: Omit<SearchQuery, "view"> = { ...fromSearchParams(searchParams), limit: 24, pageHref: "/search" };
  const r = await idx.search(q);
  return r.ok ? r.data.listings : [];
}
```

`view` picks the listing shape, and the result type follows it: cards by default, `view: "full"`
for cards plus the detail sections, and `view: "map"` for up to 200 map pins:

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

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const pins = await idx.search({ bbox: { south: 33.7, west: -84.45, north: 33.82, east: -84.3 }, view: "map" });
if (!pins.ok) throw new Error(pins.error.code);
for (const p of pins.data.listings) console.log(p.geo.lat, p.geo.lng, p.price);
```

### One listing, and homes like it

The listing page pattern reads the id from the slug, answers 404 and 410 itself, and redirects an
outdated slug:

<p class="code-title"><code>app/homes/[slug]/page.tsx</code></p>

```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>
  );
}
```

`idx.similar(listingId, { limit: 6 })` answers homes like a listing, best match first. Each item in
`data.listings` is `{ listing, why }`: the card, and a `why` breakdown (distance, price and size gaps,
rooms). Pass the cards to `ListingGrid` with `.map((s) => s.listing)`. For a listing that left the
market in the last 30 days it still answers, with `subjectRemoved: true`, so your 410 page can show
them:

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

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

export async function similarCards(listingId: string) {
  const r = await idx.similar(listingId, { limit: 6 });
  if (!r.ok) return { cards: [], mls: [] };
  return { cards: r.data.listings.map((s) => s.listing), mls: r.meta.mls, removed: r.data.subjectRemoved };
}
```

### Market statistics and outlines

```ts
import { createClient, fmt } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const m = await idx.market({ zip: "30308", months: 12 });
if (!m.ok) throw new Error(m.error.code);
const sold = m.data.measures.medianSoldPrice;
console.log(`Median sold price in ${m.data.location.label}: ${fmt.usd(sold.current)} (${fmt.change(sold, 12) ?? "no change data"} in a year)`);
if (m.data.location.boundary) {
  const outline = await idx.boundary(m.data.location.boundary.id);
  if (outline.ok) console.log(outline.data.geometry.type, outline.data.viewport);
}
```

### Mortgage estimates

`idx.mortgage(query)` answers the monthly payment for a price, line by line, at today's market rates:
principal and interest, property tax, home insurance, mortgage insurance and HOA dues. It works from
your server, or from a page through your listings route, and costs no daily units. Send the home's `state` or `zip`, and the listing's HOA dues and
yearly tax when you have them; `mortgagePrefill(listing)` from `@ruuster/idx-recipes` reads them from
a listing. A tax or insurance line you leave out is estimated, and `monthly.provenance` marks it
`estimated`. Show every line of `requiredDisclosures` with the figures.

```ts
import { createClient, toMortgageQueryString } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const m = await idx.mortgage({ price: 625000, state: "GA", zip: "30308", downPaymentPercent: 20, hoaMonthly: 150 });
if (m.ok) {
  console.log(m.data.monthly.total, m.data.monthly.provenance.propertyTax, m.data.rate.annualPercent);
  if (!m.data.eligible) console.log(m.data.ineligibleReasons.join(" "));
  for (const line of m.data.requiredDisclosures) console.log(line);
}
console.log(toMortgageQueryString({ price: 625000, state: "GA", downPaymentPercent: 20 }));
```

`toMortgageQueryString(query)` gives the query string the client sends, in the API's parameter order
with numbers in their shortest form, so one scenario is always one cached answer. The recipes'
`MortgageCalculator` builds the same string in the browser, and its `initialEstimate` prop takes the
`data` of `idx.mortgage()` for a first answer in your HTML
([Mortgage calculator](https://help.ruuster.com/idx/recipe-mortgage-calculator)).

### Public records

`idx.publicRecords` is the [Public Records add-on](https://help.ruuster.com/idx/guide-public-records).
It runs on your server with your secret key. `lookup` answers exactly one property's county record,
for a CMA or a listing presentation; `history` answers that property's recorded deeds and mortgages;
`market` answers a fixed set of counts and medians for one ZIP code, city or county. There is no
list and no search by owner.

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

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const one = await idx.publicRecords.lookup({ address: "2217 Sample Oak Dr, Atlanta, GA 30308", purpose: "cma" });
if (one.ok) {
  const record = one.data.record;
  console.log(record.parcelNumber, record.livingArea, record.lastSale?.price, one.meta.notice);
  const history = await idx.publicRecords.history(record.recordId, { purpose: "cma" });
  if (history.ok) console.log(history.data.transfers.length, history.data.mortgages.length);
} else if (one.error.code === "ambiguous_address") {
  console.log("Ask for the unit number or the parcel number.");
}
const market = await idx.publicRecords.market({ zip: "30308", type: "single_family" });
if (market.ok) {
  const homes = market.data.measures.homes;
  console.log(homes.value === null ? `Not enough data (${homes.reason})` : homes.value);
}
```

A figure of `market` with fewer than 10 properties behind it is `null` with a `reason`. Show "not
enough data" for it.

### Sitemaps and change feeds

`idx.ids` pages through every listing your key can show; follow `nextCursor` until it is null:

<p class="code-title"><code>lib/listing-ids.ts</code></p>

```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;
}
```

`idx.changes({ since })` on the first call, then `idx.changes({ cursor })` with the `nextCursor` it
returned, tells you what changed. Call again at once while `hasMore` is true. Webhooks (below) push
the same changes to you.

### Everything else

`idx.request(path, query)` reaches the endpoints without a named method, with the same keys, encoding,
retries and results. Type the data with the generated `IdxOpData` map:

```ts
import { createClient, type IdxOpData } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const shapes = await idx.request<IdxOpData["shapes.list"]>("/shapes");
const usage = await idx.request<IdxOpData["usage"]>("/usage", { days: 7 });
if (shapes.ok) console.log(shapes.data.shapes.map((s) => s.name));
if (usage.ok) console.log(usage.data);
```

## Listing Alerts

`idx.alerts` covers every [Listing Alerts endpoint](/idx/reference-alerts). It needs the secret key,
so call it from your server only. Every method answers the same result as the rest of the client,
with `meta: null`.

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

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const place = await idx.suggest({ q: "Travis Heights" });
const where = place.ok && place.data[0] ? [place.data[0].where] : [];
const created = await idx.alerts.buyers.create({
  email: "jamie@example.com",
  consent: { text: "Email me new listings that match this search.", source: "https://www.example-homes.com/search" },
  search: { criteria: { where, bedsMin: "3" }, frequency: "instant" },
});
if (!created.ok) console.error(created.error.code, created.error.message);
```

| Group | Methods |
|---|---|
| `alerts.agents` | `list`, `create`, `get`, `update`, `archive`, `makeDefault` |
| `alerts.buyers` | `list`, `create` (one call, safe to repeat), `get`, `update`, `delete`, `unsubscribe`, `resubscribe` |
| `alerts.searches` | `list`, `create`, `get`, `update`, `delete` |
| `alerts.deliveries` | `list`, `get`, `ack`, `result`, `events` |
| `alerts.settings` | `get`, `update` |
| `alerts.link(token)` | Which buyer and search a link is for |
| `alerts.unsubscribe(token)` | The one-click unsubscribe for a link |
| `alerts.credits()` | This month's email credits |

`where` objects in `criteria` can be passed as the objects `/v1/suggest` returned; the client sends
them as JSON strings. Lists answer `{ items, nextCursor }`.

## Page helpers

### Head tags

`toMetadata(head)` turns a listing's or a results page's `head` into the Next.js `Metadata` object:
title, description, canonical URL, robots, Open Graph and Twitter tags. `idx.toMetadata(head)` does
the same and makes a relative canonical URL absolute with the client's `siteOrigin`. On a framework
other than Next.js, print the `head` fields into your own tags.

### Listing URLs and JSON-LD

- `listingPath(listing, template?)` gives `/homes/{slug}`, or your own template with `{slug}`,
  `{id}` or `{mlsNumber}` filled in. A listing with a hidden address has a slug without a street.
- `parseListingSlug(slugOrPath)` reads the listing id from a slug, a path or a URL and returns
  `{ id, slug }`, or null. Compare `slug` with the listing's current slug to redirect old links.
- `serializeJsonLd(doc)` writes a JSON-LD document for a `<script type="application/ld+json">`
  element with `<`, `>` and `&` escaped, so listing text can never close the script. Answers that
  carry `jsonLdHtml` already hold the whole element; print it as it is.
- `breadcrumbJsonLd([{ name, url }, …])` builds a schema.org BreadcrumbList from your own crumbs.

These give exactly what the API gives: the package's tests run both over the same listings.

### Photos

`photoAttrs(photo, { priority, sizes })` gives the attributes of an `<img>`: `src`, `alt`, `width`
and `height` (so the page does not shift as photos load), `loading`, and for the first photo on a
page `fetchPriority: "high"`. Photos on `photos.ruuster.com` also get a `srcSet` of 480, 800 and 1200
pixel widths.

```tsx
import { photoAttrs, type ListingCard } from "@ruuster/idx";

export function CardPhoto({ listing, first }: { listing: ListingCard; first: boolean }) {
  const photo = listing.photos[0];
  return photo ? <img {...photoAttrs(photo, { priority: first })} /> : null;
}
```

### Formatting

`fmt` formats numbers and dates in US English and answers `""` (or null for `change`) when there is
nothing to show:

| Call | Answer |
|---|---|
| `fmt.usd(849000)` | `$849,000` |
| `fmt.usd(1620000, { compact: true })` | `$1.62M` (for map pins) |
| `fmt.change(series, 12)` | `+4.1%`: the latest month with a value against 12 months earlier |
| `fmt.count(2.5)` | `2.5` |
| `fmt.sqft(1850)` | `1,850 sq ft` |
| `fmt.date("2026-11-04T15:00:00Z")` | `November 4, 2026` (America/Chicago unless you pass a time zone) |
| `fmt.date(listing.closeDate)` | `September 1, 2026` for `2026-09-01T00:00:00Z`: a date-only value, or a time of exactly midnight UTC as the API sends `closeDate`, is that day in every time zone |
| `fmt.openHouse(listing.openHouses[0])` | `Saturday, Nov 7, 1:00 to 3:00 PM CT`, in the listing's own time zone |

### Reading your page's URL

- `fromSearchParams(searchParams)` reads a search from your page's URL in the API's own names
  (`bedsMin`, `priceMax`, `status`, `sort`, `page`, `where`, `f.<key>` …), the names the `Filters`
  and `Pagination` components write. Values the API would refuse are dropped, never thrown, because
  a visitor typed them. Your page sets `view`, `detailHref`, `pageHref` and `indexable` itself; the
  URL never sets them.
- `fromWidgetSearchParams(searchParams, { filterKeys })` reads the Ruuster widget's URL (`address`,
  `bounds`, `status=Active`, `bedroomsMin`, `sortBy`, `rw_page` …), for a page that used to host the
  widget. Name your advanced filter keys from `/filters` in `filterKeys` to read those too.
- `widgetPropertyId(searchParams)` reads an old widget detail link's `propertyId`, so you can
  redirect it to the listing's page.

### Display rules

The recipe components follow each board's display rules for you. When you render the JSON yourself:

- `renderAttribution(listing, r.meta.mls, compliance?)` gives the attribution text the listing must
  show (its own line, else its board's template filled in), or null when its board requires none.
- `assertDisplayable(listing, r.meta.mls, "card" | "detail")` throws a `DisplayRuleError` when a
  listing lacks what its board requires where you show it, such as the listing office on a card. The
  message names what is missing in a full sentence, and `error.missing` lists the elements.

Print each board's disclaimer, logo and "Data last updated" line from `r.meta.mls` on every page (the
`MlsDisclaimers` component does it). See [Compliance](https://help.ruuster.com/idx/compliance).

## Verify webhooks

`verifyWebhook({ body, headers, secret })` checks a listing-change delivery's `Ruuster-Signature`
with Web Crypto: HMAC-SHA256 over the timestamp and the raw body, any of the signatures in the header
may match (two while you rotate the secret), compared in constant time, and the timestamp within five
minutes (`toleranceSec` changes it). It answers `{ ok: true, events, deliveryId }`, with `events` a
list whether the body held one event or a batch, or `{ ok: false, reason }` with `missing_signature`,
`bad_signature`, `stale_timestamp` or `bad_body`. Pass the body as raw text, exactly as received.

<p class="code-title"><code>lib/revalidate.ts</code></p>

```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 });
}
```

`secret` takes one secret or a list, so you can hold the old and the new secret while you rotate it.
See [Webhooks](https://help.ruuster.com/idx/guide-webhooks) for setup and retries.

## Send leads to your CRM

`@ruuster/idx/crm` builds and sends the request each CRM expects, from your own server route with your
own CRM key. Import it only in server code. Every builder takes the form's `LeadSubmission` (exported
from `@ruuster/idx`) and your site's name as `source`, and every sender answers a `CrmSendResult`
instead of throwing for an HTTP error.

| Export | What it does |
|---|---|
| `assertSendable(lead)` | Throws `LeadRejected` before any call: `reason` is `"honeypot"` (the hidden `website` field was filled; answer as if it worked and send nothing), `"contact"` (no valid email and no phone), `"consent"` (the contact box was not checked) or `"invalid"`. `message` is a sentence to show. |
| `fub.eventFromLead(lead, { source, listing?, listingUrl?, tags? })` | The Follow Up Boss event: `Registration`, `Property Inquiry` (a tour, or a question about a listing) or `General Inquiry`. |
| `fub.sendEvent(event, { apiKey, system, systemKey }, { fetch? })` | Sends it to Follow Up Boss. `id` is the person's Follow Up Boss id. |
| `fub.viewedPropertyEvent({ id }, listing, { source, listingUrl })` | A registered visitor's `Viewed Property` event. |
| `sierra.leadFromSubmission(lead, { source, listing?, listingUrl?, tags? })` | The Sierra Interactive lead. It needs an email. |
| `sierra.createLead(lead, { apiKey }, { fetch? })` | Sends it to Sierra Interactive. |
| `suresend.personFromSubmission(lead, { source, listing?, listingUrl?, tags?, stage? })` | The Sure Send person. `stage` is one of your Sure Send stage names, or null. |
| `suresend.createPerson(person, { apiKey }, { fetch? })` | Sends it to Sure Send. |
| `crmProperty(listing, url)` | The listing fields a CRM receives. A hidden address has no street. |
| `nurtureTags(lead, extra?)` | Your tags, plus the AI Nurture tags when the alerts box was checked. The builders call it for you. |
| `assertSiteSource(source)` | Throws when `source` is empty, `Ruuster` or `App`. The builders call it for you. |

`CrmSendResult` is `{ ok: true, status, id }` or `{ ok: false, status, error, retryAfterSec }`. When
the CRM asks you to wait, `retryAfterSec` holds its `Retry-After` seconds. `error` never contains your
key.

Pass the listing from your own Listings API call, and `listingUrl` as your page for it on your own
domain: `SITE_ORIGIN` plus `listingPath(listing)`. Use the URL the form sent only when it is on
`SITE_ORIGIN`.

```ts
import { createClient, listingPath, type LeadSubmission } from "@ruuster/idx";
import { assertSendable, fub, LeadRejected } from "@ruuster/idx/crm";

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

export async function sendToFollowUpBoss(lead: LeadSubmission): Promise<{ status: number; message: string }> {
  try {
    assertSendable(lead);
  } catch (err) {
    if (err instanceof LeadRejected) return { status: err.reason === "honeypot" ? 200 : 422, message: err.message };
    throw err;
  }
  const found = lead.listing ? await idx.get(lead.listing.id) : null;
  const listing = found && found.ok ? found.data : null;
  const listingUrl = listing ? `${process.env.SITE_ORIGIN}${listingPath(listing)}` : null;
  const event = fub.eventFromLead(lead, { source: process.env.SITE_NAME ?? "", listing, listingUrl });
  const sent = await fub.sendEvent(event, {
    apiKey: process.env.FUB_API_KEY ?? "",
    system: process.env.FUB_SYSTEM ?? "",
    systemKey: process.env.FUB_SYSTEM_KEY ?? "",
  });
  if (sent.ok) return { status: 200, message: "Thanks. We got your request and will be in touch soon." };
  return sent.retryAfterSec != null
    ? { status: 429, message: `Please try again in ${sent.retryAfterSec} seconds.` }
    : { status: 502, message: "We couldn't send your request just now. Please try again in a minute." };
}
```

In tests, pass your own `fetch` as the sender's third argument, so nothing reaches a real CRM:

```ts
import { sierra } from "@ruuster/idx/crm";
import type { LeadSubmission } from "@ruuster/idx";

const lead: LeadSubmission = {
  kind: "contact",
  firstName: "Avery",
  lastName: "Lee",
  email: "avery@example.com",
  phone: null,
  message: "Is the home still available?",
  tour: null,
  listing: null,
  consent: { contact: true, alerts: false, text: "I agree that Peach Realty may contact me." },
  page: { url: "https://www.example.com/contact", referrer: null },
  attribution: { utmSource: null, utmMedium: null, utmCampaign: null, utmTerm: null, utmContent: null, gclid: null, fbclid: null },
};

const fakeFetch = (async () => new Response(JSON.stringify({ success: true, data: { leadId: 7 } }), { status: 200 })) as typeof fetch;
const body = sierra.leadFromSubmission(lead, { source: "Peach Realty" });
const result = await sierra.createLead(body, { apiKey: "test-key" }, { fetch: fakeFetch });
console.log(result.ok, body.email);
```

The complete routes for each CRM, with the messages they answer, are in the
[Next.js example](https://help.ruuster.com/idx/recipe-forms) and on
[Your CRM](https://help.ruuster.com/idx/crm-overview).

## Types

Every answer type comes from the API's response schemas, so the SDK names exactly the fields the API
sends: `ListingCard`, `ListingFullRecord`, `ListingPin`, `ListingDetail`, `SearchResult<L>`,
`SuggestRow`, `WhereObject`, `MarketData`, `MarketSeries`, `SimilarResult`, `BoundaryShape`,
`IdsPage`, `ChangesPage`, `MetaData`, `MlsCompliance`, `PageHead`, `ListingEvent` and the rest.
`IdxOpData` maps every endpoint to its data, `IdxOpQuery` to its parameters, and `IdxErrorCode` lists
every error code.
