# Live location via webhooks

This guide builds a webhook receiver that keeps the live position of every load in your database
without polling. The example uses Node.js and Express. The same steps apply in any language (see the
verification samples in [Webhooks](/webhooks)).

## Design

1. **Verify** the signature on the raw body. Reject anything that fails with `401`.
2. **Acknowledge** with `204` immediately - the endpoint must answer within 7 seconds.
3. **Deduplicate** on `webhook-id` - retries reuse it.
4. **Apply** each item in the array to its tracking, ignoring positions older than what you have.

## Receiver

```js
import express from 'express';
import { verifyWebhook } from './verify-webhook.js'; // from the Webhooks page

const app = express();
const seenWebhookIds = new Set(); // use Redis or a DB table with a TTL in production

app.post('/webhooks/loadmarket', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyWebhook(req.body, req.headers)) return res.sendStatus(401);

  const webhookId = req.headers['webhook-id'];
  res.sendStatus(204);

  if (seenWebhookIds.has(webhookId)) return; // a retry of something already processed
  seenWebhookIds.add(webhookId);

  const updates = JSON.parse(req.body.toString('utf8'));
  for (const { data } of updates) {
    queue.push(data); // process outside the request
  }
});
```

## Applying an update

```js
async function applyTrackingUpdate(data) {
  const load = await db.loads.findByTrackingId(data.trackingId); // or by data.customId
  if (!load) return;

  const changes = { status: data.status.value, statusText: data.status.description };

  // Items of one delivery can arrive out of order across retries - keep the newest position only.
  // driverCoords is null while the tracking is not live: keep the last position you stored.
  const coords = data.driverCoords;
  if (coords && (!load.lastUpdate || coords.lastUpdate > load.lastUpdate)) {
    Object.assign(changes, {
      lat: coords.lat,
      lng: coords.lng,
      speedMph: coords.speed === null ? null : Math.round(coords.speed * 2.23694),
      lastUpdate: coords.lastUpdate,
    });
  }

  (data.stopLocations ?? []).forEach((stop, i) => {
    changes[`stop:${stop.customStopId ?? i}`] = {
      arrivedAt: stop.locationStatus?.arrived?.date ?? null,
      departedAt: stop.locationStatus?.completed?.date ?? null,
      alert: stop.stopAlertStatusInfo?.stopAlertStatus ?? null,
    };
  });

  if (data.driverFiles?.length) changes.files = data.driverFiles;

  await db.loads.update(load.id, changes);
}
```

## What to expect

- **One POST per minute at most**, containing every tracking of yours that changed in that minute.
  A quiet minute sends nothing - "no webhook" means "no change", not "tracking lost".
- **Each item carries the latest position at the time of the tick**, not every 20-second fix. For the
  location history of a load, use `GET /get-reports`.
- **Positions only while live**: `driverCoords` is `null` before the driver accepts, after a rejection
  and after the tracking finished (see [Tracking lifecycle](/tracking-lifecycle#driver-position)). An
  [ELD tracking](/eld-tracking#positions) has positions from the carrier's approval on, read from the
  truck's ELD about once a minute.
- **Statuses** can change without a position change (for example `notMoving` when the truck has not
  been moving for a while, `waiting` when no new position has arrived for a while, or `settings` when
  a phone setting may stop tracking). Show them - they tell your dispatcher to call the driver.
- **`driverFiles`** is included only in updates caused by a new upload.
- **`events`** say what happened since the last update (a stop reached, the driver declined or paused, a
  document uploaded, ...). Deduplicate them by `id` - see [Webhooks](/webhooks#events).
- **Final update**: after `done` or `cancel` (`doneEld` or `cancelEld` for ELD and Hybrid) the tracking
  sends nothing more.

## Monitoring

- Alert when your endpoint answers non-2xx or slower than a few seconds - a failed delivery's snapshot is
  not redelivered later (its `events` are, for up to an hour).
- If you suspect a gap, read the current state with `GET /get-tracking` - it is always authoritative.
- During development, drive a test tracking with `POST /test/simulate` and watch the `webhook.status`
  your endpoint returned. See [Test mode](/test-mode).
