# Off-market and removed listings

Source: https://help.ruuster.com/idx/guide-removed-listings

> What happens when a listing goes off the market, sells past its board's window or leaves your scope, and how your pages, sitemaps and caches should answer.

Listings leave your site for three reasons: they go off the market, a sale passes its board's sold
window, or a board leaves your key's scope. Each one must leave your pages promptly. The API tells you
when, and these are the answers your site gives.

## What the API answers

| Situation | `GET /v1/listings/{listingId}` | Your page |
|---|---|---|
| Live listing | 200 | Render it |
| Live, but the URL's slug is outdated | 200 with the current `slug` | 301 to the current path |
| Withdrawn, expired, cancelled or deleted | 410 `listing_removed` | 410 with your "no longer available" page |
| Sold, on a board that shows sold data, inside its window | 200 with status `closed` | Render it as sold |
| Sold, past the board's window, or on a board that shows no sold data | 410 `listing_removed` | 410 |
| On a board outside your scope | 404 `mls_not_in_scope` | 404 |
| Unknown id | 404 `not_found` | 404 |

## The "no longer available" page

Answer with HTTP status 410, not 200 and not a redirect to your home page.

- Put `<meta name="robots" content="noindex">` in its head.
- Say the home is no longer available, without the old price or photos.
- Link to the area's page and to a search.
- Show homes like it. `GET /v1/listings/{listingId}/similar` keeps answering for a removed listing for
  30 days, with `data.subjectRemoved` set to true. After that, link to the area page alone. Each item
  in `data.listings` is `{ listing, why }`, so pass `data.listings.map((s) => s.listing)` to your
  grid.

Next.js adds its own `<meta name="robots" content="noindex">` to every page it answers with a status
above 400. Your 410 page then carries that tag beside its own `noindex,follow`. Both say `noindex`, so
search engines drop the page either way, and the `X-Robots-Tag: noindex` header says it once more.

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

An App Router page can't set a 410 status by itself, so the examples repo decides 301 and 410 in
`middleware.ts` before the page renders. [Listing pages](https://help.ruuster.com/idx/recipe-listing-detail#how-the-middleware-works)
explains each part of it:

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

## Sitemaps and caches

- A removed listing leaves `/v1/listings/ids` at once, so it leaves your sitemap on the next build.
- `/v1/changes` reports it as a `removed` row, and the webhook sends `listing.removed`. Re-render its
  page and the area pages that showed it.
- Purge it from any cache you keep. Never keep showing a listing the API no longer returns.

## A whole board leaves

When a board leaves your key's scope, `/v1/changes` sends one `scope_removed` row whose `id` is the
board's id. Drop every listing with that `mls`, re-render the pages that showed them, and rebuild your
sitemap. Searches stop returning its listings at the same moment.
