# Sure Send

Source: https://help.ruuster.com/idx/crm-sure-send

> Send registrations, tour requests and questions from your site to Sure Send as people with tags, a stage, the agent and a note with the request and the campaign, with the exact route, request and headers, and a test lead you can find in Sure Send.

Your site sends each form to Sure Send as a person on `POST https://api.suresend.ai/api/partner/people`.
Sure Send matches people by email: a visitor it already has comes back as that person, and a new
visitor becomes a new person with your site as the source, your stage, and the AI Nurture tags when
they asked for alerts.

## What you need

- A Sure Send API token. Create one in Sure Send under **Settings > API Tokens**. Sure Send sends it
  as `Authorization: Bearer <token>`.
- Your site's name for `SITE_NAME`, and your site's origin for `SITE_ORIGIN`.
- Optional: the name of the person stage new website leads should start in, exactly as Sure Send
  shows it.

## 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
   SURESEND_API_KEY=your-sure-send-api-token
   SITE_NAME=Peach Realty
   SITE_ORIGIN=https://www.peachrealty.com
   ```

2. Add the route file below at `app/api/leads/suresend/route.ts`, and `lib/crm.ts` from the examples
   repo beside your other `lib` files.
3. To start new leads in a stage, set `SURESEND_STAGE` in `handleLead` (in `lib/crm.ts`) to that
   stage's name, for example `"New Lead"`. Leave it `null` to send the person without a stage.
4. Point your forms at it: `action="/api/leads/suresend"` on `RegistrationForm`, `TourForm` and
   `ContactForm` (in the examples, set `LEADS_ACTION` in `lib/site.ts` to `"/api/leads/suresend"`).
5. Write your two consent sentences (below) and pass them to each form.
6. Run the test below and find the person in Sure Send.

## The route

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

```ts
// POST /api/leads/suresend: 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, "suresend", {
    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/suresend` and reads your Sure Send 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 person each form sends

| Field | What it holds |
|---|---|
| `source` | Your `SITE_NAME` |
| `firstName`, `lastName` | As the visitor typed them |
| `emails` | `[{ "value": "…" }]` when the visitor gave an email |
| `phones` | `[{ "value": "…" }]` when the visitor gave a phone number |
| `tags` | `Ruuster` and `Ruuster Default Search`, only when the alerts box is checked; Sure Send creates a tag it does not have yet |
| `stage` | Your `SURESEND_STAGE`, when you set one |
| `assignedUserId` | The agent's Sure Send user id, when the form names one (`agent` on the form). Sure Send assigns by user id only. With an agent set, Sure Send skips its Lead Flow; left out, Lead Flow assigns the person |

Then the route adds a note to that person with `POST /api/partner/notes`: `personId`, a `subject`
such as "Tour request from Peach Realty", and a `body` with the request in plain words, one line
each: 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). A failed note goes to your server log; the person is already in Sure Send and the form still
answers `{ "ok": true }`.

A visitor can leave an email, a phone number or both; Sure Send needs at least one. Here is a tour
request exactly as the route sends it, with a stage and an agent set:

```json
{
  "source": "Peach Realty",
  "firstName": "Jamie",
  "lastName": "Rivera",
  "emails": [{ "value": "jamie@example.com" }],
  "phones": [{ "value": "404-555-0100" }],
  "stage": "New Lead",
  "assignedUserId": "0b7f3c52-6a1d-4e8b-9c2f-5d4e3a2b1c0d"
}
```

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. The note that follows:

```json
{
  "personId": "8d2e4f10-3b5c-4a7d-9e1f-2c6b8a0d4e3f",
  "subject": "Tour request from Peach Realty",
  "body": "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."
}
```

Sure Send answers 201 with the person, and the route answers the form `{ "ok": true }`. When Sure
Send answers 429 (too many requests) or 409 (the same request a moment ago), it says how many
seconds to wait in `Retry-After`; the route passes that on and the form asks the visitor to try
again shortly.

## 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 Sure Send

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

```sh
SURESEND_API_KEY=... SITE_NAME="Peach Realty" node crm/suresend.mjs
```

The script prints `Sent. Sure Send answered 201.` with the person's id and the email it used. In Sure
Send, open **People** and search for that email. Open the person: the source is your `SITE_NAME`.
Delete the test person when you are done. Then fill in your own site's registration form on
`localhost` and check that a second person appears the same way.

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

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

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

export const SURESEND_PEOPLE_URL = "https://api.suresend.ai/api/partner/people";

/** The same person the Next.js route sends for a registration form without the alerts box. */
export function testPerson(siteName, email) {
  return {
    source: siteName,
    firstName: "Test",
    lastName: "Lead",
    emails: [{ value: email }],
  };
}

export function sureSendHeaders(apiKey) {
  return { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" };
}

async function main() {
  const { SURESEND_API_KEY, SITE_NAME } = process.env;
  if (!SURESEND_API_KEY || !SITE_NAME) {
    console.error("Set SURESEND_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 Sure Send shows.");
    process.exit(1);
  }
  const email = process.env.TEST_LEAD_EMAIL || `test.lead+${Date.now()}@example.com`;
  const person = testPerson(SITE_NAME.trim(), email);
  if (process.argv.includes("--dry-run")) {
    console.log(`POST ${SURESEND_PEOPLE_URL}`);
    console.log(JSON.stringify(person, null, 2));
    return;
  }
  const res = await fetch(SURESEND_PEOPLE_URL, { method: "POST", headers: sureSendHeaders(SURESEND_API_KEY), body: JSON.stringify(person) });
  const text = await res.text();
  if (res.ok) {
    const body = text ? JSON.parse(text) : {};
    console.log(`Sent. Sure Send answered ${res.status}. Person id ${body.id ?? "(none)"}, email ${email}.`);
  } else if (res.status === 429 || res.status === 409) {
    console.log(`Sure Send asked us to wait ${res.headers.get("Retry-After") ?? "a few"} seconds. Run the script again after that.`);
  } else {
    console.log(`Sure Send answered ${res.status}: ${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/suresend.sh</code></p>

```bash
# Sends one test person to Sure Send. Set SURESEND_API_KEY and SITE_NAME first.
case "$SITE_NAME" in
  "" | [Rr]uuster | [Aa]pp) echo "Set SITE_NAME to your own site's name. It is the lead source Sure Send shows."; exit 1;;
esac
curl -s -X POST "https://api.suresend.ai/api/partner/people" \
  -H "Authorization: Bearer $SURESEND_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "source": "'"$SITE_NAME"'",
    "firstName": "Test",
    "lastName": "Lead",
    "emails": [{ "value": "test.lead@example.com" }]
  }'
```

## What Ruuster does with it

When your Sure Send account is connected to Ruuster:

- Ruuster reads your people with your token, including their stage, tags, events and notes, so your
  Ruuster team can answer questions about a lead from your site.
- Ruuster keeps an hourly copy of your calls, texts, emails and appointments, so a lead's last
  contact is known.
- Ruuster follows the people in your in-progress stages, such as showing, offer and under contract.
- The AI Nurture tags start listing alerts for the person (see
  [AI Nurture tags](https://help.ruuster.com/idx/crm-ai-nurture)).
