# Email me new matches (save a search)

Source: https://help.ruuster.com/idx/recipe-save-search

> An "Email me new matches" box on your search page that saves the visitor's current search as a Listing Alerts saved search, through your own server route, with their consent.

With the Listing Alerts add-on, a visitor on your search page can ask for an email whenever a new
home matches what they are looking at. `AlertSignupForm` from `@ruuster/idx-recipes` asks for their
name, email and how often, with your consent sentence beside a box that starts unchecked. It posts to
your own server route, which creates the buyer and the saved search with your secret key.

## What the visitor sees

A short form in the same style as your other lead forms: first name, email, how often (as soon as
homes match, once a day or once a week), an optional name for the search, your consent sentence and
an "Email me new matches" button that stays off until the box is checked. On success it shows a
thank-you line.

## The page

The search page's own filters become the saved search. Leave out paging, sorting and the view:

<p class="code-title"><code>packages/ruuster-idx-recipes/snippets/alerts-search-page.tsx</code></p>

```tsx
// On your search page: "Email me new matches" for the search the visitor is looking at.
import { fromSearchParams } from "@ruuster/idx";
import { AlertSignupForm } from "@ruuster/idx-recipes";

const ALERTS_CONSENT = "Email me new listings that match this search. I can unsubscribe at any time.";

export function SearchAlerts({ searchParams }: { searchParams: Record<string, string | string[] | undefined> }) {
  // The page's own filters are the saved search's criteria (no page, sort or view).
  const { page: _page, sort: _sort, view: _view, limit: _limit, ...criteria } = fromSearchParams(searchParams) as Record<string, unknown>;
  return <AlertSignupForm action="/api/alerts/save-search" criteria={criteria as Record<string, string>} consentText={ALERTS_CONSENT} askName />;
}

// A sign-up box for one area's new listings, for a neighborhood page.
export function AreaAlerts({ zip, areaName }: { zip: string; areaName: string }) {
  return <AlertSignupForm variant="signup" action="/api/alerts/save-search" criteria={{ zip }} searchName={`New listings in ${areaName}`} consentText={ALERTS_CONSENT} defaultFrequency="daily" />;
}
```

## The server route

The route drops bot submissions (the hidden `website` field), then sends the buyer, the consent
words the visitor saw, their IP and the search in one call. Repeating it is safe.

<p class="code-title"><code>packages/ruuster-idx-recipes/snippets/alerts-save-search-route.ts</code></p>

```ts
// app/api/alerts/save-search/route.ts: AlertSignupForm posts here; the buyer, their consent and the
// saved search go to the Listings API in one call, with your secret key, from your server.
import { createClient, type AlertCriteria, type AlertFrequency } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });
const FREQUENCIES: readonly AlertFrequency[] = ["instant", "daily", "weekly"];

export async function POST(req: Request): Promise<Response> {
  let body: { email?: unknown; firstName?: unknown; frequency?: unknown; searchName?: unknown; criteria?: unknown; consent?: { text?: unknown; source?: unknown }; website?: unknown };
  try {
    body = await req.json();
  } catch {
    return Response.json({ ok: false }, { status: 400 });
  }
  // A filled honeypot is a bot: answer as if it worked, store nothing.
  if (typeof body.website === "string" && body.website !== "") return Response.json({ ok: true });
  if (typeof body.email !== "string" || typeof body.consent?.text !== "string" || !body.consent.text.trim() || !body.criteria || typeof body.criteria !== "object") {
    return Response.json({ ok: false }, { status: 400 });
  }
  const frequency = FREQUENCIES.includes(body.frequency as AlertFrequency) ? (body.frequency as AlertFrequency) : "instant";
  const r = await idx.alerts.buyers.create({
    email: body.email,
    firstName: typeof body.firstName === "string" && body.firstName ? body.firstName : undefined,
    consent: {
      text: body.consent.text,
      source: typeof body.consent.source === "string" ? body.consent.source : undefined,
      ip: req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || undefined,
    },
    search: { criteria: body.criteria as AlertCriteria, frequency, name: typeof body.searchName === "string" && body.searchName ? body.searchName : undefined },
  });
  if (!r.ok) return Response.json({ ok: false, message: r.error.message }, { status: r.status === 0 ? 502 : r.status });
  return Response.json({ ok: true });
}
```

## What happens next

The buyer gets a welcome alert with up to four matching homes, then alerts as listings change.
Your server receives each alert by webhook and sends it through your email provider:
[Send alerts through your own email provider](/idx/alerts-send-it-yourself).

## Rules

- Store the exact consent words the visitor saw; the form sends them with the request.
- Keep the secret key on your server: the form posts to your route, never to the API.
- Every alert links back to your [manage-alerts page](/idx/recipe-manage-alerts).
