# Recently sold

Source: https://help.ruuster.com/idx/recipe-recently-sold

> A /neighborhoods/<area>/sold page listing homes sold in the last 6 months, published only where your boards show sold data, with a link to the area page everywhere else.

A page such as `/neighborhoods/midtown/sold` with the homes that sold in the area in the last 6
months, most recent first. Each card shows the sold price and the sold date. MLS boards decide
whether sold listings may be shown, so the page first reads `GET /v1/meta` and publishes sold
listings only when at least one of your boards allows them; on other boards it shows a link to the
area page. Title it "Recently sold homes in" the area, never "our sales": the list holds every
brokerage's sales.

## What the visitor sees

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-card-sold-1440.png" alt="Listing card for a sold home (close price and close date), on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>Sold homes use the same card, with the sold price and date.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-card-sold-375.png" alt="Listing card for a sold home (close price and close date), on a phone (375 px wide)" width="375" height="812" loading="lazy" decoding="async"><figcaption>Sold homes use the same card, with the sold price and date.</figcaption></figure>

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

## What the page calls

| When | Request | Key | Cached |
|---|---|---|---|
| Each page view | `GET /v1/meta`, for `capabilities.sold` | secret key, on your server | 5 minutes by Next.js |
| Each page view, where sold data is shown | `GET /v1/listings` with `status=closed`, `soldPeriod=6m`, `sort=close_date_desc` | secret key, on your server | 5 minutes by Next.js |

cURL:

```bash
curl -s "https://idx.ruuster.com/v1/meta" \
  -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.meta();
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/meta",
    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/meta');
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']);
```

`capabilities.sold` lists each board with `mlsId`, `allowed` and its sold window in days. To say
which boards show sold data, match each `mlsId` with a board's `id` in `data.mls`, which holds its
`name` ([Sold listings](https://help.ruuster.com/idx/guide-sold) shows the code).

Each sold card shows the sold price (`closePrice`) and a "Sold" badge with the sale date, such as
"Sold Sep 1, 2026", in place of any open house.

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode 'where={"label":"Atlanta, GA Midtown","value":"a0000000-0000-4000-8000-000000000001","source":"neighborhood","data":{"state":"GA"}}' \
  --data-urlencode status=closed \
  --data-urlencode soldPeriod=6m \
  --data-urlencode sort=close_date_desc \
  --data-urlencode limit=24 \
  --data-urlencode pageHref=/neighborhoods/midtown/sold \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

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

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

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

Python:

```python
import os

import requests

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

PHP:

```php
<?php

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

## Steps

1. Build the [area page](https://help.ruuster.com/idx/recipe-neighborhood-page) first; the sold page
   reuses its `content/areas.ts` and `lib/area-query.ts`.
2. Set `soldPage: true` on each area in `content/areas.ts` that should have a sold page.
3. Create `app/neighborhoods/[area]/sold/page.tsx` with the code below.
4. Open `http://localhost:3000/neighborhoods/midtown/sold`. On boards without sold data you see the
   link to the area page instead.
5. `app/sitemap.ts` lists each sold page only while your boards show sold data.

## The code

<p class="code-title"><code>app/neighborhoods/[area]/sold/page.tsx</code></p>

```tsx
// /neighborhoods/<area>/sold: homes sold in the last 6 months. Published only when at least one of
// your boards shows sold data (GET /v1/meta capabilities.sold); otherwise it links to the area page.
import Link from "next/link";
import { notFound } from "next/navigation";
import { Results } from "@/components/results";
import { AREAS, areaBySlug } from "@/content/areas";
import { getMeta, idx } from "@/lib/idx";
import { showsSoldData, soldQuery } 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.filter((a) => a.soldPage).map((a) => ({ area: a.slug }));
}

async function soldAllowed(): Promise<boolean> {
  const meta = await getMeta();
  return meta.ok && showsSoldData(meta.data.capabilities);
}

export async function generateMetadata({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area?.soldPage) return {};
  if (!(await soldAllowed())) return { title: `Homes in ${area.name}`, robots: "noindex,follow" };
  const r = await idx.search(soldQuery(area, searchParams));
  return r.ok ? resultsMetadata(r.data.head, `Recently sold homes in ${area.name}`) : {};
}

export default async function SoldPage({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area?.soldPage) notFound();
  if (!(await soldAllowed())) {
    return (
      <main>
        <h1>{`Homes in ${area.name}`}</h1>
        <p>
          <Link href={`/neighborhoods/${area.slug}`}>See the homes for sale in {area.name}</Link>
        </p>
      </main>
    );
  }
  const r = await idx.search(soldQuery(area, searchParams));
  if (!r.ok) {
    const action = failureAction(r);
    if (action === "not_found") notFound();
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  return (
    <main>
      <nav aria-label="Breadcrumb">
        <Link href="/neighborhoods">Neighborhoods</Link> › <Link href={`/neighborhoods/${area.slug}`}>{area.name}</Link> › Recently sold
      </nav>
      <h1>{`Recently sold homes in ${area.name}`}</h1>
      <p>Homes that sold in the last 6 months, most recent first. Each card shows the sold price and date.</p>
      <Results r={r} basePath={`/neighborhoods/${area.slug}/sold`} searchParams={searchParams} listName={`Recently sold in ${area.name}`} />
    </main>
  );
}
```

The sold search and the capability check, from `lib/area-query.ts`:

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

```ts
// Turns an area and the page's URL into the search the page sends.
// The area fixes the location; the visitor's URL may add filters, a sort order and a page.
import { fromSearchParams, type SearchParamsInput, type SearchQuery } from "@ruuster/idx";
import type { Area } from "@/content/areas";

/** A search that answers listing cards (the default view). */
export type CardQuery = Omit<SearchQuery, "view">;

/** URL names a visitor may not change on an area page: the location, the key-level options and the page size. */
const FIXED = ["where", "bbox", "polygon", "boundariesId", "zip", "city", "state", "shape", "ownListings", "agent", "office", "view", "detailHref", "pageHref", "indexable", "limit"] as const;

/** Results per page on every results page of this site. */
export const PAGE_SIZE = 24;

/** The visitor's filters, sort and page from the URL, without anything that would change the location. */
export function visitorQuery(searchParams: SearchParamsInput): CardQuery {
  const q: Record<string, unknown> = { ...fromSearchParams(searchParams) };
  for (const k of FIXED) delete q[k];
  return q as CardQuery;
}

/** The API's default order; there is no "newest" sort. */
/** /neighborhoods/<slug>: the area's active listings in the API's recommended order unless the visitor picked another. */
export function areaQuery(area: Area, searchParams: SearchParamsInput): CardQuery {
  return {
    ...visitorQuery(searchParams),
    status: "active",
    where: area.where,
    limit: PAGE_SIZE,
    pageHref: `/neighborhoods/${area.slug}`,
  };
}

/** /neighborhoods/<slug>/sold: homes sold in the last 6 months, most recent first. */
export function soldQuery(area: Area, searchParams: SearchParamsInput): CardQuery {
  const v = visitorQuery(searchParams);
  return {
    ...v,
    status: "closed",
    soldPeriod: "6m",
    sort: "close_date_desc",
    where: area.where,
    limit: PAGE_SIZE,
    pageHref: `/neighborhoods/${area.slug}/sold`,
  };
}

/** True when the query names a location (or own, agent or office listings), which every search needs. */
export function hasLocation(q: SearchQuery): boolean {
  const where = Array.isArray(q.where) ? q.where.length > 0 : Boolean(q.where);
  return where || Boolean(q.bbox || q.polygon || q.boundariesId || q.zip || q.city || q.state || q.shape || q.ownListings || q.agent || q.office);
}

/**
 * True when at least one of your boards shows sold data (GET /v1/meta capabilities.sold).
 * Sold pages are published only then.
 */
export function showsSoldData(capabilities: Readonly<Record<string, unknown>> | null | undefined): boolean {
  const sold = capabilities?.sold;
  return Array.isArray(sold) && sold.some((b) => typeof b === "object" && b !== null && (b as { allowed?: unknown }).allowed === true);
}
```

## Forms and your CRM

Sold pages carry no forms. Visitors reach your tour and contact forms from your listing pages
([Registration, tour and contact forms](https://help.ruuster.com/idx/recipe-forms)).

## Rules this page follows

**MUST**

- Check `capabilities.sold` before showing sold listings, and follow each board's sold window (the
  API answers only the listings inside it).
- Show the sold price and date on each card and every board's disclaimer under the list.

**NEVER**

- Call the page "our sales" or imply your brokerage sold every home on it.
- Fill the page with active listings when sold data is not shown, without saying so.

## Test it

```sh
curl -s http://localhost:3000/neighborhoods/midtown/sold | grep -o "<h1>[^<]*</h1>"
```

Where your boards show sold data, the heading is "Recently sold homes in Midtown" and view source
shows the cards with their sold prices. Where they do not, the page shows the link to the area page.

## 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.

Add a recently sold page at /neighborhoods/[area]/sold for each area page, following <https://help.ruuster.com/idx/recipe-recently-sold>. First read GET /v1/meta and check capabilities.sold: build the page only where at least one of my boards shows sold data, and otherwise show a link to the area page instead of sold listings. Search with status=closed, soldPeriod=6m and sort=close_date_desc, and title the page "Recently sold homes in" the area. Never fall back to active listings without saying so. Each card shows the sold price and date.

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

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 which of my boards show sold data according to /v1/meta.
```

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.
