Menu · Guides
Guides

SEO and AI answers

Eleven steps to listing and area pages that search engines and AI assistants can read, understand and credit to your domain, from URLs and server rendering to JSON-LD, fresh data, crawlers and launch checks.

View as Markdownopenapi.json

Build every page so that Google, Bing and AI assistants such as ChatGPT, Claude, Perplexity and Google's AI Overviews can read it from the HTML your server sends, understand what it is, and credit your domain. Follow the eleven steps in order. Each one has the code to paste and a test that proves it worked.

  • Server-rendered. Every listing, area, sold and search page arrives as finished HTML. Search engines and AI crawlers see the listing text, photos and links before any JavaScript runs.
  • Tagged. The API returns the title, description, canonical URL, Open Graph, Twitter and schema.org JSON-LD for every listing and every results page, built to one standard and masked for hidden addresses.
  • Answer-ready. Area pages answer the questions people ask, with dated market numbers from /v1/market, so an AI assistant can quote your page and link to it.

The code on this page is from the examples repo's Next.js site. The same steps work in any framework (Server rendering in any framework).

1. Plan your URLs

One permanent, readable URL per page, on your own domain. These are the patterns the recipes, the SDK and the examples repo use. Keep them, and every later step works without changes.

Page URL Index it?
Listing detail /homes/{address-slug}-{id}, built by listingPath() Yes. A hidden address gets /homes/{id} with no address in the URL.
Area (city, ZIP code, neighborhood, school area, saved shape) /neighborhoods/midtown, /zip/30308, /cities/decatur Yes. These are your main ranking pages (step 7).
Area sold page /neighborhoods/midtown/sold Yes, on boards that show sold data.
Results page 2 and later /neighborhoods/midtown?page=2 Yes. Each page canonicals to itself.
Search with filters a visitor picked /search?zip=30308&bedsMin=3 No: noindex,follow. Filter combinations are endless; you want the curated area pages to rank.
Our listings, open houses, agent pages /our-listings, /open-houses, /agents/jane-doe Yes.

An outdated slug (the address was corrected) gets a 301 to the current one. The listing id at the end of the slug never changes, so old links and shares keep working. Set your detail-page template, such as https://www.example.com/homes/{slug}, on Website in your console under Listing page link, so every href, canonical link and JSON-LD URL the API returns points at your site.

2. Server-render every page

Most AI crawlers read only the HTML your server sends; they don't run JavaScript. Google renders JavaScript, but later and less reliably. So the listing text, prices, photos, attribution and links to other pages must all be in the first response. Interactive parts (the map, the search box, the photo lightbox) load on top after the page is there.

Page Server call (secret key) In the first HTML
Listing detail GET /v1/listings/{listingId} Address, price, status, facts, description, details, open houses, the first photos as <img>, attribution and disclosures, head tags, JSON-LD
Area and sold pages GET /v1/listings with the area, plus GET /v1/market The count, the first page of cards with links to each listing, your area copy with market numbers, page links, the disclaimers
Search page GET /v1/listings with the URL's parameters The first page of results; the search box and map load on top
Our listings, open houses, agent GET /v1/listings with ownListings, openHousePeriod or agent Cards with links

The area page in Next.js:

app/neighborhoods/[area]/page.tsx

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

export const revalidate = 300;

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

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

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

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

The same page in any server language, over plain HTTP, with no packages:

server.mjs

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

Rules for these pages:

  • Call the API from your server with the secret key, never from the browser, for the content of the page.
  • Cache with ISR or your CDN: about 5 minutes for results and detail pages, an hour or more for market numbers.
  • On a 429 or 503, throw, so ISR keeps serving the last good page. Never cache an error page.
  • Page links and card links are plain <a href>, never click handlers.

Test it. Run curl -s https://www.example.com/neighborhoods/midtown | grep -o 'href="[^"]*/homes/[^"]*"' | sort -u | wc -l with your own domain and area. The count should match the cards on page 1. Then turn JavaScript off in your browser and load the page: you should see every card.

3. Head tags on every page

Every listing answer and every results answer includes a head object, built from the listing (or the area) and your brokerage name, with the canonical URL on your own domain. Pass it to your framework; don't write titles by hand. In Next.js, idx.toMetadata(r.data.head) turns it into the page's metadata, as the area page above and the listing page below do.

app/homes/[slug]/page.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>
  );
}
Page Title the API builds Canonical and robots
Listing {street}, {city}, {state} {zip} · {beds} bd · {baths} ba · {price} · {brokerage} Itself; index,follow
Listing with a hidden address {beds} bd home in {city}, {state} Itself, on the id-only URL; no address anywhere in the head
Area page Homes for sale in {area} · {count} listings · {brokerage}, with · Page {n} from page 2 Itself; page 2 and later canonical to themselves
Sold page Recently sold homes in {area} · {count} listings · {brokerage} Itself
Search with visitor filters The same patterns noindex,follow
Off-market listing Your "no longer available" page HTTP 410, noindex

For results pages, send your page's own URL as pageHref (the SDK and the recipes do). It becomes the canonical link, og:url and the last item of the breadcrumb. Send indexable=1 on a filtered page you curate yourself, or indexable=0 on a page you never want indexed.

Test it. View source on a listing page and an area page. Each has one <title>, one <meta name="description">, one <link rel="canonical"> pointing at your own domain, and og:title, og:image and twitter:card tags. Page 2 of an area canonicals to ?page=2.

4. Structured data (JSON-LD)

Structured data tells search engines and AI assistants exactly what each page is: a home for sale with a price, a list of homes in a place, a brokerage. Google shows no special search result for home listings, so the value is understanding, not stars or badges: the page is read as a listing with a price and a place, which is what an assistant needs to cite it.

  • Listing pages get a schema.org RealEstateListing with an Offer (price, currency, availability), in r.data.jsonLd. Address and coordinates are in it only when the address is not hidden.
  • Area and results pages get an ItemList of the listings on the page and, when you send pageHref, a BreadcrumbList, in r.data.jsonLd.
  • Your whole site gets one RealEstateAgent block for your brokerage, from GET /v1/meta in data.organization. Put it in your layout once.

In React, print them with <JsonLd docs={r.data.jsonLd} /> from @ruuster/idx-recipes, which escapes them safely. Over plain HTTP, print jsonLdHtml exactly as it comes: it is the finished <script type="application/ld+json"> element, already escaped. Never build the script element yourself with a plain JSON.stringify, because listing descriptions can contain text that would end the script early.

The layout with the site-wide block:

app/layout.tsx

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

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

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

Use the same brokerage name, address and phone everywhere you are listed, so assistants recognise one business.

Test it. Paste a listing URL and an area URL into Google's Rich Results Test and the Schema Markup Validator (validator.schema.org). Both should parse with no errors. A hidden-address listing should show no street, no coordinates and an id-only URL.

5. Sitemaps, redirects and 410s

Publish a sitemap of every live listing, built from GET /v1/listings/ids (secret key), and one of your area pages:

lib/listing-ids.ts

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

export const URLS_PER_SITEMAP = 50_000;

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

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

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

app/homes/sitemap.ts

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

export const revalidate = 3600;

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

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

app/sitemap.ts

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

export const revalidate = 3600;

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

Then answer every listing URL with the right status:

The API says Your page does
200, and the slug matches Render the page
200, the slug is outdated 301 to the listing's current path
410 listing_removed HTTP 410 with a "no longer available" page, noindex, links to the area page and similar homes. GET /v1/listings/{listingId}/similar still answers for 30 days after removal. The listing leaves your sitemap on the next build.
404 HTTP 404
Sold, on a board that shows sold data Keep the page live showing "Sold" until the board's sold window ends; then the API answers 410

An App Router page can't answer 410 or 301 by itself, so the example makes the decision in middleware.ts, and the "no longer available" page is a component of its own:

middleware.ts

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

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

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

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

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

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

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

components/gone.tsx

// The page a removed listing shows. 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>
  );
}

Test it. Request a removed listing's URL with curl -sI: the status line says 410. Change one word of a live listing's slug and request it: you get a 301 to the right slug. Fetch both sitemaps and check that they load.

6. Keep pages fresh

Prices and statuses change through the day. Re-render a page as soon as its listing changes, so Google and assistants never quote a stale price. Use the listing-change webhook (within minutes) or poll GET /v1/changes every 5 minutes.

app/api/ruuster-webhook/route.ts

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

export const dynamic = "force-dynamic";

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

The route calls handleRuusterWebhook, which checks the signature and re-renders the pages each event touches:

lib/revalidate.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 });
}

Set it up:

  1. In your console, open Keys and domains, find Sample webhooks and press Add a webhook. Enter https://www.example.com/api/ruuster-webhook with your own domain.
  2. Pick the four listing events. Copy the signing secret into RUUSTER_WEBHOOK_SECRET on your host.
  3. Press Send test and check your function logs for a 200.
  4. Once you are live, email helpme@ruuster.com with the same address to have a webhook added for your live listings. Listing-change webhooks.

Deliveries are at least once and can arrive out of order, so the handler only re-renders. Changing a page twice is harmless. verifyWebhook from @ruuster/idx checks the signature and returns the events, whether the body holds one event or a batch. Listing-change webhooks has the details.

Test it. After a real price change in your boards, load the listing page within a few minutes: the new price is in view-source and in the JSON-LD offers.price.

7. Area pages that answer questions

Answer engines (ChatGPT search, Perplexity, Claude, Google AI Overviews and AI Mode) quote pages that answer a question directly, with specific numbers and a date, near the top. Listing pages are the same on every site; your area pages are what make your site the source. Write one for each place you sell in, using this template, top to bottom:

  1. A one-sentence answer first, with the numbers and the date.
  2. Four stat tiles from /v1/market (the MarketStats component).
  3. Three to five questions as <h2> headings, each answered in its first sentence.
  4. Your own section: what only your agents know about the place.
  5. Listings, page links, the map and the disclaimers.

The lead sentence and the tiles come from one call, m.data.measures:

content/answer.ts

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

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

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

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

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

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

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

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

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

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

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

Writing rules:

  • Always print the "updated" date and the boards the numbers came from.
  • Show a sold number only where your boards show sold data. /v1/market leaves it null otherwise, so hide that tile.
  • Write your own words. Don't paste listing descriptions into area copy.
  • Fair housing: describe homes, places and amenities, never who lives there or who a place suits. Name schools by name and boundary; don't rank them as a reason to buy.
  • Mark up the questions as FAQPage if you like. Google shows FAQ results only for a few kinds of sites, but assistants still read the structure.

Test it. Read your area page's first sentence aloud. It should answer "how much do homes cost here?" with a number and a date. Then ask an assistant that question about the area a few weeks after launch.

8. Let search and AI crawlers in

app/robots.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`))],
  };
}

Why each matters:

  • Search crawlers (OAI-SearchBot and ChatGPT-User for ChatGPT search, Claude-SearchBot and Claude-User for Claude, PerplexityBot and Perplexity-User, Googlebot, Bingbot) decide whether an assistant can find and cite you. Keep them allowed.
  • Training crawlers (GPTBot, ClaudeBot, Google-Extended, Applebot-Extended) only affect model training. Blocking them is your choice and doesn't remove you from search or AI answers.
  • ChatGPT search draws on Bing's index, so submit your sitemaps to Bing Webmaster Tools as well as Google Search Console.
  • Turn on IndexNow in your host or CDN, if it offers it, so Bing re-crawls changed pages within minutes.

Keep staging out. Your staging site shows live MLS data. Put it behind a password, or send X-Robots-Tag: noindex on every response, and never list it in a sitemap.

Optional: /llms.txt. A short Markdown file at your site's root that lists your area pages and what your brokerage does. It is cheap to add; treat it as a bonus, since the sitemap and the HTML do the real work. The example generates it from your area list:

app/llms.txt/route.ts

// /llms.txt: a short Markdown summary of your site for AI assistants, built from content/areas.ts.
// Your sitemaps and the HTML of each page do the real work; this file is a small extra.
import { AREAS } from "@/content/areas";
import { absoluteUrl, SITE_NAME } from "@/lib/site";

export const revalidate = 3600;

export function GET() {
  const lines = [
    `# ${SITE_NAME}`,
    "",
    `> ${SITE_NAME} is a real estate brokerage. This site lists the homes for sale in the areas below, with a page for every listing, recent market numbers for each area and our agents' own notes.`,
    "",
    "## Area pages",
    "",
    ...AREAS.map((a) => `- [Homes for sale in ${a.name}](${absoluteUrl(`/neighborhoods/${a.slug}`)}): listings, market numbers and our notes on ${a.name}.`),
    "",
    "## Listings",
    "",
    `- [Search homes for sale](${absoluteUrl("/search")})`,
    `- [Our listings](${absoluteUrl("/our-listings")})`,
    `- [Open houses this weekend](${absoluteUrl("/open-houses")})`,
    `- [Listing sitemap](${absoluteUrl("/homes/sitemap/0.xml")}): one URL per home for sale.`,
    "",
  ];
  return new Response(lines.join("\n"), { headers: { "Content-Type": "text/markdown; charset=utf-8" } });
}

Leave filtered searches crawlable. Don't add /search? to robots.txt. A filtered search page sends noindex,follow, and a crawler only sees that when it is allowed to fetch the page. A blocked URL can still be indexed without its content, and the links on it go unfollowed. If crawl volume on filtered searches becomes a problem later, add Disallow: /search? only after Search Console shows those URLs have left the index.

Test it. Open /robots.txt on your site. It allows /, disallows /api/ and /account/, and names both sitemaps. Open both sitemap URLs and check that they load.

9. Fast pages (Core Web Vitals)

Speed counts toward ranking. Aim for these at the 75th percentile on mobile:

Target How the recipes meet it
Largest Contentful Paint at most 2.5 s The first photo is a real <img> with fetchpriority="high" and, on photos.ruuster.com, a sized srcset. Preconnect to photos.ruuster.com.
Cumulative Layout Shift at most 0.1 Every photo carries its width and height. The map and gallery reserve their space before they load.
Interaction to Next Paint at most 200 ms The map, the search box and the lightbox load after the page is interactive. Fonts use font-display: swap.

photoAttrs from @ruuster/idx gives every photo these attributes: Photos: sizes, alt text and loading.

Test it. Run Lighthouse on a listing page and an area page in mobile mode. Largest Contentful Paint, Cumulative Layout Shift and Total Blocking Time should all be green.

10. Analytics tags

The recipe components push GA4's recommended events to dataLayer, so Google Analytics, Google Ads and Meta can measure your listing pages and your forms. Load your own Google Tag Manager container; the components only push events.

Event When What it carries
view_item_list A results or area page renders item_list_name (the area), and items with item_id (the MLS number), price and item_category (the type)
view_item A listing page renders The one item
search A visitor runs a search search_term (the place picked)
generate_lead Your tour, contact or registration form succeeds The form's name and the item

Analytics: GA4 and Google Tag Manager has the importable container and how the CRM routes carry the same campaign details.

Test it. Open Google Tag Manager's preview mode on an area page and a listing page. You see view_item_list and view_item. Submit a form: you see generate_lead.

11. Verify, submit and monitor

Before launch, check every line:

  • View source on a listing, an area and a sold page: the address, price and card links are in the HTML.
  • With JavaScript off, every page still shows its listings.
  • Search Console URL Inspection, "View crawled page": the same content.
  • Rich Results Test and validator.schema.org: no errors.
  • A hidden-address listing: no street in the URL, title, JSON-LD, Open Graph tags or map.
  • An off-market listing answers 410, and an old slug answers 301.
  • /robots.txt and both sitemaps load, and staging is not indexable.
  • Lighthouse mobile: Largest Contentful Paint, Cumulative Layout Shift and Total Blocking Time in the green.
  • A test webhook answers 200, and a price change shows within minutes.
  • Every board's disclaimer shows on every results page and on the map.
  • Sitemaps are submitted to Google Search Console and Bing Webmaster Tools.

After launch, every month:

  • Search Console, Pages: listing pages indexed compared with submitted.
  • Search Console, Performance: area pages by query. Add the questions people search for to the page.
  • Ask ChatGPT, Perplexity and Claude your top area questions ("homes for sale in Midtown Atlanta", "median home price in Midtown Atlanta") and note whether your page is cited.
  • GA4: sessions referred from chatgpt.com, perplexity.ai and claude.ai.
  • Refresh each area page's own section every quarter.

Same listing, many sites. The same home appears on every broker's site and on the portals. Your page wins on your domain's reputation, speed, internal links and the content around the listing that only you have: your area pages, your agents' notes, your sales.

Launch checklist adds the compliance, key, CRM and webhook checks to this list.

Build it with your AI coding assistant. Prompt: SEO listing pages and Prompt: neighborhood pages from a list build steps 1 to 8 from this page and RUUSTER_IDX.md. Prompt: compliance and launch audit runs this checklist against your site and changes nothing until you approve.