# Search page with map

Source: 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.

A search page at `/search` on your domain. The URL holds the whole search in the API's own parameter
names (`where`, `bedsMin`, `priceMax`, `page` and the rest), and your server renders the first page
of results from it, so every search has a shareable link and the cards are in the first HTML. The
search box and the map load on top. Searches with filters a visitor picked are marked
`noindex,follow` by the API, so your [area pages](https://help.ruuster.com/idx/recipe-neighborhood-page)
are the pages that rank.

## What the visitor sees

<figure class="idx-shot"><img src="/idx-docs/screens/ours/desktop-list.png" alt="A search results page with the search box, the More filters button, the count with the sort menu and the Grid and Map switch, and listing cards in a grid" width="1440" height="900" loading="lazy" decoding="async"><figcaption>Results on a desktop: the filter bar, the toolbar and the cards.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/filters-drawer-dynamic-1440.png" alt="The More filters drawer built from the account's filter list, on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>&quot;More filters&quot; opens the drawer with every filter your account offers.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/filters-drawer-dynamic-375.png" alt="The More filters drawer built from the account's filter list, on a phone (375 px wide)" width="375" height="812" loading="lazy" decoding="async"><figcaption>&quot;More filters&quot; opens the drawer with every filter your account offers.</figcaption></figure>

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

<figure class="idx-shot"><img src="/idx-docs/screens/ours/desktop-filters-drawer-advanced.png" alt="The More filters drawer scrolled to Advanced filters, open, with a row for each filter and Reset filters and Show results under it" width="1440" height="900" loading="lazy" decoding="async"><figcaption>Further down the drawer: &quot;Advanced filters&quot;, opened.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/mobile-list.png" alt="Listing cards stacked in one column on a phone under a full-width More filters button" width="390" height="844" loading="lazy" decoding="async"><figcaption>The same results on a phone.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/grid-skeleton-1440.png" alt="The result grid while a search loads (eight card placeholders), on a desktop (1440 px wide)" width="1440" height="1264" loading="lazy" decoding="async"><figcaption>While a search runs, `loading.tsx` shows the outlines of the count and the cards.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/grid-skeleton-375.png" alt="The result grid while a search loads (eight card placeholders), on a phone (375 px wide)" width="375" height="2759" loading="lazy" decoding="async"><figcaption>While a search runs, `loading.tsx` shows the outlines of the count and the cards.</figcaption></figure>

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

## What is on the page

- **The filter bar.** From 1741 pixels, Status, Price, Beds and baths, and Home type open as small
  panels with an Apply button. "More filters" opens a drawer from the right with every filter, "Reset
  filters" (which keeps the place) and "Show results". The button shows how many filters are on, such
  as "More filters (2)". Under 520 pixels it fills the width.
- **Every filter your account offers.** The drawer builds itself from `GET /v1/filters`: after
  price, beds, baths, type, status and sort come the filters of your own Ruuster filter panel, in
  its order, then every other filter your MLSs offer under "Advanced filters". Each one gets the
  right control for its type, and a list's choices load when the visitor opens it. You write no
  field names.
- **The results toolbar.** "Showing 37 listings", the "Sort by" menu, which applies as soon as the
  visitor picks an order, and the Grid and Map switch. Each switch is a link to the same search, with
  `view=map` for the map. Without JavaScript, the sort menu has its own button for screen readers
  and keyboards.
- **The grid** of cards, one to four columns by width, with the page links under it.
- **The map view** at `?view=map`: up to 200 price pins across the full width. Pins close together
  group into a circle with the number of homes, and a click zooms in on them. After the visitor pans
  or zooms, "Search this area" reloads the page for the box on screen with `bbox=`. The tools on the
  right draw an area or a circle (sent as `polygon=`), lock the drawn area, and switch to the
  satellite view; "Clear the drawn area" removes it. A school search shows a school pin at the
  school's outline.
- **The loading state.** `app/search/loading.tsx` shows the outline of the count and eight cards.
  The shimmer starts only after 200 milliseconds and holds still for visitors who ask for less motion.

## What the page calls

| When | Request | Key | Cached |
|---|---|---|---|
| Each page view | `GET /v1/listings` with the URL's parameters, `limit=24` and `pageHref=/search` | secret key, on your server | 5 minutes by Next.js (`revalidate`) |
| The map view (`?view=map`) | `GET /v1/listings` with the URL's parameters and `view=map`, up to 200 pins | secret key, on your server | 5 minutes by Next.js |
| When the search is an outlined area and the map is on | `GET /v1/boundaries/{boundaryId}` for the outline | secret key, on your server | 5 minutes by Next.js |
| Each page view | `GET /v1/filters` for the drawer's filter list | secret key, on your server | 5 minutes by Next.js |
| When the visitor opens a list in the drawer | `GET /v1/filters/options` for that filter's choices, through your listings route | secret key, added by your listings route | an hour at Ruuster's edge |
| As the visitor types in the search box | `GET /v1/suggest`, through your listings route | secret key, added by your listings route | an hour at Ruuster's edge |

The results call, as the server sends it for a visitor who searched Midtown with 3 or more beds:

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode 'where={"label":"Atlanta, GA Midtown","value":"a0000000-0000-4000-8000-000000000001","source":"neighborhood","data":{"state":"GA"}}' \
  --data-urlencode bedsMin=3 \
  --data-urlencode limit=24 \
  --data-urlencode pageHref=/search \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

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

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

const r = await idx.search({
  where: {
    label: "Atlanta, GA Midtown",
    value: "a0000000-0000-4000-8000-000000000001",
    source: "neighborhood",
    data: {
      state: "GA",
    },
  },
  bedsMin: 3,
  limit: 24,
  pageHref: "/search",
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/listings",
    params={
        "where": "{\"label\":\"Atlanta, GA Midtown\",\"value\":\"a0000000-0000-4000-8000-000000000001\",\"source\":\"neighborhood\",\"data\":{\"state\":\"GA\"}}",
        "bedsMin": "3",
        "limit": "24",
        "pageHref": "/search",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'where' => '{"label":"Atlanta, GA Midtown","value":"a0000000-0000-4000-8000-000000000001","source":"neighborhood","data":{"state":"GA"}}',
    'bedsMin' => '3',
    'limit' => '24',
    'pageHref' => '/search',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

The answer holds `listings` (each card with its `href` on your site), `total`, `page`, `pages`,
`viewport` and `boundary` for the map, `head` for your page's metadata, `jsonLd`, and `meta.mls` with
every board's disclaimer.

## Steps

1. Add `lib/idx.ts`, `lib/site.ts` and `components/results.tsx` from the
   [recipes overview](https://help.ruuster.com/idx/recipes), and `lib/area-query.ts` and
   `lib/results.ts` from below.
2. In `.env.local`, set `IDX_SECRET_KEY`, `SITE_ORIGIN` and `SITE_NAME`. For the
   map, set `NEXT_PUBLIC_GOOGLE_MAPS_KEY` and `NEXT_PUBLIC_GOOGLE_MAP_ID` (your own Google Maps key,
   restricted to your domains).
3. Add your listings route, `app/api/idx/[...path]/route.ts`, with `createListingsRoute` from
   `@ruuster/idx/route` ([No key in your pages](https://help.ruuster.com/idx/keys-and-domains)), and
   give `SearchBox` and `Filters` `baseUrl="/api/idx"`. The page carries no key, and the route
   works on `localhost` and on staging.
4. Create `app/search/page.tsx`, `app/search/loading.tsx`, `components/map-results.tsx` and
   `lib/search-view.ts` with the code below. Before a visitor picks a place, the page shows
   your popular areas as links (from `content/areas.ts`) and your own listings, so the page is never
   empty and search engines find your area pages from it.
5. Run `npm run dev`, open `http://localhost:3000/search`, type a place in the search box and pick it.
6. Link to `/search` from your header.

## The code

<p class="code-title"><code>app/search/page.tsx</code></p>

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

<p class="code-title"><code>app/search/loading.tsx</code></p>

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

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

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

<p class="code-title"><code>components/map-results.tsx</code></p>

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

<p class="code-title"><code>components/results.tsx</code></p>

```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 ?? []} />
    </>
  );
}
```

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

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

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

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

## Forms and your CRM

The search page carries no forms. Tour and contact forms belong on your
[listing pages](https://help.ruuster.com/idx/recipe-listing-detail), and they send leads to your CRM
through your own route ([Registration, tour and contact forms](https://help.ruuster.com/idx/recipe-forms),
[Your CRM](https://help.ruuster.com/idx/crm-overview)).

## Rules this page follows

**MUST**

- Call `GET /v1/listings` from your server with the secret key.
- Show the attribution line on every card whose board requires one (`ListingGrid` does it) and every
  board's disclaimer with the "Data last updated" line (`MlsDisclaimers`).
- Keep pagination, card links and the Grid and Map switch as plain `<a href>` links.
- Keep the place, the drawn area and the view on every filter change (`SEARCH_KEEP` does it).
- Use the `head` the API returns for the page's metadata, so filtered searches stay `noindex,follow`.
- Throw on a 429 or 503, so Next.js keeps serving the last good page.

**NEVER**

- Put `IDX_SECRET_KEY` in browser code or a URL.
- Build or edit a `where` object by hand: the search box writes the row `/v1/suggest` answered.
- Show a street address or map pin the API left out.

## Test it

```sh
curl -s "http://localhost:3000/search?where=%7B%22label%22%3A%22Atlanta%2C%20GA%20Midtown%22%2C%22value%22%3A%22a0000000-0000-4000-8000-000000000001%22%2C%22source%22%3A%22neighborhood%22%2C%22data%22%3A%7B%22state%22%3A%22GA%22%7D%7D&bedsMin=3" | grep -o 'name="robots" content="[^"]*"'
```

The answer is `name="robots" content="noindex,follow"`, because `bedsMin` is a filter the visitor
picked. Then view source on the page and find the first card's address and a link that starts with
`/homes/`. Turn JavaScript off in your browser and reload: every card is still there. Click "More
filters", pick 3 bedrooms and click "Show results": the URL has `bedsMin=3` and the place you
picked. Click Map: the URL has `view=map` and the pins appear; drag the map and click "Search this
area": the URL has `bbox=`.

## Build it with AI

```text
Read RUUSTER_IDX.md first and follow its MUST and NEVER rules. Ask me if it doesn't cover something.

Build a search page at /search that follows the recipe at <https://help.ruuster.com/idx/recipe-search-page>. Render the first page of results on the server with GET /v1/listings and my secret key, reading the page's own URL parameters (the API's names, through fromSearchParams from @ruuster/idx). Show the Filters, ListingGrid, Pagination, AreaMap and MlsDisclaimers components from @ruuster/idx-recipes, put the SearchBox at the top with baseUrl="/api/idx" (and the same baseUrl on Filters), and set the page's metadata from the head object the API returns (toMetadata). Pagination and card links must be plain <a href> links.

Use these environment variables: IDX_SECRET_KEY (server only), SITE_ORIGIN and SITE_NAME. Never paste a secret key into a chat, and never put IDX_SECRET_KEY in browser code, a URL or a log. No key goes in any page: my pages call my own /api/idx route, made with createListingsRoute from @ruuster/idx/route, which adds my secret key on the server (on a site with no server, the widgets call the API with no key from my approved website address). The map uses NEXT_PUBLIC_GOOGLE_MAPS_KEY and NEXT_PUBLIC_GOOGLE_MAP_ID.

Fair housing: describe homes, places and amenities only. Never describe the people who live in an area or who a home or area suits, and never rank schools as a reason to buy.

When you are done, show me how to check with curl that the first page of cards is in the HTML, and that a search with filters I picked has a noindex,follow robots tag.
```

On a site without React, such as PHP, Python, Ruby on Rails, Go or plain HTML, [Build without React: HTML, CSS and JavaScript](https://help.ruuster.com/idx/recipe-html-css) gives you the same markup, the stylesheet and the script for every widget.
