JavaScript & TypeScript
The official TagLogger SDK for Node, browsers and modern runtimes
Install
The @taglogger/sdk package is the official SDK for the TagLogger API. It is written in TypeScript, ships full type definitions, has zero runtime dependencies, and is published for both ESM and CommonJS. The core is isomorphic (it uses the global fetch) and runs on Node 18+, modern runtimes and bundlers.
npm install @taglogger/sdk
Keep your API key on a server you control. Treat tl_live_ keys like passwords and never ship them in client-side bundles.
Quick start
import { TagLoggerClient } from '@taglogger/sdk';
const client = new TagLoggerClient({ apiKey: process.env.TAGLOGGER_API_KEY });
// One page of tags (envelope: { data, nextCursor })
const { data: tags } = await client.tags.list({
limit: 50,
label: 'Coca-Cola',
});
for (const tag of tags) console.log(tag.id, tag.name);
// Or stream every tag, paging transparently
for await (const tag of client.tags.iterate()) {
console.log(tag.id);
}
// Latest location for one tag -> { data: point | null, recordingPaused }
const { data: location } = await client.tags.location('tag-1');Returned tag and fleet objects include the read-only originalPhysicalLabel when TagLogger has a safely recorded label from original shipment or provisioning. It remains stable when name or a later sticker changes.
Get an API key from your dashboard under Settings → API Keys. Keys are scoped; each method documents the scope it needs in the package README.
Configuration
const client = new TagLoggerClient({
apiKey: 'tl_live_...',
baseUrl: 'https://api.taglogger.com', // override to target a staging deployment
authHeader: 'bearer', // 'bearer' (default) or 'x-api-key'
timeoutMs: 30000,
maxRetries: 2, // GET/DELETE retried on 5xx/network; any method retried on 429
fetch: customFetch, // inject a fetch implementation for tests or custom transports
});Every request method accepts an optional trailing AbortSignal for cancellation and per-request timeouts. Transient failures retry with randomized backoff: network errors and 5xx on idempotent methods (GET/DELETE), and 429 on any method. Non-idempotent writes are never silently retried after a transport failure.
Reading tags and locations
// A single tag, its battery, and its current location
const tag = await client.tags.get('tag-1'); // read:tags
await client.tags.update('tag-1', { // manage:tags
name: 'Main warehouse AED',
labels: ['Coca-Cola', 'Seattle', 'AED-0042'],
recordingPause: { paused: true, until: null, reason: 'Maintenance' },
});
const battery = await client.tags.battery('tag-1'); // read:tags
const { data: point } = await client.tags.location('tag-1');// read:locations
// Location history (start/end accept ISO 8601 or epoch ms)
const page = await client.tags.history('tag-1', { order: 'asc', limit: 500 });
// Incremental, whole-fleet sync — pass last sync's high-water mark as 'since'
let cursor;
do {
const delta = await client.fleet.delta({ since: lastSync, cursor });
handle(delta.data);
cursor = delta.nextCursor;
} while (cursor);Every list endpoint has a matching iterate* helper that returns an async Paginator — use for await for items, .pages() for a page at a time, or .all() to collect everything. Pages are fetched lazily.
Geofences, webhooks and share links
// Create a geofence (manage:geofences; recipient lists also need read:locations)
const gf = await client.geofences.create({
name: 'Yard',
center: { lat: 37.77, lng: -122.42 },
radiusMeters: 150,
targetTagIds: ['tag-1', 'tag-2'],
alerts: { onEntry: true, emailEnabled: true, emailAddresses: ['dispatch@example.com'] },
});
// Polygons and corridors (a band around a route); every geofence has a type
const depot = {
name: 'Depot',
type: 'polygon',
vertices: [{ lat: 37.770, lng: -122.420 }, { lat: 37.770, lng: -122.410 }, { lat: 37.776, lng: -122.415 }],
targetTagIds: ['all'],
};
const route = {
name: 'Route 1',
type: 'corridor',
path: [{ lat: 37.77, lng: -122.42 }, { lat: 37.80, lng: -122.27 }],
widthMeters: 1000, // full band width, 500-20000 m
targetTagIds: ['tag-1'],
};
// Up to 450 geofences in one all-or-nothing transaction (manage:geofences)
const created = await client.geofences.bulkCreate([depot, route], { idempotencyKey: 'import-2026-10-01' });
// Each tag's visits: entered, exited (null while still inside), duration, a page of tags at a time
// (read:geofences + read:locations; the workspace needs the geofence time report)
const range = { from: '2026-10-01T00:00:00Z', to: '2026-10-08T00:00:00Z' };
let cursor;
do {
const visits = await client.geofences.visits(gf.id, { ...range, limit: 50, cursor });
for (const t of visits.tags) console.log(t.tagId, t.visitCount, t.totalMs);
cursor = visits.nextCursor ?? undefined;
} while (cursor);
// Create a multi-tag Customer Page (manage:customer-pages)
const page = await client.customerPages.create({
pageName: 'Operations',
tagIds: ['tag-1', 'tag-2'],
expiresAt: null,
features: { liveMap: true, zones: true, statusTable: true, zoneActivity: true, locationHistory: false, labels: false },
});
// Subscribe to a webhook (manage:webhooks)
const webhook = await client.webhooks.create({
url: 'https://example.com/hooks/taglogger',
events: ['geofence.entry', 'geofence.exit', 'tag.offline'],
});
const secret = webhook.signingSecret; // shown ONCE — store it now to verify deliveries
// Verify your endpoint right away
await client.webhooks.sendTest(webhook.id);The seven event types are geofence.entry, geofence.exit, geofence.dwell, tag.moved, tag.battery_low, tag.offline and security.event (company sign-in events; needs read:security-events). See Set up Webhooks for the full event catalog and delivery details.
Geofence shapes and saving pauses
A circle is center plus radiusMeters (10 to 100,000 m), a polygon is 3 to 500 vertices in order, and a corridor is a path of 2 to 1,000 points plus widthMeters. A polygon or corridor comes back with center as its label point and radiusMeters: null. Visits default to the 7 days before to (default now) and can span at most 400 days.
Visits work the same for circles, polygons and corridors and come a page of tags at a time (limit default 10, at most 100). While nextCursor is not null, call again with it as cursor and the same from, to and tagIds (the window the first page returned, if you left it out); another window or tagIds fails with status 400 and code invalid_cursor. Tags come in tag id order, and a page can hold fewer than limit tags and still have a next page. A page whose window holds too many recorded locations fails with status 422 and code window_too_large: choose a shorter window or a smaller limit. The API answers a page within 75 seconds (503 service_unavailable after that), so visits waits at least 90 seconds per attempt whatever timeoutMs is. bulkCreate waits as long, since the API can take up to 75 seconds to save a bulk.
An update without type edits the current shape and must fit it: center and/or radiusMeters on a circle, vertices on a polygon, path and widthMeters together on a corridor. An update with type and that shape's fields replaces the shape whole. Anything else is 400 invalid_geofence.
A geofence write can fail with status 503 service_unavailable: the store did not answer and the write may have landed. Wait err.retryAfterSeconds and send the request again. With an idempotencyKey, retrying a create or bulk create after service_unavailable is safe: send the same key and body, and the retry returns the same geofences and never writes them twice. Without a key, list geofences before retrying a create. If a geofence the key created was edited since, or the key comes back with a different body after 24 hours, the create fails with 409 conflict, so send a new key with each new request. A bulk create is one transaction, all or nothing. The client retries a delete that fails with a 5xx by itself, but never a create or an update.
Verifying incoming webhooks
Every delivery carries an X-TagLogger-Signature header (sha256=<hex>, an HMAC-SHA256 of the raw request body). Verify against the raw bytes before trusting the payload — re-serializing the JSON changes the bytes and fails the check. Delivery is at-least-once, so de-duplicate on the event id.
import { constructWebhookEvent, SIGNATURE_HEADER, TagLoggerError } from '@taglogger/sdk';
// Express — capture the RAW body, e.g. express.raw({ type: 'application/json' })
app.post('/hooks/taglogger', (req, res) => {
const raw = req.body.toString('utf8'); // raw bytes as received, not JSON.parse'd
try {
const event = constructWebhookEvent(raw, req.header(SIGNATURE_HEADER), WEBHOOK_SECRET);
res.sendStatus(200); // event is the parsed, authenticated payload
} catch (err) {
if (err instanceof TagLoggerError) return res.sendStatus(400);
throw err;
}
});verifyWebhookSignature(rawBody, signatureHeader, secret) is the lower-level check; it returns false (never throws) on a missing header or mismatch.
Analytics toolkit
The package bundles @taglogger/sdk/analytics, a dependency-free, pure-math toolkit that turns the location data the API returns into stops, trips, dwell intervals, clusters and map-ready shapes. Everything runs locally, in-process — nothing is sent anywhere. Import it as a deep entry point so it tree-shakes away when unused.
import {
fixesFromLocationPoints,
conditionFixes,
detectStops,
detectTrips,
toFeatureCollection,
} from '@taglogger/sdk/analytics';
// Pull a tag's history, then analyze it in-process
const page = await client.tags.history('tag-1', { order: 'asc', limit: 500 });
const fixes = fixesFromLocationPoints(page.data);
const clean = conditionFixes(fixes, { maxAccuracyMeters: 100 });
const stops = detectStops(clean, { radiusMeters: 50, minDurationMs: 300000 }); // 5 min
const trips = detectTrips(clean, stops);
const geojson = toFeatureCollection(trips, stops); // ready for any mapThe toolkit also exposes conditioning (sortByTime, dedupeByTimestamp), DBSCAN clusterFixes, geometry primitives (haversineMeters, pointInPolygon, douglasPeucker, encodePolyline), and estimateBatteryDaysRemaining for battery projection from a series of readings.
isInsideGeofence(point, geofence) takes a geofence as the API returns it and follows the same rules TagLogger alerts use: polygon edges are straight lines on the map, and a corridor covers widthMeters / 2 on each side of its route. computeDwell(fixes, geofence) accepts any geofence shape.
Error handling
Any non-2xx response, or a transport failure, throws TagLoggerError with a stable code, status (0 for transport failures), requestId, isRateLimit and retryAfterSeconds.