# Listing detail page

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

One permanent page per listing on your domain, such as
`/homes/123-peachtree-st-ne-atlanta-ga-30308-aaaaaaaa-0000-4000-8000-000000000001`. The whole listing
is in the HTML your server sends: the photos, price and facts, the description, the details, open
houses, the MLS attribution, the head tags and the JSON-LD. Around it, `ListingDetail` builds every
screen of the listing page: a header that follows the visitor down the page, the full-screen gallery,
the mortgage calculator, the location map, your contact and tour cards, and the share, contact and
tour screens. When the address in the URL is out of date the page answers a 301 to the current one,
and when the listing leaves the market it answers 410 Gone with similar homes. This is the one page
type that carries a call to action.

## What the visitor sees

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-detail-1440.png" alt="Listing page with every screen: the header, the photo grid, the price block, the description, agent information, open houses, the property details, the mortgage calculator, the location map, the contact and tour cards, the mobile bar, and the closed full gallery, share, contact and tour dialogs, on a desktop (1440 px wide)" width="1440" height="3125" loading="lazy" decoding="async"><figcaption>The listing page: photo grid, price block, description, details, open houses and the sidebar cards.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-detail-375.png" alt="Listing page with every screen: the header, the photo grid, the price block, the description, agent information, open houses, the property details, the mortgage calculator, the location map, the contact and tour cards, the mobile bar, and the closed full gallery, share, contact and tour dialogs, on a phone (375 px wide)" width="375" height="4044" loading="lazy" decoding="async"><figcaption>The listing page: photo grid, price block, description, details, open houses and the sidebar cards.</figcaption></figure>

The markup is `static/html/listing-detail.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/detail-header-pinned-1440.png" alt="The header once the price block has scrolled behind it: data-rw-pinned is set, so the summary and X show in place of Back, on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>Once the price block scrolls away, the header shows the price, the address and the facts.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/detail-header-pinned-375.png" alt="The header once the price block has scrolled behind it: data-rw-pinned is set, so the summary and X show in place of Back, on a phone (375 px wide)" width="375" height="812" loading="lazy" decoding="async"><figcaption>Once the price block scrolls away, the header shows the price, the address and the facts.</figcaption></figure>

The markup is `static/html/detail-header-pinned.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/detail-skeleton-1440.png" alt="The listing page while it loads, on a desktop (1440 px wide)" width="1440" height="982" loading="lazy" decoding="async"><figcaption>While the listing loads, `loading.tsx` shows the page's outline.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/detail-skeleton-375.png" alt="The listing page while it loads, on a phone (375 px wide)" width="375" height="978" loading="lazy" decoding="async"><figcaption>While the listing loads, `loading.tsx` shows the page's outline.</figcaption></figure>

The markup is `static/html/detail-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.

## Every screen on the page

The page is one `ListingDetail`. From top to bottom it renders:

1. **The header.** A "Back" link to `backHref` (your search page). Once the price block scrolls
   behind it, the header shows the price, the address, beds, baths and square feet, and an X that
   goes back too.
2. **The photo grid.** One photo on phones; from 768 pixels the first photo large beside up to four
   more. A round share button on the first photo, "Street view" bottom left, "N photos" bottom
   right, and the board's logo where its rule asks for it. Any photo opens the
   [full gallery](https://help.ruuster.com/idx/recipe-gallery).
3. **The board's courtesy line**, above the price block when the board's rule places it there.
4. **The price block.** The status with its colored dot, the price, beds, baths and square feet, and
   the address as the page's `h1` (the city, state and ZIP code when the address is hidden).
5. **The description**, five lines with "Show more" when it runs longer, the virtual tour link, and
   the board's office or agent line when its rule places it here.
6. **Agent information.** Your agent's name and photo, the brokerage, the license number, and round
   email and phone buttons.
7. **Open houses** in the next 30 days, in the listing's time zone: "Today", "Tomorrow" or the date,
   "1:00 PM to 3:00 PM", and "Happening now" while one is on. Three show, then "Show all open
   houses". Under them, "Schedule a tour" opens the tour screen.
8. **Property details** in sections with icons. The first section is open; each shows its facts as a
   list in two columns from 768 pixels.
9. **The [mortgage calculator](https://help.ruuster.com/idx/recipe-mortgage-calculator).**
10. **The location map** with the price over a pin, a "Street view" and "Map view" switch, and a
    button that fills the screen.
11. **The MLS block**: the attribution line, the MLS number and the board's disclaimer. It always
    renders.

Beside the main column from 992 pixels, the sidebar holds your agent card ("Questions about this
home?" and "Contact Jordan Lee") and the tour card ("Schedule a tour" and "Choose tour time"), and
stays in view as the visitor scrolls. Under 992 pixels the same two buttons sit in a bar fixed to the
bottom of the screen.

The four screens that open over the page are mounted once at its end:

| Screen | Opens from | Page |
|---|---|---|
| Full gallery | Any photo, "N photos", "Street view" | [Photo gallery](https://help.ruuster.com/idx/recipe-gallery) |
| Share | The share button on the first photo and in the gallery | [Share a listing](https://help.ruuster.com/idx/recipe-share) |
| Contact | "Contact Jordan Lee" in the agent card and the action bar | [Contact the agent](https://help.ruuster.com/idx/recipe-contact-agent) |
| Tour | "Choose tour time", "Schedule a tour" | [Book a tour](https://help.ruuster.com/idx/recipe-tour-booking) |

Each opening button carries `data-rw-open="gallery"`, `"share"`, `"contact"` or `"tour"`, and each
screen listens inside the page's root element, which carries `data-rw-detail`. Your own buttons work
the same way.

## The props, and what each one turns on

| Prop | Type | Without it |
|---|---|---|
| `listing` | `ListingDetail` (required) | `data` from `GET /v1/listings/{listingId}` |
| `mls` | `MlsCompliance[]` | Always pass `meta.mls` from the same answer: the board's logo, its disclaimer and its placement rules come from it |
| `backHref` | `string \| null` | The header has no Back link and no X |
| `agent` | `DetailAgent \| null` | The cards and buttons read "Contact an agent", and Agent information is left out |
| `leadAction` | `string \| null` | With `consentText`: the agent and tour cards, the action bar, "Schedule a tour" and the contact and tour screens. Without both, none of them |
| `consentText` | `ReactNode` | As `leadAction` |
| `alertsConsentText` | `ReactNode` | The contact and tour screens have no listing-alerts box |
| `shareUrl` | `string \| null` | The share link is `head.canonical`, else `href`. `null` leaves sharing out |
| `googleMapsKey` | `string \| null` | No location map, no "Street view" pill and no Street view tab |
| `mapId` | `string \| null` | The location map draws its pin without a Map ID |
| `apiBaseUrl` | `string` | No mortgage calculator. Set it to your listings route, such as `/api/idx`, to show it |
| `mortgage` | `boolean` | Default `true` when `apiBaseUrl` is set. `true` with no `apiBaseUrl` asks `https://idx.ruuster.com/v1` with no key, from an approved address. `false` leaves the calculator off |
| `aside` | `ReactNode` | Your own sidebar in place of the agent and tour cards (the action bar is left off then) |
| `ga4` | `boolean` | Default `true`: GA4 `view_item` once. `false` sends nothing |

`agent` is your own agent or office, never the MLS listing agent: `{ name, photoUrl, phone, email,
brokerage, license }`, every field optional. Agent information shows when `agent` has a license
number, or when the board's rule asks for agent contact details on the listing page.

## While it loads, and when it is gone

| Case | Status | What the page shows |
|---|---|---|
| Loading | streamed first | `app/homes/[slug]/loading.tsx` renders `ListingDetailSkeleton`: the photo grid, the price block, two text blocks and the sidebar card in light grey. The shimmer starts only after 200 milliseconds, so a fast answer never flashes it, and it holds still for visitors who ask for less motion |
| Not found | 404 | `app/homes/[slug]/not-found.tsx` renders `ListingUnavailable`: "This home is not available right now. Please go back to the search to see other homes." and a Back link |
| Left the market | 410 | `components/gone.tsx`: similar homes and links to your area pages |

## What the page calls

| When | Request | Key | Cached |
|---|---|---|---|
| Each page view (the middleware) | `GET /v1/listings/{listingId}` for the status and current slug | secret key, on your server | remembered 60 seconds per server |
| Each page view (the page) | `GET /v1/listings/{listingId}` | secret key, on your server | 5 minutes by Next.js |
| The mortgage calculator, in the browser | `GET /v1/mortgage/estimate`, through your listings route | secret key, added by your listings route | 5 minutes at Ruuster's edge |
| A removed listing | `GET /v1/listings/{listingId}/similar` | secret key, on your server | 5 minutes by Next.js |
| Your listing sitemap, once an hour | `GET /v1/listings/ids`, 1,000 per page | secret key, on your server | an hour by Next.js |

cURL:

```bash
curl -s "https://idx.ruuster.com/v1/listings/aaaaaaaa-0000-4000-8000-000000000001" \
  -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.get("aaaaaaaa-0000-4000-8000-000000000001");
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/aaaaaaaa-0000-4000-8000-000000000001",
    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

$ch = curl_init('https://idx.ruuster.com/v1/listings/aaaaaaaa-0000-4000-8000-000000000001');
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 is the listing itself: every card field plus `description`, `details`, `openHouses`,
`compliance` (the attribution and courtesy lines), `head` (title, description, canonical URL on your
site, robots, Open Graph and Twitter), `jsonLd` and `jsonLdHtml`. A hidden address answers no street,
no coordinates and an id-only `slug` everywhere.

| The API answers | Your page does |
|---|---|
| 200, and the slug in the URL matches `slug` | Renders the listing |
| 200, and the slug in the URL is out of date | 301 to the listing's current path |
| 410 `listing_removed` | HTTP 410 with `noindex`, "This home is no longer available", similar homes and links to your area pages |
| 404 | HTTP 404 with `ListingUnavailable` |

Similar homes for a listing that left the market (the API answers them for 30 days after it left):

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings/aaaaaaaa-0000-4000-8000-000000000001/similar" \
  --data-urlencode limit=6 \
  -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.similar("aaaaaaaa-0000-4000-8000-000000000001", {
  limit: 6,
});
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/aaaaaaaa-0000-4000-8000-000000000001/similar",
    params={
        "limit": "6",
    },
    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([
    'limit' => '6',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings/aaaaaaaa-0000-4000-8000-000000000001/similar' . '?' . $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']);
```

Every listing for your sitemap:

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings/ids" \
  --data-urlencode limit=1000 \
  -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.ids({
  limit: 1000,
});
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/ids",
    params={
        "limit": "1000",
    },
    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([
    'limit' => '1000',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings/ids' . '?' . $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']);
```

## Steps

1. Add `lib/idx.ts` and `lib/site.ts` from the [recipes overview](https://help.ruuster.com/idx/recipes).
   In `lib/site.ts`, `SEARCH_PATH` is your search page and `SITE_AGENT` is the agent or office your
   listing pages offer.
2. In `.env.local`, set `SITE_AGENT_NAME`, `SITE_AGENT_PHOTO_URL`, `SITE_AGENT_PHONE`,
   `SITE_AGENT_EMAIL` and `SITE_AGENT_LICENSE`, and your own `NEXT_PUBLIC_GOOGLE_MAPS_KEY` and
   `NEXT_PUBLIC_GOOGLE_MAP_ID` ([Get your Google Maps key](https://help.ruuster.com/idx/google-maps-key)).
   Add your listings route (`app/api/idx/[...path]/route.ts` with `createListingsRoute` from
   `@ruuster/idx/route`) and pass `apiBaseUrl="/api/idx"` to `ListingDetail` to turn on the
   mortgage calculator. The page carries no key.
3. In Ruuster, set your detail-page template to `https://www.example.com/homes/{slug}` with your own
   domain, so every `href`, canonical URL and JSON-LD URL the API answers points at this page.
4. Create `app/homes/[slug]/page.tsx`, `loading.tsx` and `not-found.tsx`, `middleware.ts` and
   `components/gone.tsx` with the code below. The middleware is what lets the page answer real 301
   and 410 status codes.
5. Create `lib/listing-ids.ts`, `app/homes/sitemap.ts`, `app/sitemap.ts` and `app/robots.ts`, then
   submit `https://www.example.com/sitemap.xml` and each `/homes/sitemap/0.xml` file in Google
   Search Console and Bing Webmaster Tools.
6. Wire `LEADS_ACTION` to your CRM ([Your CRM](https://help.ruuster.com/idx/crm-overview)).
7. Run `npm run dev` and open a listing from any results page.

## The code

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

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

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

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

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

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

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

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

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

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

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

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

<p class="code-title"><code>app/homes/sitemap.ts</code></p>

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

<p class="code-title"><code>app/robots.ts</code></p>

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

### How the middleware works

The page alone can answer 200 and 404. The 301 and the 410 come from `middleware.ts`, which runs
before the page:

1. **Match every path under `/homes/`.** Use `matcher: ["/homes/:path*"]` and check inside the
   function that the path has one segment, so `/homes/sitemap/0.xml` passes through. Never write
   `matcher: "/homes/:slug"`: Next.js 14 compiles a matcher that ends in one named segment so that it
   matches `/homes` alone, and the middleware never runs on a listing.
2. **Give the middleware its own client.** Middleware runs in the edge runtime and can't import
   `lib/idx.ts`, which imports `server-only`. Create a second client in `middleware.ts` with
   `createClient` from `@ruuster/idx`, the same `IDX_SECRET_KEY`, `IDX_BASE_URL` and `detailHref`.
3. **Ask the API about the listing.** Read the id with `parseListingSlug`, then call `idx.get(id)`.
   Keep each answer in a `Map` for 60 seconds, so a burst of visits costs one call. On 429, 503 or a
   network error, let the page render: it throws, and Next.js keeps serving the last good page.
4. **Answer 301 for an outdated slug.** Build the new path from the API's answer, not from the URL:
   `listingPath({ id, slug: r.data.slug, mlsNumber: r.data.mlsNumber }, DETAIL_HREF)`. `listingPath`
   needs the id, the slug and the MLS number, because your template may use any of them.
5. **Answer 410 for a removed listing.** Return
   `NextResponse.rewrite(req.nextUrl, { status: 410, headers: { "X-Robots-Tag": "noindex" } })`. The
   listing page then renders under that status, sees the API's 410 itself and shows the `Gone`
   component with similar homes.

Next.js adds its own `<meta name="robots" content="noindex">` to a page answered with a status above
400, so the 410 page has that tag beside its own `noindex,follow`. Both say `noindex`.

The same page over plain HTTP, with no packages, in Node.js:

<p class="code-title"><code>server.mjs</code></p>

```js
// A dependency-free Node.js server (Node 18.17 or later) that renders area pages and listing pages from
// the Ruuster Listings API over plain HTTP. Port the same calls to PHP, Python, Ruby or Go: the API
// answers JSON, and this file shows every field a page needs.
//
//   IDX_SECRET_KEY=idx_sk_... SITE_ORIGIN=http://localhost:3000 SITE_NAME="Your Brokerage" node server.mjs
//
// Pages: /neighborhoods/<area>[?page=N&sort=…&priceMin=…] and /homes/<slug>. The server answers 301
// for an outdated listing slug, 410 for a listing that left the market and 404 for an unknown one.
// The pages print the recipe components' markup (templates.mjs), styled by /ruuster-idx.css and made
// interactive by /ruuster-idx.js, which this server sends from the @ruuster/idx-recipes static
// folder: the area page has the results toolbar and the More filters drawer; the listing page has
// every screen (header, photo grid and full gallery, share, contact and tour dialogs, open houses,
// location map and the mortgage calculator, whose first answer this server asks for).
// No key is ever in a page: the calculator asks this server's own route, GET /api/idx/..., which adds
// the secret key here and forwards only the few calls a page's widgets make (see pageRoute below).
// Lead routes (leads.mjs): POST /api/leads/fub, /api/leads/sierra and /api/leads/suresend for the
// registration, tour and contact forms, and POST /api/activity/fub for listing views.
import fs from "node:fs";
import http from "node:http";
import { pathToFileURL } from "node:url";
import { handleFubActivity, handleLead } from "./leads.mjs";
import { detail, disclaimers, esc, filtersDrawer, grid, mortgagePrefill, mortgageQueryString, mortgageStart, page, pagination, resultsToolbar } from "./templates.mjs";

// IDX_BASE_URL is optional; leave it unset to call the Ruuster Listings API itself.
const API_ORIGIN = "https://idx.ruuster.com";
const API = (process.env.IDX_BASE_URL || `${API_ORIGIN}/v1`).replace(/\/+$/, "");
const SITE_NAME = process.env.SITE_NAME || "Your Brokerage";
const PAGE_SIZE = 24;
// The lead route the tour form posts to (leads.mjs): fub, sierra or suresend.
const LEAD_CRM = ["fub", "sierra", "suresend"].includes(process.env.LEAD_CRM) ? process.env.LEAD_CRM : "fub";
const CONSENT_TEXT = `I agree that ${SITE_NAME} may contact me by phone, text or email about this request.`;
const ALERTS_TEXT = "Email me new listings like this one. I can unsubscribe at any time.";
// Optional: your Google Maps browser key turns on the location map and Street view, and your agent the
// contact surfaces. The mortgage calculator needs no key: it asks /api/idx on this server.
const MAPS_KEY = process.env.GOOGLE_MAPS_KEY || null;
const MAP_ID = process.env.GOOGLE_MAP_ID || null;
const AGENT = { name: process.env.AGENT_NAME || null, brokerage: SITE_NAME, license: process.env.AGENT_LICENSE || null, email: process.env.AGENT_EMAIL || null, phone: process.env.AGENT_PHONE || null, photoUrl: process.env.AGENT_PHOTO_URL || null };

// ruuster-idx.css and ruuster-idx.js: from a static/ folder next to this file when you copied them
// there, else from packages/ruuster-idx-recipes/static/ in this repository.
const STATIC_DIRS = [new URL("./static/", import.meta.url), new URL("../../packages/ruuster-idx-recipes/static/", import.meta.url)];
const STATIC_FILES = { "/ruuster-idx.css": "text/css; charset=utf-8", "/ruuster-idx.js": "text/javascript; charset=utf-8" };

// Your areas: each `where` is the row GET /v1/suggest answered, pasted in unchanged.
// This example row is replaced with your own.
export const AREAS = {
  midtown: { name: "Midtown", where: { label: "Atlanta, GA Midtown", value: "a0000000-0000-4000-8000-000000000001", source: "neighborhood", data: { state: "GA" } } },
};

const LISTING_ID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;

/** GET an API path with the secret key, server side. Answers { status, body, retryAfter }. */
export async function api(path, params) {
  const url = new URL(`${API}${path}`);
  for (const [k, v] of Object.entries(params ?? {})) {
    if (v === undefined || v === null) continue;
    for (const one of Array.isArray(v) ? v : [v]) url.searchParams.append(k, typeof one === "object" ? JSON.stringify(one) : String(one));
  }
  const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.IDX_SECRET_KEY}` } });
  const body = await res.json().catch(() => null);
  return { status: res.status, body, retryAfter: res.headers.get("retry-after") };
}

/**
 * Your brand kit (GET /v1/meta data.themeVars), read again every 10 minutes. When the call fails, the
 * page keeps the last brand variables it had (none before the first answer) and asks again a minute later.
 */
let brand = { vars: null, at: 0, ttl: 0 };
export async function themeVars() {
  if (brand.at && Date.now() - brand.at < brand.ttl) return brand.vars;
  try {
    const r = await api("/meta", {});
    brand = r.status === 200 ? { vars: r.body?.data?.themeVars ?? null, at: Date.now(), ttl: 600_000 } : { vars: brand.vars, at: Date.now(), ttl: 60_000 };
  } catch {
    brand = { vars: brand.vars, at: Date.now(), ttl: 60_000 };
  }
  return brand.vars;
}

/** GET /ruuster-idx.css and /ruuster-idx.js. */
function sendStatic(res, pathname) {
  for (const dir of STATIC_DIRS) {
    const file = new URL(pathname.slice(1), dir);
    if (!fs.existsSync(file)) continue;
    res.writeHead(200, { "Content-Type": STATIC_FILES[pathname], "Cache-Control": "public, max-age=3600" });
    return res.end(fs.readFileSync(file));
  }
  send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
}

function send(res, status, html, headers = {}) {
  res.writeHead(status, { "Content-Type": "text/html; charset=utf-8", ...headers });
  res.end(html);
}

/** 429 and 503: tell the visitor to try again; a cache in front of this server keeps the last good page. */
function busy(res, r) {
  send(res, 503, page({ siteName: SITE_NAME, fallbackTitle: "Please try again", body: "<main><h1>Please try again in a moment</h1></main>" }), { "Retry-After": r.retryAfter ?? "5" });
}

// The search parameters the area page passes on to GET /v1/listings (the toolbar's sort and the drawer's filters).
const SEARCH_PARAMS = ["sort", "priceMin", "priceMax", "bedsMin", "bathsMin", "subtype", "type", "status"];
const REPEATABLE = new Set(["subtype", "type", "status"]);

/** The page's own filters from its query: one value each, a list for the repeatable ones, numbers checked. */
export function searchQuery(searchParams) {
  const out = {};
  for (const k of SEARCH_PARAMS) {
    const all = searchParams.getAll(k).filter((v) => v !== "");
    if (all.length) out[k] = REPEATABLE.has(k) ? all : all[0];
  }
  for (const k of ["priceMin", "priceMax", "bedsMin", "bathsMin"]) if (out[k] !== undefined && !/^\d+(\.\d+)?$/.test(out[k])) delete out[k];
  return out;
}

async function areaPage(res, slug, pageNo, searchParams = new URLSearchParams()) {
  const area = AREAS[slug];
  if (!area) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  const q = searchQuery(searchParams);
  const r = await api("/listings", { where: area.where, status: "active", ...q, limit: PAGE_SIZE, page: pageNo, detailHref: "/homes/{slug}", pageHref: `/neighborhoods/${slug}` });
  if (r.status === 429 || r.status >= 500) return busy(res, r);
  if (r.status !== 200) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  const { data, meta } = r.body;
  const mls = meta?.mls ?? [];
  const pages = data.pages ?? Math.min(Math.ceil(data.total / data.limit), Math.floor(2000 / data.limit));
  const path = `/neighborhoods/${slug}`;
  const body = `<main>
    <h1>Homes for sale in ${esc(area.name)}</h1>
    ${filtersDrawer({ action: path, value: q })}
    ${resultsToolbar({ total: data.total, view: "list", basePath: path, searchParams: q })}
    ${grid(data.listings, mls, `Homes in ${area.name}`)}
    ${pagination(path, data.page, pages, q)}
    ${disclaimers(mls, meta?.freshness?.asOf)}
  </main>`;
  send(res, 200, page({ siteName: SITE_NAME, head: data.head, fallbackTitle: `Homes for sale in ${area.name}`, jsonLdHtml: data.jsonLdHtml ?? "", themeVars: await themeVars(), body }));
}

async function listingPage(res, slug) {
  const id = LISTING_ID.exec(slug)?.[1];
  if (!id) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  const r = await api(`/listings/${id}`, { detailHref: "/homes/{slug}" });
  if (r.status === 410) {
    // The listing left the market: 410 Gone with noindex, and similar homes to look at instead.
    const s = await api(`/listings/${id}/similar`, { limit: 6, detailHref: "/homes/{slug}" });
    const cards = s.status === 200 && s.body.data.listings.length ? grid(s.body.data.listings.map((x) => x.listing), s.body.meta?.mls ?? [], "Similar homes") : "";
    const body = `<main>
    <h1>This home is no longer available</h1>
    <p>The listing has left the market.${cards ? " Here are similar homes for sale." : ""}</p>
    ${cards}
    ${s.status === 200 ? disclaimers(s.body.meta?.mls ?? [], s.body.meta?.freshness?.asOf) : ""}
    <p><a href="/neighborhoods/midtown">Homes for sale in Midtown</a></p>
  </main>`;
    return send(res, 410, page({ siteName: SITE_NAME, head: { title: "This home is no longer available", description: "This listing has left the market.", robots: "noindex,follow", canonical: null }, fallbackTitle: "", themeVars: await themeVars(), body }), { "X-Robots-Tag": "noindex" });
  }
  if (r.status === 404) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  if (r.status !== 200) return busy(res, r);
  const listing = r.body.data;
  // The address in the URL is out of date: move permanently to the current one.
  if (listing.slug !== slug) {
    res.writeHead(301, { Location: `/homes/${listing.slug}` });
    return res.end();
  }
  const mls = r.body.meta?.mls ?? [];
  // The mortgage calculator's first answer, asked here with the secret key for the page's own starting
  // query; the browser asks /api/idx on this server again as the visitor changes it. Null on any
  // failure: the calculator then prints empty and the browser fills it.
  const estimate = await mortgageEstimate(listing);
  // The contact and tour dialogs post the LeadSubmission JSON to your lead route; ruuster-idx.js sends it.
  const html = detail(listing, mls, {
    backHref: `/neighborhoods/${Object.keys(AREAS)[0]}`,
    agent: AGENT,
    leadAction: `/api/leads/${LEAD_CRM}`,
    consentText: CONSENT_TEXT,
    alertsConsentText: ALERTS_TEXT,
    shareUrl: listing.head?.canonical || `${(process.env.SITE_ORIGIN || "").replace(/\/+$/, "")}/homes/${listing.slug}`,
    googleMapsKey: MAPS_KEY,
    mapId: MAP_ID,
    // The calculator's requests go to this server's own route, never to the API with a key in the page.
    apiBaseUrl: PAGE_ROUTE,
    estimate,
  });
  // The listing page prints its own board's disclaimer. When meta.mls has no entry for that board, it prints every board's.
  const hasBoard = mls.some((m) => m.mlsId === listing.mls.id);
  const body = `<main>
    ${html}
    ${hasBoard ? "" : disclaimers(mls, null)}
  </main>`;
  send(res, 200, page({ siteName: SITE_NAME, head: listing.head, fallbackTitle: listing.address.display, jsonLdHtml: listing.jsonLdHtml ?? "", themeVars: await themeVars(), body }));
}

/** GET /v1/mortgage/estimate for the listing's starting query (price, 20% down, state, ZIP, HOA dues, tax), or null. */
export async function mortgageEstimate(listing) {
  const prefill = mortgagePrefill(listing);
  if (!prefill.price || !prefill.state) return null;
  try {
    const r = await api("/mortgage/estimate", Object.fromEntries(new URLSearchParams(mortgageQueryString(mortgageStart(prefill)))));
    return r.status === 200 && r.body?.ok ? r.body.data : null;
  } catch {
    return null;
  }
}

// #region pageRoute
/** Where the widgets on these pages send their requests: this server's own route. */
const PAGE_ROUTE = "/api/idx";
/** The only API paths a page's widgets ask for here: suggestions, the filter lists and the mortgage estimate. */
const PAGE_PATHS = new Set(["/suggest", "/filters", "/filters/options", "/mortgage/estimate"]);

/**
 * GET /api/idx/<path>: the browser's calls, forwarded to the API with the secret key added here, so the
 * page carries no key. Anything outside PAGE_PATHS answers 404, so secret-only data stays out. In a
 * project that can install packages, `createListingsRoute` from `@ruuster/idx/route` does the same
 * with a per-visitor limit and every page-safe path.
 */
async function pageRoute(req, res, url) {
  if (req.method !== "GET") return sendJson(res, { status: 405, body: { ok: false, error: { code: "method_not_allowed", message: "This route answers GET requests only." } }, headers: { Allow: "GET" } });
  const path = url.pathname.slice(PAGE_ROUTE.length);
  if (!PAGE_PATHS.has(path)) return sendJson(res, { status: 404, body: { ok: false, error: { code: "not_found", message: "No such resource." } } });
  const query = new URLSearchParams(url.searchParams);
  query.delete("key");
  const upstream = await fetch(`${API}${path}?${query}`, { headers: { Authorization: `Bearer ${process.env.IDX_SECRET_KEY}`, Accept: "application/json" } });
  const headers = { "Content-Type": upstream.headers.get("content-type") ?? "application/json", "Cache-Control": upstream.ok ? "public, max-age=60" : "no-store" };
  const retryAfter = upstream.headers.get("retry-after");
  if (retryAfter) headers["Retry-After"] = retryAfter;
  res.writeHead(upstream.status, headers);
  res.end(Buffer.from(await upstream.arrayBuffer()));
}
// #endregion pageRoute

// #region leadRoutes
/** Reads a JSON request body of at most 64 KB. Null when it is too big or isn't JSON. */
async function readJson(req) {
  let size = 0;
  const chunks = [];
  for await (const chunk of req) {
    size += chunk.length;
    if (size > 65_536) return null;
    chunks.push(chunk);
  }
  try {
    return JSON.parse(Buffer.concat(chunks).toString("utf8"));
  } catch {
    return null;
  }
}

/** The listing a form or a view was about, from the API (null when it is gone or the call failed). */
async function getListing(listingId) {
  const r = await api(`/listings/${encodeURIComponent(listingId)}`, {});
  return r.status === 200 ? r.body.data : null;
}

function sendJson(res, out) {
  res.writeHead(out.status, { "Content-Type": "application/json", "Cache-Control": "no-store", ...out.headers });
  res.end(JSON.stringify(out.body));
}

/** POST /api/leads/<crm> and POST /api/activity/fub. Your CRM keys are read from this server's environment. */
async function leadRoute(req, res, pathname) {
  const deps = { env: process.env, getListing };
  const lead = /^\/api\/leads\/(fub|sierra|suresend)$/.exec(pathname);
  if (lead) return sendJson(res, await handleLead({ origin: req.headers.origin, body: await readJson(req) }, lead[1], deps));
  return sendJson(res, await handleFubActivity({ origin: req.headers.origin, cookie: req.headers.cookie, body: await readJson(req) }, deps));
}
// #endregion leadRoutes

/** The request handler (exported so a test can serve it on any port). */
export async function handle(req, res) {
  try {
    const url = new URL(req.url ?? "/", "http://localhost");
    if (STATIC_FILES[url.pathname]) return sendStatic(res, url.pathname);
    if (url.pathname.startsWith(`${PAGE_ROUTE}/`)) return await pageRoute(req, res, url);
    if (/^\/api\/(leads\/(fub|sierra|suresend)|activity\/fub)$/.test(url.pathname)) {
      if (req.method !== "POST") return sendJson(res, { status: 405, body: { ok: false, error: "Send this form with POST." }, headers: { Allow: "POST" } });
      return await leadRoute(req, res, url.pathname);
    }
    const area = /^\/neighborhoods\/([a-z0-9-]+)\/?$/.exec(url.pathname);
    if (area) {
      const n = Number(url.searchParams.get("page") ?? "1");
      return await areaPage(res, area[1], Number.isInteger(n) && n > 0 ? n : 1, url.searchParams);
    }
    const home = /^\/homes\/([^/]+)$/.exec(url.pathname);
    if (home) return await listingPage(res, decodeURIComponent(home[1]));
    if (url.pathname === "/") {
      const links = Object.entries(AREAS).map(([slug, a]) => `<li><a href="/neighborhoods/${esc(slug)}">Homes for sale in ${esc(a.name)}</a></li>`).join("");
      return send(res, 200, page({ siteName: SITE_NAME, fallbackTitle: SITE_NAME, body: `<main><h1>${esc(SITE_NAME)}</h1><ul>${links}</ul></main>` }));
    }
    send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  } catch {
    send(res, 503, page({ siteName: SITE_NAME, fallbackTitle: "Please try again", body: "<main><h1>Please try again in a moment</h1></main>" }), { "Retry-After": "5" });
  }
}

if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
  if (!process.env.IDX_SECRET_KEY) {
    console.error("Set IDX_SECRET_KEY (your idx_sk_ key) in this server's environment.");
    process.exit(1);
  }
  const port = Number(process.env.PORT || 3000);
  http.createServer(handle).listen(port, () => console.log(`Listening on http://localhost:${port}`));
}
```

## Forms and your CRM

The contact and tour screens post the visitor's request to your own route, `LEADS_ACTION` in
`lib/site.ts`, which sends it to Follow Up Boss, Sierra Interactive or Sure Send with the listing
attached. Both consent boxes start unchecked, and the request carries the exact wording the visitor
saw. [Contact the agent](https://help.ruuster.com/idx/recipe-contact-agent) and
[Book a tour](https://help.ruuster.com/idx/recipe-tour-booking) show what your route receives; see
also [Registration, tour and contact forms](https://help.ruuster.com/idx/recipe-forms) and
[Your CRM](https://help.ruuster.com/idx/crm-overview).

## Rules this page follows

**MUST**

- Show the attribution block (`ListingDetail` always renders it) and the board's disclaimer.
- Answer 410 with `noindex` for a removed listing and drop it from your sitemap (the next sitemap
  build leaves it out on its own).
- Answer 301 for an outdated slug, so links and shares keep working.
- Print JSON-LD with the `JsonLd` component or `jsonLdHtml`, never with `JSON.stringify` inside a
  script element.
- Put your own agent or office in `agent`, and your own wording in `consentText`.
- Share your own listing URL.

**NEVER**

- Show a street, map pin, Street view or coordinates for a listing whose address is hidden.
- Send a lead to a CRM from the browser. The screens post to your server route.
- Keep a removed listing's page live.
- Put the MLS listing agent in `agent` unless that agent works with you.

## Test it

```sh
curl -sI http://localhost:3000/homes/aaaaaaaa-0000-4000-8000-0000000000c1 | head -1
curl -s http://localhost:3000/homes/aaaaaaaa-0000-4000-8000-0000000000c1 | grep -o 'href="[^"]*/homes/[^"]*"' | sort -u | wc -l
curl -sI http://localhost:3000/homes/old-address-aaaaaaaa-0000-4000-8000-000000000001 | grep -i "^location"
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/homes/aaaaaaaa-0000-4000-8000-0000000000ff
```

Use listing ids from your own site: a listing that left the market in the last 30 days, a live one
with an old address in its URL, and an id that is no listing. The first line answers
`HTTP/1.1 410 Gone`, the second counts the similar homes on the 410 page, the third shows the 301's
`location` with the current slug, and the last prints `404`. A listing that left the market more than
30 days ago still answers 410, with links to your area pages in place of similar homes.

Then, on a live listing:

- View source and find the address, the price, the attribution line and the
  `<script type="application/ld+json">` block. Paste the URL into Google's Rich Results Test.
- Scroll down: the header shows the price and the address. Click a photo: the gallery opens at that
  photo, and Escape closes it.
- Click the share button and "Copy link": the link is your own listing URL.
- Click "Choose tour time", pick a day and a time, fill in your details and send the request. Your
  CRM shows the tour with the date and time you picked.
- Change the down payment in the mortgage calculator: the monthly figures follow.
- Fetch `/homes/sitemap/0.xml` and find the listing's URL with its `lastmod`.

## 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 SEO listing pages at /homes/[slug] that follow the recipe at <https://help.ruuster.com/idx/recipe-listing-detail>. Read the listing id with parseListingSlug, call GET /v1/listings/{listingId} on the server with my secret key, and render the ListingDetail component with every screen turned on: backHref set to my search page, agent set to my own agent or office [name, photo URL, phone, email, brokerage and license number], leadAction set to my own lead route with my consent wording in consentText, shareUrl set to the page's own URL on my domain, googleMapsKey and mapId from my own Google Maps key, and apiBaseUrl="/api/idx" for the mortgage calculator (my own listings route, made with createListingsRoute from @ruuster/idx/route). Set the metadata from the listing's head object, print its JSON-LD with the JsonLd component, and add loading.tsx with ListingDetailSkeleton and not-found.tsx with ListingUnavailable and a link back to my search page. Add middleware so an outdated slug answers a 301 to the listing's current path and a removed listing answers HTTP 410 with noindex and a page of similar homes. An unknown id answers 404. Add app/homes/sitemap.ts built from GET /v1/listings/ids (split at 50,000 URLs), app/sitemap.ts for my own pages, and app/robots.ts that lists both.

Use these environment variables: IDX_SECRET_KEY (server only), NEXT_PUBLIC_GOOGLE_MAPS_KEY, NEXT_PUBLIC_GOOGLE_MAP_ID, 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 contact and tour screens post to my own server route, which sends the lead to my CRM; never call a CRM from the browser.

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, tell me how to check each status code with curl -sI, how to test a page in Google's Rich Results Test, and how to open the gallery, the share screen, the contact screen and the tour screen on a live listing and send a test tour request to my CRM.
```

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.
