# One agent's listings

Source: https://help.ruuster.com/idx/recipe-agent-listings

> An /agents/<agent> page with one agent's listings, rendered on your server, and a contact form that sends to your CRM.

A page for each of your agents, such as `/agents/jordan-agent`, with that agent's listings and a
contact form. `agent=<the agent's Ruuster slug or id>` asks for the listings, and it needs no
location. The agent's photo and bio are your own content: add them above the listings. The contact
form posts to your own route, which sends the message to your CRM.

## 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 agent's listings in the card grid.</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 agent's listings in the card grid.</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.

## What the page calls

| When | Request | Key | Cached |
|---|---|---|---|
| Each page view | `GET /v1/listings` with `agent` | secret key, on your server | 5 minutes by Next.js |

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode agent=jordan-agent \
  --data-urlencode status=active \
  --data-urlencode status=coming_soon \
  --data-urlencode status=pending \
  --data-urlencode limit=24 \
  --data-urlencode pageHref=/agents/jordan-agent \
  -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({
  agent: "jordan-agent",
  status: ["active", "coming_soon", "pending"],
  limit: 24,
  pageHref: "/agents/jordan-agent",
});
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={
        "agent": "jordan-agent",
        "status": ["active", "coming_soon", "pending"],
        "limit": "24",
        "pageHref": "/agents/jordan-agent",
    },
    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

// Repeated names are sent once per value: http_build_query would add [] to them.
$pairs = [
    ['agent', 'jordan-agent'],
    ['status', 'active'],
    ['status', 'coming_soon'],
    ['status', 'pending'],
    ['limit', '24'],
    ['pageHref', '/agents/jordan-agent'],
];
$query = implode('&', array_map(fn ($p) => rawurlencode($p[0]) . '=' . rawurlencode($p[1]), $pairs));
$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']);
```

An agent slug that does not belong to your brokerage answers 404 `agent_not_found`, and the page
answers 404.

## 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. Create `app/agents/[agent]/page.tsx` with the code below, and add each agent's photo and bio
   above the listings.
3. Wire the contact form to your CRM ([Registration, tour and contact forms](https://help.ruuster.com/idx/recipe-forms)).
4. Open `http://localhost:3000/agents/` followed by an agent's Ruuster slug.

## The code

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

```tsx
// /agents/<agent>: one agent's listings and a contact form. <agent> is the agent's Ruuster slug or id.
// The agent's photo and bio are your own content; add them above the listings.
import { notFound } from "next/navigation";
import { ContactForm } from "@ruuster/idx-recipes";
import { Results } from "@/components/results";
import { idx } from "@/lib/idx";
import { PAGE_SIZE, visitorQuery, type CardQuery } from "@/lib/area-query";
import { failureAction, resultsMetadata } from "@/lib/results";
import { CONSENT_TEXT, LEADS_ACTION } from "@/lib/site";

export const revalidate = 300;

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

function query(agent: string, searchParams: Props["searchParams"]): CardQuery {
  return { ...visitorQuery(searchParams), agent, status: ["active", "coming_soon", "pending"], limit: PAGE_SIZE, pageHref: `/agents/${encodeURIComponent(agent)}` };
}

export async function generateMetadata({ params, searchParams }: Props) {
  const r = await idx.search(query(params.agent, searchParams));
  return r.ok ? resultsMetadata(r.data.head, "Agent listings") : {};
}

export default async function AgentPage({ params, searchParams }: Props) {
  const r = await idx.search(query(params.agent, searchParams));
  if (!r.ok) {
    // agent_not_found: no agent with that slug at your brokerage.
    if (failureAction(r) === "not_found") notFound();
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  const name = r.data.location?.label ?? "this agent";
  return (
    <main>
      <h1>{`Listings from ${name}`}</h1>
      <Results r={r} basePath={`/agents/${encodeURIComponent(params.agent)}`} searchParams={searchParams} listName={`Listings from ${name}`} emptyText="No listings on the market right now." />
      <section aria-labelledby="contact">
        <h2 id="contact">Contact {name}</h2>
        <ContactForm action={LEADS_ACTION} consentText={CONSENT_TEXT} submitLabel="Send message" />
      </section>
    </main>
  );
}
```

## Forms and your CRM

The `ContactForm` posts to `LEADS_ACTION` in `lib/site.ts`, your own route, which sends the message
to Follow Up Boss, Sierra Interactive or Sure Send. Its consent box starts unchecked. See
[Registration, tour and contact forms](https://help.ruuster.com/idx/recipe-forms) and
[Your CRM](https://help.ruuster.com/idx/crm-overview).

## Rules this page follows

**MUST**

- Show each card's attribution line where its board requires one, and every board's disclaimer.
- Keep the contact consent box unchecked until the visitor checks it.

**NEVER**

- Describe the agent's clients or who the agent's listings suit
  ([Fair housing](https://help.ruuster.com/idx/fair-housing)).
- Post the form to a CRM from the browser.

## Test it

```sh
curl -sI http://localhost:3000/agents/nobody-here | head -1
```

An unknown agent answers `HTTP/1.1 404 Not Found`. On a real agent's page, view source and find the
listing links and the contact form with its unchecked consent box, then send a test message and find
it in your CRM.

## 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 an agent page at /agents/[agent] that follows <https://help.ruuster.com/idx/recipe-agent-listings>. Show that agent's listings from GET /v1/listings with agent=<the agent's Ruuster slug>, rendered on the server, and a ContactForm posting to my own lead route. The agent's photo and bio are my own content: leave a clearly marked place for them, and do not invent a bio. If the API answers agent_not_found, the page answers 404.

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, list the agent slugs you used 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.
