# Sierra Interactive

Source: https://help.ruuster.com/idx/crm-sierra

> Send registrations, tour requests and questions from your site to Sierra Interactive as new leads with the lead type, the agent, the listing viewed, the campaign and the visit, with the exact route, request and headers, and a test lead you can find in Sierra.

Your site sends each form to Sierra Interactive as a new lead on
`POST https://api.sierrainteractivedev.com/leads`. The lead carries the visitor's name, email and
phone, your site as the source, the AI Nurture tags when the visitor asked for alerts, and a note
with the request: the tour time, the visitor's message, the listing and the consent sentence.

## What you need

- Your Sierra Interactive API key. Sierra sends it in the `Sierra-ApiKey` header on every request.
- Your site's name for `SITE_NAME`, and your site's origin for `SITE_ORIGIN`.

## Steps

1. Add these lines to `.env.local` in your site's folder (and to your host's environment for
   production). Keep them on your server.

   ```sh
   SIERRA_API_KEY=your-sierra-api-key
   SITE_NAME=Peach Realty
   SITE_ORIGIN=https://www.peachrealty.com
   ```

2. Add the route file below at `app/api/leads/sierra/route.ts`, and `lib/crm.ts` from the examples
   repo beside your other `lib` files.
3. Point your forms at it: `action="/api/leads/sierra"` on `RegistrationForm`, `TourForm` and
   `ContactForm` (in the examples, set `LEADS_ACTION` in `lib/site.ts` to `"/api/leads/sierra"`).
4. Ask for an email on every form. Sierra Interactive creates every lead from an email address, so
   the route answers a visitor who left only a phone number with "Please enter your email address."
5. Write your two consent sentences (below) and pass them to each form.
6. Run the test below and find the lead in Sierra Interactive.

## The route

<p class="code-title"><code>app/api/leads/sierra/route.ts</code></p>

```ts
// POST /api/leads/sierra: the registration, tour and contact forms post here. lib/crm.ts does the work.
import { idx } from "@/lib/idx";
import { handleLead } from "@/lib/crm";

export const runtime = "nodejs";

export async function POST(request: Request): Promise<Response> {
  return handleLead(request, "sierra", {
    env: process.env,
    getListing: async (listingId) => {
      const r = await idx.get(listingId);
      return r.ok ? r.data : null;
    },
  });
}
```

`lib/crm.ts` does the work for all three CRMs. This is the handler the route calls:

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

```ts
/**
 * POST /api/leads/{fub|sierra|suresend}: check the origin and the form, look up the listing, build
 * the CRM payload and send it. Answers { ok: true } or { ok: false, error } with a sentence the form
 * shows: 400 unreadable, 403 another site, 422 missing contact or consent, 429 the CRM asked us to
 * wait, 500 not set up, 502 the CRM refused.
 */
export async function handleLead(request: Request, crm: CrmName, deps: CrmDeps): Promise<Response> {
  const env = deps.env;
  if (!sameOrigin(request, env.SITE_ORIGIN)) return fail(403, MESSAGES.wrongOrigin);
  let lead: LeadSubmission | null = null;
  try {
    lead = parseLead(await request.json());
  } catch {
    lead = null;
  }
  if (!lead) return fail(400, MESSAGES.unreadable);
  try {
    assertSendable(lead);
  } catch (err) {
    if (err instanceof LeadRejected) {
      // A filled honeypot is a bot: answer as if it worked and send nothing.
      if (err.reason === "honeypot") return json(200, { ok: true, message: MESSAGES.sent });
      return fail(422, err.message);
    }
    throw err;
  }
  if (crm === "sierra" && !lead.email) return fail(422, MESSAGES.sierraNeedsEmail);

  const source = env.SITE_NAME ?? "";
  const listing = lead.listing ? await deps.getListing(lead.listing.id).catch(() => null) : null;
  const listingUrl = ownUrl(lead.listing?.url, env.SITE_ORIGIN);
  const init = { fetch: deps.fetch };

  try {
    if (crm === "fub") {
      const creds = { apiKey: env.FUB_API_KEY ?? "", system: env.FUB_SYSTEM ?? "", systemKey: env.FUB_SYSTEM_KEY ?? "" };
      const event = fub.eventFromLead(lead, { source, listing, listingUrl });
      const result = await fub.sendEvent(event, creds, init);
      // Remember who registered, so their listing views can follow (app/api/activity/fub).
      const secret = env.FUB_COOKIE_SECRET;
      const cookie: Record<string, string> =
        result.ok && result.id && secret ? { "Set-Cookie": personCookie(result.id, env.SITE_ORIGIN ?? "", secret) } : {};
      return answer(result, cookie);
    }
    const now = (deps.now ?? (() => new Date()))();
    if (crm === "sierra") {
      const creds = { apiKey: env.SIERRA_API_KEY ?? "" };
      const body = sierra.leadFromSubmission(lead, { source, listing, listingUrl });
      const result = await sierra.createLead(body, creds, init);
      // Then the visit that brought the lead. A failed visit doesn't undo the lead: log it and answer the form.
      const visit = result.ok && result.id ? sierra.siteVisitFromSubmission(lead, now) : null;
      if (result.ok && result.id && visit) {
        const v = await sierra.addSiteVisit(result.id, visit, creds, init);
        if (!v.ok) console.error(`Sierra site visit not added (${v.status}): ${v.error}`);
      }
      return answer(result);
    }
    // Put one of your Sure Send person stage names here (for example the stage new website leads start in), or leave it null.
    const SURESEND_STAGE: string | null = null;
    const creds = { apiKey: env.SURESEND_API_KEY ?? "" };
    const person = suresend.personFromSubmission(lead, { source, listing, listingUrl, stage: SURESEND_STAGE });
    const result = await suresend.createPerson(person, creds, init);
    // Then the request as a note on the person. A failed note doesn't undo the person: log it and answer the form.
    if (result.ok && result.id) {
      const n = await suresend.createNote(suresend.noteFromSubmission(lead, result.id, { source, listing, listingUrl }), creds, init);
      if (!n.ok) console.error(`Sure Send note not added (${n.status}): ${n.error}`);
    }
    return answer(result);
  } catch (err) {
    // A missing key or SITE_NAME throws before any call. Say so in your log, and give the visitor a plain answer.
    console.error(`CRM route not set up: ${err instanceof Error ? err.message : String(err)}`);
    return fail(500, MESSAGES.notSetUp);
  }
}
```

## Without Next.js

The plain HTTP example does the same work with no packages, so you can port it to PHP, Python, Ruby
or Go. Its server answers `POST /api/leads/sierra` and reads your Sierra Interactive key from the server's
environment. Copy `leads.mjs` from `examples/idx-plain-http` beside your server, and route the
request to it:

<p class="code-title"><code>server.mjs</code></p>

```js
/** Reads a JSON request body of at most 64 KB. Null when it is too big or isn't JSON. */
async function readJson(req) {
  let size = 0;
  const chunks = [];
  for await (const chunk of req) {
    size += chunk.length;
    if (size > 65_536) return null;
    chunks.push(chunk);
  }
  try {
    return JSON.parse(Buffer.concat(chunks).toString("utf8"));
  } catch {
    return null;
  }
}

/** The listing a form or a view was about, from the API (null when it is gone or the call failed). */
async function getListing(listingId) {
  const r = await api(`/listings/${encodeURIComponent(listingId)}`, {});
  return r.status === 200 ? r.body.data : null;
}

function sendJson(res, out) {
  res.writeHead(out.status, { "Content-Type": "application/json", "Cache-Control": "no-store", ...out.headers });
  res.end(JSON.stringify(out.body));
}

/** POST /api/leads/<crm> and POST /api/activity/fub. Your CRM keys are read from this server's environment. */
async function leadRoute(req, res, pathname) {
  const deps = { env: process.env, getListing };
  const lead = /^\/api\/leads\/(fub|sierra|suresend)$/.exec(pathname);
  if (lead) return sendJson(res, await handleLead({ origin: req.headers.origin, body: await readJson(req) }, lead[1], deps));
  return sendJson(res, await handleFubActivity({ origin: req.headers.origin, cookie: req.headers.cookie, body: await readJson(req) }, deps));
}
```

The handler checks the origin, the honeypot and the consent box, looks up the listing, and sends
the same request as the Next.js route. A listing with a hidden address sends no street.

<p class="code-title"><code>leads.mjs</code></p>

```js
/**
 * POST /api/leads/{fub|sierra|suresend}. `request` is { origin, body } (body already parsed from JSON,
 * or null when it wasn't JSON). `deps` is { env, getListing(id), fetch }. Answers { status, body, headers }.
 */
export async function handleLead(request, crm, deps) {
  const env = deps.env;
  if (!sameOrigin(request.origin, env.SITE_ORIGIN)) return fail(403, MESSAGES.wrongOrigin);
  const lead = parseLead(request.body);
  if (!lead) return fail(400, MESSAGES.unreadable);
  const problem = leadProblem(lead);
  // A filled honeypot is a bot: answer as if it worked and send nothing.
  if (problem === "honeypot") return answer(200, { ok: true, message: MESSAGES.sent });
  if (problem) return fail(422, problem);
  if (crm === "sierra" && !lead.email) return fail(422, MESSAGES.sierraNeedsEmail);

  const listing = lead.listing ? await deps.getListing(lead.listing.id).catch(() => null) : null;
  const listingUrl = ownUrl(lead.listing?.url, env.SITE_ORIGIN);
  const opts = { source: env.SITE_NAME, listing, listingUrl };
  try {
    if (crm === "fub") {
      const result = await sendToCrm("fub", fubEvent(lead, opts), env, deps.fetch);
      // Remember who registered, so their listing views can follow (POST /api/activity/fub).
      const secret = env.FUB_COOKIE_SECRET;
      const secure = (env.SITE_ORIGIN ?? "").startsWith("https://") ? "; Secure" : "";
      const headers = result.ok && result.id && secret ? { "Set-Cookie": `${FUB_PERSON_COOKIE}=${signPersonId(result.id, secret)}; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}` } : {};
      return crmAnswer(result, headers);
    }
    const now = (deps.now ?? (() => new Date()))();
    if (crm === "sierra") {
      const result = await sendToCrm("sierra", sierraLead(lead, opts), env, deps.fetch);
      // Then the visit that brought the lead. A failed visit doesn't undo the lead: log it and answer the form.
      const visit = result.ok && result.id ? sierraSiteVisit(lead, now) : null;
      if (visit) {
        const v = await sendToCrm("sierra", visit, env, deps.fetch, `${SIERRA_LEADS_URL}/${encodeURIComponent(result.id)}/siteVisit`);
        if (!v.ok) console.error(`Sierra site visit not added (${v.status}): ${v.error}`);
      }
      return crmAnswer(result);
    }
    // Put one of your Sure Send person stage names here, or leave it null.
    const SURESEND_STAGE = null;
    const result = await sendToCrm("suresend", sureSendPerson(lead, { source: env.SITE_NAME, stage: SURESEND_STAGE }), env, deps.fetch);
    // Then the request as a note on the person. A failed note doesn't undo the person: log it and answer the form.
    if (result.ok && result.id) {
      const n = await sendToCrm("suresend", sureSendNote(lead, result.id, opts), env, deps.fetch, SURESEND_NOTES_URL);
      if (!n.ok) console.error(`Sure Send note not added (${n.status}): ${n.error}`);
    }
    return crmAnswer(result);
  } catch (err) {
    // A missing key or SITE_NAME throws before any call. Say so in your log, and give the visitor a plain answer.
    console.error(`CRM route not set up: ${err instanceof Error ? err.message : String(err)}`);
    return fail(500, MESSAGES.notSetUp);
  }
}
```

## The lead each form sends

| Field | What it holds |
|---|---|
| `email` | The visitor's email |
| `password` | A random password for the lead's account on your Sierra site, which Sierra requires; the visitor can reset it from your Sierra site |
| `source` | Your `SITE_NAME` |
| `sourceType` | `IDX`. Pass `sourceType` to `sierra.leadFromSubmission` for another of Sierra's types |
| `firstName`, `lastName`, `phone` | As the visitor typed them |
| `tags` | `Ruuster` and `Ruuster Default Search`, only when the alerts box is checked |
| `leadType` | `1` buyer, `2` seller, `3` both, when the form says (`leadType` on the form). Left out, Sierra makes the lead a buyer |
| `assignTo` | `agentUserId` and `agentUserEmail` when the form names an agent (`agent` on the form). Left out, Sierra's own routing assigns the lead |
| `note` | The request in plain words, one line each, added to the lead's history as a note: the tour time, the message, the listing, your page, the consent sentence, then where the visitor came from (the campaign, ad click ids, landing page, referrer, and their first and latest visit) |
| `session.propertyViews` | The listing the form was about, by MLS number, with your own page for it as `partnerLink`. Sierra matches it in its own MLS feed |

After Sierra creates the lead, the route adds the visit that brought it with
`POST /leads/{leadId}/siteVisit`: `url` is the first page of the visit, `visitDateTime` is when the
form was sent, and `referrer` is the outside page the visit came from (left out when there is none).
A failed visit goes to your server log; the lead is already in Sierra and the form still answers
`{ "ok": true }`.

The headers are `Sierra-ApiKey`, `Content-Type: application/json` and
`Sierra-OriginatingSystemName`, which the route sets to your `SITE_NAME` (Sierra takes up to 50
characters).

A visitor first came from a Facebook ad in October, came back from a Google ad in November, and asked for a tour. The form named the listing agent. Here is the tour request exactly as the route sends it (the password is random on each lead):

```json
{
  "email": "jamie@example.com",
  "password": "Xq3v9TzM2bL8kR1pW7nA4cYe",
  "source": "Peach Realty",
  "sourceType": "IDX",
  "firstName": "Jamie",
  "lastName": "Rivera",
  "phone": "404-555-0100",
  "leadType": 1,
  "assignTo": {
    "agentUserId": 12,
    "agentUserEmail": "pat@peachrealty.com"
  },
  "note": "Requested a tour: 2026-11-08, Morning.\nMessage: Is Saturday morning open?\nListing: 123 Peachtree St, Atlanta, GA 30308, MLS# 7412345, $525,000.\nListing page: https://www.peachrealty.com/homes/123-peachtree-st-atlanta-ga-30308-3f2c1a4e\nSent from: https://www.peachrealty.com/homes/123-peachtree-st-atlanta-ga-30308-3f2c1a4e\nConsent given: I agree that Peach Realty may contact me by phone, text or email about this request.\nCampaign: utm_source google, utm_medium cpc, utm_campaign atlanta-buyers.\nAd click ids: gclid Cj0KCQiA.\nLanded on: https://www.peachrealty.com/atlanta?utm_source=google&utm_medium=cpc&utm_campaign=atlanta-buyers&gclid=Cj0KCQiA\nCame from: https://www.google.com/\nFirst visit: utm_source facebook, utm_medium paid_social, utm_campaign fall-open-houses, fbclid IwAR2x; landed on https://www.peachrealty.com/?utm_source=facebook&utm_medium=paid_social&utm_campaign=fall-open-houses&fbclid=IwAR2x, from https://www.facebook.com/, on 2026-10-03.\nLatest visit: utm_source google, utm_medium cpc, utm_campaign atlanta-buyers, gclid Cj0KCQiA; landed on https://www.peachrealty.com/atlanta?utm_source=google&utm_medium=cpc&utm_campaign=atlanta-buyers&gclid=Cj0KCQiA, from https://www.google.com/, on 2026-11-05.",
  "session": {
    "propertyViews": [
      {
        "mlsNumber": "7412345",
        "partnerLink": "https://www.peachrealty.com/homes/123-peachtree-st-atlanta-ga-30308-3f2c1a4e"
      }
    ]
  }
}
```

And the site visit that follows it, to `POST /leads/{leadId}/siteVisit`:

```json
{
  "url": "https://www.peachrealty.com/atlanta?utm_source=google&utm_medium=cpc&utm_campaign=atlanta-buyers&gclid=Cj0KCQiA",
  "visitDateTime": "2026-11-05T14:09:31.000Z",
  "referrer": "https://www.google.com/"
}
```

When the listing's address is hidden, the note names the city, state, ZIP and MLS number and leaves
the street out.

Sierra answers `"success": true` with the new lead's id in `data.leadId`, and the route answers the
form `{ "ok": true }`. When Sierra answers `"success": false`, the route writes Sierra's
`errorMessage` to your server log and tells the visitor to try again in a minute.

## The consent box text you supply

Write these in your own words and have them reviewed for your market. Two sentences to start from:

- Contact box: "I agree that Peach Realty may contact me by phone, text or email about this request."
- Alerts box: "Email me new listings like this one. I can unsubscribe at any time."

## Send a test lead and find it in Sierra Interactive

From the `examples/idx-plain-http` folder, with the two values in your shell:

```sh
SIERRA_API_KEY=... SITE_NAME="Peach Realty" node crm/sierra.mjs
```

The script prints `Sent. Sierra Interactive answered 200.` with the new lead's id and the email it
used (a new `test.lead+…@example.com` address on each run). In Sierra Interactive, open your
**Leads** and search for that email. Open the lead: the source is your `SITE_NAME`, the source type
is IDX, and the note says "Registered on the website." Delete the test lead when you are done. Then fill in your own
site's registration form on `localhost` and check that a second lead appears the same way.

Add `--dry-run` to print the request without sending it.

<p class="code-title"><code>crm/sierra.mjs</code></p>

```js
// Sends one test lead to your Sierra Interactive site, with no dependencies (Node 18 or later).
//
// Run it from the examples/idx-plain-http folder:
//   SIERRA_API_KEY=... SITE_NAME="Your Brokerage" node crm/sierra.mjs
// Add --dry-run to print the request without sending it.
// Then open Leads in Sierra Interactive and look for "Test Lead".
import { randomBytes } from "node:crypto";
import { pathToFileURL } from "node:url";

export const SIERRA_LEADS_URL = "https://api.sierrainteractivedev.com/leads";

/**
 * The same lead the Next.js route sends for a registration form without the alerts box. Sierra
 * requires a password for the lead's site account, so the route sends a random one.
 */
export function testLead(siteName, email, pageUrl, password = randomBytes(18).toString("base64url")) {
  return {
    email,
    password,
    source: siteName,
    sourceType: "IDX",
    firstName: "Test",
    lastName: "Lead",
    note: [
      "Registered on the website.",
      `Sent from: ${pageUrl}`,
      `Consent given: I agree that ${siteName} may contact me by phone, text or email about this request.`,
    ].join("\n"),
  };
}

export function sierraHeaders(apiKey, siteName) {
  return {
    "Sierra-ApiKey": apiKey,
    "Content-Type": "application/json",
    "Sierra-OriginatingSystemName": siteName.slice(0, 50),
  };
}

async function main() {
  const { SIERRA_API_KEY, SITE_NAME, SITE_ORIGIN } = process.env;
  if (!SIERRA_API_KEY || !SITE_NAME) {
    console.error("Set SIERRA_API_KEY and SITE_NAME first.");
    process.exit(1);
  }
  if (/^(app|ruuster)$/i.test(SITE_NAME.trim())) {
    console.error("Set SITE_NAME to your own site's name. It is the lead source Sierra Interactive shows.");
    process.exit(1);
  }
  const email = process.env.TEST_LEAD_EMAIL || `test.lead+${Date.now()}@example.com`;
  const lead = testLead(SITE_NAME.trim(), email, `${SITE_ORIGIN || "https://www.example.com"}/register`);
  if (process.argv.includes("--dry-run")) {
    console.log(`POST ${SIERRA_LEADS_URL}`);
    console.log(JSON.stringify({ ...lead, password: "(random)" }, null, 2));
    return;
  }
  const res = await fetch(SIERRA_LEADS_URL, { method: "POST", headers: sierraHeaders(SIERRA_API_KEY, SITE_NAME.trim()), body: JSON.stringify(lead) });
  const text = await res.text();
  let body = {};
  try {
    body = text ? JSON.parse(text) : {};
  } catch {
    body = {};
  }
  if (res.ok && body.success !== false) {
    console.log(`Sent. Sierra Interactive answered ${res.status}. Lead id ${body.data?.leadId ?? "(none)"}, email ${email}.`);
  } else if (res.status === 429) {
    console.log(`Sierra Interactive asked us to wait ${res.headers.get("Retry-After") ?? "a few"} seconds. Run the script again after that.`);
  } else {
    console.log(`Sierra Interactive answered ${res.status}: ${body.errorMessage ?? text.slice(0, 300)}`);
    process.exitCode = 1;
  }
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();
```

The same request with cURL:

<p class="code-title"><code>crm/sierra.sh</code></p>

```bash
# Sends one test lead to Sierra Interactive. Set SIERRA_API_KEY and SITE_NAME first.
# SITE_ORIGIN is optional; it fills in the "Sent from" line.
# Sierra requires a password for the lead's site account, so this sends a random one.
case "$SITE_NAME" in
  "" | [Rr]uuster | [Aa]pp) echo "Set SITE_NAME to your own site's name. It is the lead source Sierra Interactive shows."; exit 1;;
esac
PAGE_URL="${SITE_ORIGIN:-https://www.example.com}/register"
curl -s -X POST "https://api.sierrainteractivedev.com/leads" \
  -H "Sierra-ApiKey: $SIERRA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Sierra-OriginatingSystemName: $SITE_NAME" \
  -d '{
    "email": "test.lead@example.com",
    "password": "'"$(openssl rand -hex 16)"'",
    "source": "'"$SITE_NAME"'",
    "sourceType": "IDX",
    "firstName": "Test",
    "lastName": "Lead",
    "note": "Registered on the website.\nSent from: '"$PAGE_URL"'\nConsent given: I agree that '"$SITE_NAME"' may contact me by phone, text or email about this request."
  }'
```

## What Ruuster does with it

When your Sierra Interactive site is connected to Ruuster:

- Ruuster reads your leads with your key, including their tags, saved searches and notes, so your
  Ruuster team can answer questions about a lead from your site.
- Ruuster counts the leads each of your agents holds in Sierra, so a lead that stops arriving shows
  up early.
- The AI Nurture tags start listing alerts for the lead (see
  [AI Nurture tags](https://help.ruuster.com/idx/crm-ai-nurture)).
