# Follow Up Boss

Source: https://help.ruuster.com/idx/crm-follow-up-boss

> Send registrations, tour requests, questions and listing views from your site to Follow Up Boss as events, with the exact route, request, headers and a test lead you can find in Follow Up Boss in a few minutes.

Your site sends each form to Follow Up Boss as one event on `POST https://api.followupboss.com/v1/events`.
Follow Up Boss creates the person, or adds the event to the person it already has with that email or
phone, and runs your lead flow for your site's source.

## What you need

- Your Follow Up Boss API key (Follow Up Boss uses it as the user name for HTTP Basic sign-in, with
  a blank password).
- A registered system name and system key. Register your site once with Follow Up Boss's system
  registration form at `https://apps.followupboss.com/system-registration`. Follow Up Boss asks every
  integration to send them on every request as `X-System` and `X-System-Key`.
- 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; none of them starts with `NEXT_PUBLIC_`.

   ```sh
   FUB_API_KEY=your-follow-up-boss-api-key
   FUB_SYSTEM=YourSiteSystemName
   FUB_SYSTEM_KEY=your-system-key
   FUB_COOKIE_SECRET=a-long-random-string
   SITE_NAME=Peach Realty
   SITE_ORIGIN=https://www.peachrealty.com
   ```

2. Add the route file below at `app/api/leads/fub/route.ts`, and `lib/crm.ts` from the examples
   repo beside your other `lib` files.
3. Point your forms at it: `action="/api/leads/fub"` on `RegistrationForm`, `TourForm` and
   `ContactForm` (the examples set `LEADS_ACTION` in `lib/site.ts`).
4. Write your two consent sentences (below) and pass them to each form.
5. Add the listing-view route and `ReportListingView` to your listing page (below) if you want
   Follow Up Boss to see what registered visitors look at.
6. Run the test below and find the lead in Follow Up Boss.
7. If your brokerage is also on the Ruuster Platform with Follow Up Boss connected to Ruuster, email
   `helpme@ruuster.com` before you launch to confirm the connection is ready for website events. A
   Listings API account on its own skips this step.

## The route

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

```ts
// POST /api/leads/fub: 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, "fub", {
    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);
  }
}
```

These are the sentences the form shows for each answer:

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

```ts
/** What the form shows. Every answer is a full sentence. */
export const MESSAGES = {
  sent: "Thanks. We got your request and will be in touch soon.",
  wrongOrigin: "Please send this form from our website.",
  unreadable: "We couldn't read this form. Please refresh the page and try again.",
  notSetUp: "This form isn't set up yet. Please call or email us instead.",
  failed: "We couldn't send your request just now. Please try again in a minute.",
  busy: (sec: number | null) => `We're getting a lot of requests right now. Please try again in ${sec && sec > 0 ? `${sec} seconds` : "a minute"}.`,
  sierraNeedsEmail: "Please enter your email address.",
} as const;
```

## 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/fub` and reads your Follow Up Boss 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);
  }
}
```

For listing views, the same server answers `POST /api/activity/fub` with this handler. It sends a
view only for a signed `fub_person` cookie, and it needs `FUB_COOKIE_SECRET` like the Next.js route:

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

```js
/**
 * POST /api/activity/fub with { listingId, url }: sends "Viewed Property" for a visitor whose signed
 * fub_person cookie checks out, at most once per person, listing and day. `request` is
 * { origin, cookie, body }. Anonymous visitors send nothing: { ok: true, sent: false }.
 */
export async function handleFubActivity(request, deps, dedupe = viewedToday) {
  const env = deps.env;
  if (!sameOrigin(request.origin, env.SITE_ORIGIN)) return fail(403, MESSAGES.wrongOrigin);
  const body = request.body && typeof request.body === "object" ? request.body : null;
  const listingId = body ? str(body.listingId, 100) : "";
  if (!listingId) return fail(400, MESSAGES.unreadable);
  const personId = verifyPersonId(cookieValue(request.cookie, FUB_PERSON_COOKIE), env.FUB_COOKIE_SECRET);
  if (!personId) return answer(200, { ok: true, sent: false });
  const now = (deps.now ?? (() => new Date()))();
  if (!dedupe.firstToday(personId, listingId, now)) return answer(200, { ok: true, sent: false });

  const listing = await deps.getListing(listingId).catch(() => null);
  if (!listing) {
    dedupe.forget(personId, listingId, now);
    return answer(200, { ok: true, sent: false });
  }
  try {
    const event = fubViewedProperty(personId, listing, { source: env.SITE_NAME, listingUrl: ownUrl(str(body.url, 1000), env.SITE_ORIGIN) });
    const result = await sendToCrm("fub", event, env, deps.fetch);
    if (result.ok) return answer(200, { ok: true, sent: true });
    dedupe.forget(personId, listingId, now);
    return crmAnswer(result);
  } catch (err) {
    dedupe.forget(personId, listingId, now);
    console.error(`CRM route not set up: ${err instanceof Error ? err.message : String(err)}`);
    return fail(500, MESSAGES.notSetUp);
  }
}
```

## The event each form sends

| Form | `type` | What else is in the event |
|---|---|---|
| `RegistrationForm` | `Registration` | `person`, and the AI Nurture tags when the alerts box is checked |
| `TourForm` | `Property Inquiry` | `person`, `property`, the tour time in `description`, the visitor's words in `message` |
| `ContactForm` on a listing | `Property Inquiry` | `person`, `property`, `message`, `description` |
| `ContactForm` without a listing | `General Inquiry` | `person`, `message`, `description` |
| `ContactForm` for a seller, without a listing (`leadType="seller"`) | `Seller Inquiry` | `person`, `message`, `description` |
| A registered visitor opens a listing | `Viewed Property` | `person.id`, `property` |

The fields:

- `source`: your `SITE_NAME`.
- `person`: `firstName`, `lastName`, `emails` as `[{ "value": "…" }]`, `phones` as
  `[{ "value": "…" }]`, `tags`, and `sourceUrl`, the page the form was sent from (Follow Up Boss
  keeps it from the person's first event). When the form names an agent (`agent` on the form),
  `assignedUserId` carries their Follow Up Boss user id, or `assignedTo` their full name when there
  is no id. Follow Up Boss can't assign by email. Left out, your lead flow assigns the person.
- `property`: `street`, `city`, `state`, `code` (the ZIP), `mlsNumber` and `price`, plus `url` (your
  page for the listing), `forRent`, `type`, `bedrooms`, `bathrooms`, `area` (square feet) and `lot`
  (acres). The price is the current price, or the sold price on a sold listing; it is left out
  rather than sent as 0. When the listing's address is hidden, `street` is left out and the rest
  stays.
- `campaign`: `source`, `medium`, `campaign`, `term` and `content` from the visit's UTM values. A
  visit with an ad click id and no `utm_source` gets `google` (gclid), `bing` (msclkid) or
  `facebook` (fbclid) as the source. Left out when the visit had neither.
- `pageUrl`: the page the form was sent from. `pageReferrer`: the outside page the visit came from.
- `message`: what the visitor typed.
- `description`: the request in plain words, one line each: the tour time, the listing, your page
  for the listing, the page the form was sent from, the consent sentence the visitor agreed to, then
  where the visitor came from (the campaign, ad click ids, landing page, referrer, and their first
  and latest visit).

`Viewed Property` events are unchanged: `person.id` and the listing's `street`, `city`, `state`,
`code`, `mlsNumber` and `price`.

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:

```json
{
  "source": "Peach Realty",
  "type": "Property Inquiry",
  "message": "Is Saturday morning open?",
  "person": {
    "firstName": "Jamie",
    "lastName": "Rivera",
    "emails": [
      {
        "value": "jamie@example.com"
      }
    ],
    "phones": [
      {
        "value": "404-555-0100"
      }
    ],
    "sourceUrl": "https://www.peachrealty.com/homes/123-peachtree-st-atlanta-ga-30308-3f2c1a4e",
    "assignedUserId": 12
  },
  "property": {
    "street": "123 Peachtree St",
    "city": "Atlanta",
    "state": "GA",
    "code": "30308",
    "mlsNumber": "7412345",
    "price": 525000,
    "forRent": false,
    "url": "https://www.peachrealty.com/homes/123-peachtree-st-atlanta-ga-30308-3f2c1a4e",
    "type": "Single Family Residence",
    "bedrooms": "3",
    "bathrooms": "2.5",
    "area": "1850",
    "lot": "0.21"
  },
  "campaign": {
    "source": "google",
    "medium": "cpc",
    "campaign": "atlanta-buyers"
  },
  "pageUrl": "https://www.peachrealty.com/homes/123-peachtree-st-atlanta-ga-30308-3f2c1a4e",
  "pageReferrer": "https://www.google.com/",
  "description": "Requested a tour: 2026-11-08, Morning.\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."
}
```

Follow Up Boss answers 201 when it created a new person and 200 when it added the event to a person
it already had. The route answers the form `{ "ok": true }` in both cases. When Follow Up Boss
answers 429 it says how many seconds to wait in `Retry-After`; the route passes the 429 and that
header 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 Follow Up Boss

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

```sh
FUB_API_KEY=... FUB_SYSTEM=... FUB_SYSTEM_KEY=... SITE_NAME="Peach Realty" node crm/fub.mjs
```

The script prints `Sent. Follow Up Boss answered 201.` and the new person's id. In Follow Up Boss,
open **People** and search for **Test Lead**. Open the person: the source is your `SITE_NAME`, and the
timeline shows the **Registration** event with the description lines. 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/fub.mjs</code></p>

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

export const FUB_EVENTS_URL = "https://api.followupboss.com/v1/events";

/** The same Registration event the Next.js route sends for a registration form without the alerts box. */
export function testEvent(siteName, email, pageUrl) {
  return {
    source: siteName,
    type: "Registration",
    person: {
      firstName: "Test",
      lastName: "Lead",
      emails: [{ value: email }],
      sourceUrl: pageUrl,
    },
    pageUrl,
    description: [
      "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"),
  };
}

/** HTTP Basic with your API key as the user name and a blank password, plus your registered system headers. */
export function fubHeaders(apiKey, system, systemKey) {
  return {
    Authorization: `Basic ${Buffer.from(`${apiKey}:`).toString("base64")}`,
    "Content-Type": "application/json",
    Accept: "application/json",
    "X-System": system,
    "X-System-Key": systemKey,
  };
}

async function main() {
  const { FUB_API_KEY, FUB_SYSTEM, FUB_SYSTEM_KEY, SITE_NAME, SITE_ORIGIN } = process.env;
  if (!FUB_API_KEY || !FUB_SYSTEM || !FUB_SYSTEM_KEY || !SITE_NAME) {
    console.error("Set FUB_API_KEY, FUB_SYSTEM, FUB_SYSTEM_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 Follow Up Boss shows.");
    process.exit(1);
  }
  const email = process.env.TEST_LEAD_EMAIL || `test.lead+${Date.now()}@example.com`;
  const event = testEvent(SITE_NAME.trim(), email, `${SITE_ORIGIN || "https://www.example.com"}/register`);
  if (process.argv.includes("--dry-run")) {
    console.log(`POST ${FUB_EVENTS_URL}`);
    console.log(JSON.stringify(event, null, 2));
    return;
  }
  const res = await fetch(FUB_EVENTS_URL, { method: "POST", headers: fubHeaders(FUB_API_KEY, FUB_SYSTEM, FUB_SYSTEM_KEY), body: JSON.stringify(event) });
  const text = await res.text();
  if (res.status === 200 || res.status === 201) {
    const person = text ? JSON.parse(text) : {};
    console.log(`Sent. Follow Up Boss answered ${res.status}. Person id ${person.id ?? "(none)"}, email ${email}.`);
  } else if (res.status === 204) {
    console.log("Follow Up Boss ignored the event because the lead flow for this source is archived.");
  } else if (res.status === 429) {
    console.log(`Follow Up Boss asked us to wait ${res.headers.get("Retry-After") ?? "a few"} seconds. Run the script again after that.`);
  } else {
    console.log(`Follow Up Boss 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/fub.sh</code></p>

```bash
# Sends one test Registration to Follow Up Boss. Set FUB_API_KEY, FUB_SYSTEM, FUB_SYSTEM_KEY and SITE_NAME first.
# SITE_ORIGIN is optional; it fills in the "Sent from" line.
case "$SITE_NAME" in
  "" | [Rr]uuster | [Aa]pp) echo "Set SITE_NAME to your own site's name. It is the lead source Follow Up Boss shows."; exit 1;;
esac
PAGE_URL="${SITE_ORIGIN:-https://www.example.com}/register"
curl -s -X POST "https://api.followupboss.com/v1/events" \
  -u "$FUB_API_KEY:" \
  -H "Content-Type: application/json" \
  -H "X-System: $FUB_SYSTEM" \
  -H "X-System-Key: $FUB_SYSTEM_KEY" \
  -d '{
    "source": "'"$SITE_NAME"'",
    "type": "Registration",
    "person": {
      "firstName": "Test",
      "lastName": "Lead",
      "emails": [{ "value": "test.lead@example.com" }],
      "sourceUrl": "'"$PAGE_URL"'"
    },
    "pageUrl": "'"$PAGE_URL"'",
    "description": "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."
  }'
```

## Listing views from registered visitors

When a visitor registers, the route stores the Follow Up Boss person id in an HttpOnly cookie on
your own domain, signed with `FUB_COOKIE_SECRET`. Your listing page then reports each view to your
server. The server checks the signature and sends one `Viewed Property` per person, listing and day.
A cookie that was edited or copied from another site fails the check, and the server sends nothing
for it.

Make the secret once and keep it on your server with your other keys:

```sh
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

Changing the secret signs everyone out of listing views until they register again. Without
`FUB_COOKIE_SECRET`, registrations still reach Follow Up Boss, and listing views are not sent.

Add the route at `app/api/activity/fub/route.ts`:

<p class="code-title"><code>app/api/activity/fub/route.ts</code></p>

```ts
// POST /api/activity/fub: your listing page calls this when a registered visitor opens a listing.
// lib/crm.ts sends one Follow Up Boss "Viewed Property" per person, listing and day.
import { idx } from "@/lib/idx";
import { handleFubActivity } from "@/lib/crm";

export const runtime = "nodejs";

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

Add this component to your listing page, with the listing's id and your page's URL:

<p class="code-title"><code>app/api/activity/fub/report-view.tsx</code></p>

```tsx
"use client";
// Put <ReportListingView listingId={r.data.id} url={pageUrl} /> on your listing page.
// It tells your own server once per page view; app/api/activity/fub/route.ts decides whether to send
// Follow Up Boss a "Viewed Property" (only for a visitor who registered, once per listing and day).
import { useEffect } from "react";

export function ReportListingView({ listingId, url }: { listingId: string; url: string }) {
  useEffect(() => {
    void fetch("/api/activity/fub", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ listingId, url }),
      keepalive: true,
    }).catch(() => undefined);
  }, [listingId, url]);
  return null;
}
```

The handler and its once-a-day rule:

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

```ts
/**
 * The cookie that remembers a registered visitor's Follow Up Boss person id, for Viewed Property events.
 * Its value is `<id>.<signature>`: an HMAC-SHA256 of the id made with FUB_COOKIE_SECRET, a long random
 * string only your server knows. The listing-view route trusts an id only when its signature checks
 * out, so nobody can add views to another person by editing the cookie. Without FUB_COOKIE_SECRET the
 * registration sets no cookie and listing views send nothing.
 */
export const FUB_PERSON_COOKIE = "fub_person";

function signId(id: string, secret: string): string {
  return createHmac("sha256", secret).update(`fub_person:${id}`).digest("hex");
}

/** The cookie value for a person id: `<id>.<signature>`. */
export function signPersonId(id: string, secret: string): string {
  return `${id}.${signId(id, secret)}`;
}

/** The person id in a signed cookie value, or null when it is missing, unsigned or edited. */
export function verifyPersonId(value: string | null, secret: string | undefined): string | null {
  if (!value || !secret) return null;
  const dot = value.indexOf(".");
  if (dot <= 0) return null;
  const id = value.slice(0, dot);
  const sig = value.slice(dot + 1);
  if (!/^\d+$/.test(id) || !/^[0-9a-f]{64}$/.test(sig)) return null;
  const expected = Buffer.from(signId(id, secret), "hex");
  return timingSafeEqual(Buffer.from(sig, "hex"), expected) ? id : null;
}

function personCookie(id: string, siteOrigin: string, secret: string): string {
  const secure = siteOrigin.startsWith("https://") ? "; Secure" : "";
  return `${FUB_PERSON_COOKIE}=${signPersonId(id, secret)}; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax${secure}`;
}
```

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

```ts
/**
 * POST /api/activity/fub with { listingId, url }: sends Follow Up Boss "Viewed Property" for a
 * visitor who registered on this site (the signed fub_person cookie the registration set), at most
 * once per person, listing and day. Anonymous visitors, and a cookie whose signature doesn't check
 * out, send nothing: { ok: true, sent: false }.
 */
export async function handleFubActivity(request: Request, deps: CrmDeps, dedupe: ViewDedupe = viewedToday): Promise<Response> {
  const env = deps.env;
  if (!sameOrigin(request, env.SITE_ORIGIN)) return fail(403, MESSAGES.wrongOrigin);
  let body: Record<string, unknown> | null = null;
  try {
    const parsed: unknown = await request.json();
    body = parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : null;
  } catch {
    body = null;
  }
  const listingId = body ? str(body.listingId, 100) : "";
  if (!listingId) return fail(400, MESSAGES.unreadable);
  const personId = verifyPersonId(cookieValue(request, FUB_PERSON_COOKIE), env.FUB_COOKIE_SECRET);
  if (!personId) return json(200, { ok: true, sent: false });
  const now = (deps.now ?? (() => new Date()))();
  if (!dedupe.firstToday(personId, listingId, now)) return json(200, { ok: true, sent: false });

  const listing = await deps.getListing(listingId).catch(() => null);
  if (!listing) {
    dedupe.forget(personId, listingId, now);
    return json(200, { ok: true, sent: false });
  }
  const listingUrl = ownUrl(body ? str(body.url, 1000) : null, env.SITE_ORIGIN) ?? "";
  try {
    const event = fub.viewedPropertyEvent({ id: personId }, listing, { source: env.SITE_NAME ?? "", listingUrl });
    const creds = { apiKey: env.FUB_API_KEY ?? "", system: env.FUB_SYSTEM ?? "", systemKey: env.FUB_SYSTEM_KEY ?? "" };
    const result = await fub.sendEvent(event, creds, { fetch: deps.fetch });
    if (result.ok) return json(200, { ok: true, sent: true });
    dedupe.forget(personId, listingId, now);
    return answer(result);
  } catch (err) {
    dedupe.forget(personId, listingId, now);
    console.error(`CRM route not set up: ${err instanceof Error ? err.message : String(err)}`);
    return fail(500, MESSAGES.notSetUp);
  }
}
```

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

```ts
/**
 * One Viewed Property per person, listing and day. This keeps the count in memory, which is right
 * for one server process (next start, a single container). On serverless hosts each instance keeps
 * its own count, so a person can get a second event for the same listing on the same day; move this
 * to your own store (Redis, your database) if that matters to you.
 */
export class ViewDedupe {
  private seen = new Map<string, number>();
  constructor(private readonly max = 50_000) {}
  /** True the first time this person, listing and UTC day is seen; false after that. */
  firstToday(personId: string, listingId: string, now: Date): boolean {
    const day = now.toISOString().slice(0, 10);
    const key = `${personId}|${listingId}|${day}`;
    if (this.seen.has(key)) return false;
    if (this.seen.size >= this.max) this.prune(day);
    this.seen.set(key, now.getTime());
    return true;
  }
  /** Undo firstToday after a failed send, so the next view tries again. */
  forget(personId: string, listingId: string, now: Date): void {
    this.seen.delete(`${personId}|${listingId}|${now.toISOString().slice(0, 10)}`);
  }
  private prune(today: string): void {
    for (const k of Array.from(this.seen.keys())) if (!k.endsWith(`|${today}`)) this.seen.delete(k);
    if (this.seen.size >= this.max) this.seen.clear();
  }
}

export const viewedToday = new ViewDedupe();
```

## What Ruuster does with it

When your Follow Up Boss account is connected to Ruuster:

- Ruuster keeps a copy of your Follow Up Boss listing events and refreshes it every 15 minutes.
  `Viewed Property` and `Property Inquiry` events with a city, ZIP or street are placed on the map
  by their address. They count toward
  [Find leads looking in an area](https://help.ruuster.com/api/leads-area-interest), which lists the
  leads who have been looking in a city, ZIP or neighborhood at a price.
- Ruuster reads the type and the source of each event. Registrations, inquiries and listing views
  from your site count as the lead's own activity, credited to your `SITE_NAME`.
- The AI Nurture tags start listing alerts for the person (see
  [AI Nurture tags](https://help.ruuster.com/idx/crm-ai-nurture)).
