TypeScript / Node
The trackified npm package, for Node 18+, Deno, Bun and edge runtimes.
The trackified package has no runtime dependencies. It uses the platform fetch and Web Crypto, ships ESM and CommonJS builds, and includes full type declarations. Source: trackified/trackified-node.
Install
- npm
- pnpm
- yarn
npm install trackifiedpnpm add trackifiedyarn add trackifiedConfigure
import Trackified from "trackified"; // CommonJS: const { Trackified } = require("trackified");
const client = new Trackified(); // reads TRACKIFIED_API_KEY and TRACKIFIED_BASE_URLPass options to override the defaults:
const client = new Trackified({
apiKey: process.env.TRACKIFIED_API_KEY,
baseURL: "https://api.trackified.net",
timeout: 30_000, // ms per attempt
maxRetries: 2,
});The base URL works with or without /v1 at the end.
Check that the API is up. No key is needed for this call:
const { status } = await client.health(); // "ok"; a 503 throws APIErrorTrackings
Create
const tracking = await client.trackings.create({
tracking_number: "1Z999AA10123456784",
carrier: "ups", // optional: our id or a name like "UPS Ground"; detected when left out
custom_id: "order_1042", // optional: your own reference
customer_email: "ada@example.com", // optional
});carrier takes our carrier id, a carrier or service name ("USPS Priority Mail"), or another provider's slug ("dhl_express"). The tracking stores our id. Leave carrier out and we detect it from the number. If we can't tell, the call fails with a ValidationError whose code is carrier_not_detected.
Get
const tracking = await client.trackings.get("trk_...");
console.log(tracking.status, tracking.estimated_delivery);
for (const event of tracking.events) {
// newest first
console.log(event.occurred_at, event.status, event.description, event.location);
}List and auto-paginate
// One page
const page = await client.trackings.list({ status: "in_transit", limit: 50 });
console.log(page.data.length, "of", page.pagination.total);
// Every matching tracking, fetching pages as needed
for await (const t of client.trackings.iterate({ status: "delivered" })) {
console.log(t.tracking_number, t.delivered_at);
}Filters: status, carrier, custom_id, tracking_number, plus limit and offset.
Update, stop and retrack
// Change the carrier, custom_id or customer_email. Fields you leave out stay as they are.
await client.trackings.update("trk_...", { carrier: "usps" });
// Ask for the carrier to be checked again within a minute.
const { queued } = await client.trackings.retrack("trk_...");
// Stop tracking. The tracking is no longer checked or returned.
await client.trackings.delete("trk_...");Bulk create
const result = await client.trackings.createBulk([
{ tracking_number: "1Z999AA10123456784", custom_id: "order_1042" },
{ tracking_number: "9434650110837017316201", carrier: "usps", custom_id: "order_1043" },
]);
for (const row of result.data) {
console.log(row.ok ? row.tracking?.id : row.error);
}Each row succeeds or fails on its own. Your plan sets the most rows per request. See Rate limits and plans.
Carriers
const { candidates } = await client.carriers.detect("1Z999AA10123456784");
console.log(candidates[0]?.carrier, candidates[0]?.confidence); // best first
// Map a free-text name or another provider's slug to our id. null if we don't serve it.
const match = await client.carriers.resolve("FedEx SmartPost");
console.log(match?.carrier, match?.confidence, match?.matched);
const catalog = await client.carriers.search({ q: "dhl" }); // the full carrier catalogWebhooks
Create an endpoint
const webhook = await client.webhooks.create({
url: "https://example.com/webhooks/trackified",
event_types: ["tracking.status_changed", "tracking.delivered"],
});
// Store webhook.secret now. It's only returned here.Update, pause and rotate
// Change the URL or events, or pause it. The secret stays the same.
await client.webhooks.update(webhook.id, { eventTypes: ["tracking.status_changed"] });
await client.webhooks.update(webhook.id, { enabled: false });
// New secret, shown once. The old one keeps verifying for 24 hours by default.
const rotated = await client.webhooks.rotateSecret(webhook.id, { expiresInHours: 24 });
console.log(rotated.secret, rotated.previous_secret_expires_at);rotateSecret isn't retried automatically: if a first attempt went through without you seeing the new secret, a retry would drop the secret you're using. During the window, pass both secrets when you verify (below).
Verify in Express
Use express.raw on the webhook route so you get the body as a Buffer, not parsed JSON.
import express from "express";
import { Trackified } from "trackified";
const app = express();
app.post("/webhooks/trackified", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = await Trackified.webhooks.constructEvent(
req.body, // Buffer
req.header("x-tracking-signature"),
process.env.TRACKIFIED_WEBHOOK_SECRET!,
);
} catch {
return res.sendStatus(400);
}
if (event.type === "tracking.status_changed") {
console.log(event.data.previous_status, "->", event.data.current_status);
}
const tracking = Trackified.webhooks.trackingOf(event); // the tracking, for any event type
console.log(event.type, tracking.tracking_number);
res.sendStatus(200);
});Verify in a Next.js route handler
Read the body with request.text(). The same code works in other Fetch-style handlers: Cloudflare Workers, Deno and Bun.
import { Trackified } from "trackified";
export async function POST(request: Request) {
const body = await request.text();
let event;
try {
event = await Trackified.webhooks.constructEvent(
body,
request.headers.get("x-tracking-signature"),
process.env.TRACKIFIED_WEBHOOK_SECRET!,
);
} catch {
return new Response("bad signature", { status: 400 });
}
if (event.type === "tracking.delivered") {
console.log("delivered:", event.data.tracking_number);
}
return new Response(null, { status: 200 });
}Events are typed
constructEvent returns a union typed by type. Check event.type and TypeScript knows the shape of event.data: tracking.status_changed carries { tracking, previous_status, current_status }, every other type carries the Tracking. Trackified.webhooks.trackingOf(event) returns the tracking for any type.
Failed carrier checks
A tracking.exception sent because we couldn't reach the carrier carries { tracking_id, error }, not a tracking, so trackingOf doesn't return a full tracking for it. Check for tracking_id before you use the result. See Webhook events.
Why verification failed
constructEvent throws SignatureVerificationError with a reason: missing, malformed, timestamp or mismatch. verifyDetailed returns it without throwing; verify returns a boolean:
// body: the raw request body; header: the x-tracking-signature value
const { valid, reason } = await Trackified.webhooks.verifyDetailed(body, header, secret);
if (!valid) console.warn("webhook rejected:", reason);All three take one secret or an array of secrets (any may match), and { tolerance } in seconds as a fourth argument (default 300). Pass both secrets while a rotation is in progress:
const event = await Trackified.webhooks.constructEvent(body, header, [
process.env.TRACKIFIED_WEBHOOK_SECRET!,
process.env.TRACKIFIED_WEBHOOK_SECRET_OLD!,
]);Errors
import {
ConnectionError,
NotFoundError,
QuotaExceededError,
RateLimitError,
TrackifiedError,
ValidationError,
} from "trackified";
try {
await client.trackings.create({ tracking_number: "ABC123" }, { idempotencyKey: "order_1042" });
} catch (err) {
if (err instanceof ValidationError && err.code === "carrier_not_detected") {
// ask the user for the carrier
} else if (err instanceof QuotaExceededError) {
// 402: this month's trackings are used up
} else if (err instanceof ConnectionError && err.code === "timeout") {
// The outcome is unknown. Retry later with the same idempotency key.
} else if (err instanceof NotFoundError) {
// 404
} else if (err instanceof RateLimitError) {
console.log("retry in", err.retryAfter, "s");
} else if (err instanceof TrackifiedError) {
console.log(err.status, err.code, err.message, err.requestId);
} else {
throw err;
}
}The classes are AuthenticationError (401), PermissionError (403), NotFoundError (404), ValidationError (400, 422), QuotaExceededError (402), ConflictError (409, including idempotency_in_progress), RateLimitError (429), APIError (5xx), ConnectionError (no response; code is timeout or connection) and SignatureVerificationError. ConflictError isn't retried.
A timeout means the outcome is unknown: the request may have reached us. The library's own retries reuse the idempotency key, so a create is never doubled. If you retry yourself later, pass the same idempotencyKey.
Options
Client option | Default | |
|---|---|---|
|
| |
|
| |
|
| Milliseconds per attempt. |
|
| Retries for network errors, 408, 429 and 5xx. |
|
| A custom fetch implementation. |
| none | Extra headers on every request. |
| none | Called before each attempt. |
| none | Called after each attempt. |
Request hooks
const client = new Trackified({
onRequest: ({ method, url, attempt, idempotencyKey }) => {
console.log("->", method, url, "attempt", attempt, idempotencyKey ?? "");
},
onResponse: ({ method, url, status, requestId, idempotentReplayed, durationMs, error }) => {
console.log("<-", method, url, status ?? error?.code, requestId, `${durationMs}ms`, idempotentReplayed ? "(replay)" : "");
},
});Each hook runs once per attempt, so a retried request calls them more than once. attempt is 0 for the first try. status is undefined when no response arrived; error is the typed error when the status is 400 or more or the connection failed. A hook that throws is ignored.
Every method also takes per-call options as its last argument:
const controller = new AbortController();
await client.trackings.create(
{ tracking_number: "1Z999AA10123456784" },
{ idempotencyKey: "order_1042", timeout: 10_000, maxRetries: 0, signal: controller.signal },
);idempotencyKey replaces the generated key on creates. See Pagination, retries and idempotency.