# Neighborhood and area pages

Source: https://help.ruuster.com/idx/recipe-neighborhood-page

> An area page such as /neighborhoods/midtown that answers the questions people ask with dated market numbers, adds your own words, and lists the area's homes with pagination, the map and the MLS disclaimers.

A page such as `/neighborhoods/midtown` for each place you sell in. It opens with one sentence that
answers "what is the market like here" with today's numbers and the date, shows four market tiles,
answers the questions people ask as `<h2>` headings, adds your agents' own words, and then lists the
area's homes with pagination, a map with the area's outline and the MLS disclaimers. Your server
renders all of it, so search engines index it and AI assistants can quote it. These pages are your
main ranking pages ([SEO and AI answers](https://help.ruuster.com/idx/guide-seo-ai-answers), step 7).

The same recipe makes a ZIP code page, a city page, a school area page or a page for a shape you saved
in Ruuster: store that place's `/v1/suggest` row instead.

## What the visitor sees

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-grid-1440.png" alt="Listing grid with the disclaimers under it, on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>The area's listings.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/listing-grid-375.png" alt="Listing grid with the disclaimers under it, on a phone (375 px wide)" width="375" height="1403" loading="lazy" decoding="async"><figcaption>The area's listings.</figcaption></figure>

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

Above the listings, the page shows your answer sentence, the market tiles and the questions, in your
site's own layout.

## What the page calls

| When | Request | Key | Cached |
|---|---|---|---|
| Once, while you set up the page | `GET /v1/suggest` for the place's name | secret key, from your terminal | you store the row in `content/areas.ts` |
| Each page view | `GET /v1/listings` with the stored `where` row | secret key, on your server | 5 minutes by Next.js |
| Each page view | `GET /v1/market` with the same `where` row, 13 months | secret key, on your server | 5 minutes by Next.js |
| When the map is on | `GET /v1/boundaries/{boundaryId}` for the outline | secret key, on your server | 5 minutes by Next.js |

Find the place's row once:

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/suggest" \
  --data-urlencode q=Midtown \
  --data-urlencode groups=neighborhood \
  -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.suggest({
  q: "Midtown",
  groups: ["neighborhood"],
});
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/suggest",
    params={
        "q": "Midtown",
        "groups": "neighborhood",
    },
    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([
    'q' => 'Midtown',
    'groups' => 'neighborhood',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/suggest' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

The listings on page 1:

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=active \
  --data-urlencode limit=24 \
  --data-urlencode pageHref=/neighborhoods/midtown \
  -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: "active",
  limit: 24,
  pageHref: "/neighborhoods/midtown",
});
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": "active",
        "limit": "24",
        "pageHref": "/neighborhoods/midtown",
    },
    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' => 'active',
    'limit' => '24',
    'pageHref' => '/neighborhoods/midtown',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

The market numbers for the answer sentence and the tiles:

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/market" \
  --data-urlencode 'where={"label":"Atlanta, GA Midtown","value":"a0000000-0000-4000-8000-000000000001","source":"neighborhood","data":{"state":"GA"}}' \
  --data-urlencode months=13 \
  -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.market({
  where: {
    label: "Atlanta, GA Midtown",
    value: "a0000000-0000-4000-8000-000000000001",
    source: "neighborhood",
    data: {
      state: "GA",
    },
  },
  months: 13,
});
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/market",
    params={
        "where": "{\"label\":\"Atlanta, GA Midtown\",\"value\":\"a0000000-0000-4000-8000-000000000001\",\"source\":\"neighborhood\",\"data\":{\"state\":\"GA\"}}",
        "months": "13",
    },
    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"}}',
    'months' => '13',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/market' . '?' . $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`, `lib/site.ts` and `components/results.tsx` from the
   [recipes overview](https://help.ruuster.com/idx/recipes), and `lib/area-query.ts` and
   `lib/results.ts` from the [search page recipe](https://help.ruuster.com/idx/recipe-search-page).
2. For each place, run the suggest call above in your terminal with your secret key in your shell
   (never in a chat), pick the row for the place you mean, and paste its `where` object into
   `content/areas.ts` unchanged.
3. Write your agents' own paragraphs for each area in `ownWords`, and any questions you answer
   yourself in `questions`.
4. Create `content/answer.ts` and `app/neighborhoods/[area]/page.tsx` with the code below.
5. Run `npm run dev` and open `http://localhost:3000/neighborhoods/midtown`.
6. Add every area page to `app/sitemap.ts` ([Area guide hub](https://help.ruuster.com/idx/recipe-area-guide-hub)
   has the file).

## The code

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

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

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

```ts
// The places you sell in: one entry per area page. This file is your own content.
//
// `where` is the row GET /v1/suggest answered for the place, copied in once and never edited by
// hand. To get one, run (with your secret key in your shell, never in a chat):
//   curl -s "https://idx.ruuster.com/v1/suggest?q=Midtown&groups=neighborhood" -H "Authorization: Bearer $IDX_SECRET_KEY"
// and paste the `where` object of the row you want.
// The two areas below are example rows; replace them with your own.
import type { WhereObject } from "@ruuster/idx";

export type AreaQuestion = { question: string; answer: string };

export type Area = {
  /** The URL segment: /neighborhoods/<slug>. */
  slug: string;
  /** The name you show in headings and links. */
  name: string;
  /** The /v1/suggest row for this place, unchanged. */
  where: WhereObject;
  /** Publish /neighborhoods/<slug>/sold. The page also checks that your boards show sold data. */
  soldPage: boolean;
  /** Your agents' own words about the area: the streets, the housing, what buyers ask about. */
  ownWords: readonly string[];
  /** Questions you answer yourself, shown after the market questions. Each answer starts with the answer. */
  questions: readonly AreaQuestion[];
};

export const AREAS: readonly Area[] = [
  {
    slug: "midtown",
    name: "Midtown",
    where: { label: "Atlanta, GA Midtown", value: "a0000000-0000-4000-8000-000000000001", source: "neighborhood", data: { state: "GA" } },
    soldPage: true,
    ownWords: [
      "Midtown mixes high-rise condos along Peachtree Street with brick bungalows on the quieter side streets east of the park.",
      "Most condo buildings here have a monthly association fee that covers the pool, the gym and building insurance, so ask for the budget early.",
    ],
    questions: [
      {
        question: "What kinds of homes are in Midtown?",
        answer: "Mostly condos in mid-rise and high-rise buildings, with single-family homes and townhomes on the side streets.",
      },
    ],
  },
  {
    slug: "atlanta",
    name: "Atlanta",
    where: { label: "Atlanta, GA", value: "Atlanta", source: "crm-system", data: { state: "GA", city: "Atlanta" }, city: "Atlanta", state: "GA" },
    soldPage: true,
    ownWords: ["Atlanta's listings range from downtown lofts to wooded lots inside the Perimeter, and every neighborhood has its own page on this site."],
    questions: [],
  },
];

/** The area the site-wide pages (open houses, price reduced, new construction) search in. */
export const MARKET_AREA: Area = AREAS[AREAS.length - 1];

export function areaBySlug(slug: string): Area | null {
  return AREAS.find((a) => a.slug === slug) ?? null;
}
```

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

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

## Forms and your CRM

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

## Rules this page follows

**MUST**

- Store the `where` row exactly as `/v1/suggest` answered it.
- Print the "Updated" date with the market numbers, and every board's disclaimer under the listings.
- Hide a market tile and its sentence when `/v1/market` answers null for it (boards that show no sold
  data answer null for the sold measures).
- Re-render at least every 5 minutes (`revalidate = 300`) or on the listing-change webhook.

**NEVER**

- Describe a neighborhood by who lives there or who it suits, or rank schools as a reason to buy
  ([Fair housing](https://help.ruuster.com/idx/fair-housing)).
- Paste listing remarks into your area copy.
- Store listings in bulk or serve them to another site.

## Test it

```sh
curl -s http://localhost:3000/neighborhoods/midtown | grep -o 'href="[^"]*/homes/[^"]*"' | sort -u | wc -l
```

The count matches the cards on page 1. View source and find the answer sentence with its date, each
question as an `<h2>`, and the `<script type="application/ld+json">` block with the `ItemList`. Paste
the URL into Google's Rich Results Test: it parses with no errors.

## 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 neighborhood pages at /neighborhoods/[area] for this list of places: [your list]. Follow the recipe at <https://help.ruuster.com/idx/recipe-neighborhood-page>. For each place, call GET /v1/suggest once on the server with my secret key, show me the rows it answers so I can confirm the right one, and store that row's where object unchanged in content/areas.ts. Never build or edit a where object by hand. Each page opens with one sentence that answers what the market is like, using GET /v1/market numbers and the date. Then it shows the MarketStats tiles, answers three to five questions as <h2> headings with the answer in the first sentence, leaves a section for my agents' own words, and shows the listings, pagination, the map, the MLS disclaimers and the JSON-LD. Add the area pages to app/sitemap.ts and build an area hub at /neighborhoods.

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. Do not copy listing remarks into the area copy, and write a marked placeholder for my agents' own section instead of inventing it.

When you are done, list the where rows you stored so I can check them.
```

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.
