Setting Up Webhooks
Step-by-step guide to implement real-time event handling
Overview
This guide walks you through setting up webhooks to receive real-time notifications when tags move, battery is low, or go offline.
Step 1: Implement Your Webhook Endpoint
Create an HTTPS endpoint that will receive webhook POST requests. Your endpoint must:
- Be publicly accessible over HTTPS (HTTP will be rejected)
- Accept POST requests with JSON bodies
- Verify the X-TagLogger-Signature header
- Respond with a 2xx status (for example, 200 OK) to acknowledge receipt
Example (Express.js)
const express = require('express');
const crypto = require('crypto');
const app = express();
// IMPORTANT: Use raw body for signature verification
app.use(express.json({ verify: (req, res, buf) => {
req.rawBody = buf.toString();
} }));
app.post('/webhooks/taglogger', (req, res) => {
// 1. Verify the signature
// Header format: "X-TagLogger-Signature: sha256=<hex>"
const header = req.headers['x-taglogger-signature'] || '';
const provided = header.replace(/^sha256=/, '');
const secret = process.env.WEBHOOK_SECRET;
// Must use the raw body, not parsed JSON
const expected = crypto
.createHmac('sha256', secret)
.update(req.rawBody, 'utf8')
.digest('hex');
const valid =
provided.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(expected));
if (!valid) {
console.error('Signature mismatch!');
return res.status(401).json({ error: 'Unauthorized' });
}
// 2. Acknowledge receipt immediately
res.sendStatus(200);
// 3. Process the event asynchronously
const event = JSON.parse(req.rawBody);
handleEvent(event).catch(err => {
console.error('Failed to process webhook:', err);
});
});
async function handleEvent(event) {
// Dedup: store event.id to prevent processing duplicates
const isDuplicate = await db.webhookEvents.findOne({ id: event.id });
if (isDuplicate) {
console.log(`Already processed ${event.id}`);
return;
}
// Process based on event type
switch (event.event) {
case 'tag.moved':
console.log(`Tag ${event.tag.id} moved to ${event.data.to.lat},${event.data.to.lng}`);
break;
case 'tag.battery_low':
// event.data.status is 3 (low, plan a swap) or 4 (critical, replace soon); prefer the critical boolean.
console.log(`Tag ${event.tag.id} battery low (critical: ${event.data.critical})`);
break;
case 'tag.offline':
console.log(`Tag ${event.tag.id} last seen ${event.data.lastSeenAt}`);
break;
}
// Mark as processed
await db.webhookEvents.insert({ id: event.id, processedAt: new Date() });
}
app.listen(3000);Step 2: Create a Webhook Subscription
Create a subscription in your workspace to tell TagLogger where to send events.
Subscriptions are managed through the API. Send a POST /v1/webhooks request with your endpoint URL and the event types you want. The response includes the signing secret. Copy it immediately and store it in your environment (for example, as WEBHOOK_SECRET); it is shown only once.
POST /v1/webhooks HTTP/1.1
Host: api.taglogger.com
Authorization: Bearer tl_live_xxxxx
Content-Type: application/json
{
"url": "https://example.com/webhooks/taglogger",
"events": ["tag.moved", "tag.battery_low", "tag.offline"],
"label": "My App Webhooks"
}
Response (201 Created):
{
"data": {
"id": "kP9mX2qR7tA4nB1c",
"url": "https://example.com/webhooks/taglogger",
"events": ["tag.moved", "tag.battery_low", "tag.offline"],
"label": "My App Webhooks",
"active": true,
"signingSecret": "whsec_xxxxx...",
"signingSecretSet": true,
"createdAt": "2024-06-19T13:45:23Z",
"updatedAt": "2024-06-19T13:45:23Z"
}
}Leaving events out subscribes to every event type except security.event. To receive company sign-in security events, name security.event; the API key also needs the read:security-events scope. See Events for every type and its payload.
Important: The signing secret (signingSecret, prefix whsec_) is shown only once, at creation. Store it immediately. If you lose it, rotate it with POST /v1/webhooks/{webhookId}/rotate-secret to get a new one.
Step 3: Test Your Endpoint
Before enabling live deliveries, test your endpoint with a sample event:
- Send a test delivery:
POST /v1/webhooks/{webhookId}/test - Check your server logs to verify the test was received and processed
- Verify that signature verification succeeded
See the Testing Webhooks page for detailed debugging tips.
Step 4: Go Live
Tag event delivery is off by default at launch. There is nothing to request and no per-workspace switch to flip on your side: once production delivery is enabled, every existing subscription—including the one you just created—starts receiving live tag.* events automatically. No re-creation or code change is needed.
Until then, your POST /v1/webhooks/{webhookId}/test deliveries work right now, so you can build and verify your entire handler—signature checks included—before live events begin flowing.
Step 5: Implement Robust Event Handling
Deliveries are at-least-once and retried automatically, but a subscription that stays down past the retry budget can still miss events, so reconcile against the API to be certain you don't fall behind:
Poll the Fleet Delta Regularly
Set up a scheduled job to poll GET /v1/fleet/delta every few minutes. This ensures you catch any changes that didn't result in a webhook delivery.
// Scheduled job: sync tags every 5 minutes
setInterval(async () => {
const since = await db.lastDeltaPoll.get();
const response = await fetch(
`https://api.taglogger.com/v1/fleet/delta?since=${since}`,
{ headers: { 'Authorization': 'Bearer tl_live_xxx' } }
);
const { data, nextCursor } = await response.json();
for (const change of data) {
// Update your local state with the change
await db.tags.upsert(change);
}
// Update last poll time
await db.lastDeltaPoll.set(new Date());
}, 5 * 60 * 1000); // 5 minutesTrack Processed Event IDs
Store the event ID of every webhook you process. If you see the same ID again, skip processing. Because deliveries are at-least-once, the same event id can legitimately arrive more than once (a retry after a slow 200, or overlap at a delivery boundary), so this de-duplication is required for correctness, not just a safeguard.
Best Practices Checklist
- Verify signatures: Always check X-TagLogger-Signature before trusting the payload.
- Respond immediately: Send a 2xx response (for example, 200 OK) within a few seconds, even if processing the event takes longer.
- Process asynchronously: Queue the event and process it in a background job or worker.
- Track event IDs: Store processed event IDs to prevent duplicate processing.
- Handle out-of-order delivery: Use occurredAt timestamps to order events, not arrival order.
- Use HTTPS: Your endpoint must be served over HTTPS. HTTP requests will be rejected.
- Set up alerts: Log webhook failures and set up alerts for signature mismatches.
- Poll for reconciliation: Don't rely on webhooks alone. Poll GET /v1/fleet/delta on an interval.
- Inspect delivery status: Use GET /v1/webhooks/{webhookId}/deliveries to see per-event status, attempt counts, and the last error when debugging an endpoint that isn't receiving events.
- Test the full path: Send a test delivery to your endpoint and confirm signature verification so your handler is ready when live deliveries begin.
- Monitor delivery latency: Track how long deliveries take and set up alerts if latency spikes.
Common Pitfalls
Using HTTP instead of HTTPS
Your endpoint must be served over HTTPS. HTTP endpoints will be rejected during creation or testing.
Not verifying the signature
Always verify X-TagLogger-Signature to ensure the webhook came from TagLogger and wasn't forged.
Using parsed JSON for signature verification
The signature is computed over the raw request body as a string, not the parsed JSON object. Use the raw body bytes for verification.
Doing heavy work synchronously in the handler
Respond with a 2xx status (for example, 200 OK) immediately, then process the event asynchronously. Don't make the webhook timeout waiting for your logic.
Relying on webhooks as the source of truth
Webhooks are at-least-once and retried, but they are a notification channel, not a ledger—a subscription that stays down past the retry budget will give up. Poll GET /v1/fleet/delta regularly to reconcile and catch any missed changes.