Node package
The @apps-patrol/node package for Remix, React Router and Express apps.
@apps-patrol/node sends usage events and shop profiles from a Node Shopify app. Calls return immediately; batches are sent in the background with retries. It is written in TypeScript, ships ES module and CommonJS builds with types, has no dependencies, and needs Node 20 or newer.
Status
Version 0.2.0. It is not on npm yet; install it from the repository.
Install
npm install @apps-patrol/node
# or: npm install github:MahdiKetata99/apps-patrol-node
Create a client
// app/patrol.server.ts
import { AppsPatrol } from "@apps-patrol/node";
export const patrol = new AppsPatrol({
apiKey: process.env.APPS_PATROL_KEY,
baseUrl: "https://www.apps-patrol.com",
enabled: process.env.NODE_ENV === "production",
onError: (error, context) => console.warn(error.code, context),
});
Create one client per process and import it where you need it.
| Option | Default | Description |
|---|---|---|
apiKey | APPS_PATROL_KEY | The app's ingest key. Without it every call is a no-op and one warning is logged. |
baseUrl | APPS_PATROL_URL, else http://localhost:3000 | Your Apps Patrol address. |
enabled | true | false turns every call into a no-op. |
flushAt | 100 | Send as soon as this many items are waiting (1 to 100). Use 1 on serverless platforms. |
flushInterval | 2000 | Send at least this often, in milliseconds. |
maxQueue | 10000 | Items kept in memory while the server is unreachable. Beyond this the oldest are dropped. |
maxRetries | 5 | Attempts per request for network errors, server errors and rate limiting. |
timeout | 5000 | Milliseconds allowed per request. |
onError | none | Called with (error, context) for anything that could not be sent. |
logger | console | Where problems are logged. null silences it. |
fetch | global fetch | Replace it to go through a proxy. |
test | false | Record calls instead of sending them. See Testing below. |
Check your setup
const info = await patrol.ping();
// { ok: true, app: { name: "Cart Holder", … }, usage: { events_this_month: 12, events_limit: 250000 } }
ping is the one call that rejects: an AppsPatrolError with code and status for a rejected key, or a message naming the address when the server cannot be reached.
Track events
patrol.track({ shop: session.shop, event: "reservation_created", properties: { items: 3 } });
track is synchronous and returns true when the event was queued. Optional fields: eventId (defaults to a random UUID) and occurredAt (a Date or ISO string, defaults to now).
Standard events
patrol.onboardingStarted(shop);
patrol.onboardingCompleted(shop, { steps: 3 });
patrol.featureUsed(shop, "bulk_edit");
patrol.planViewed(shop);
patrol.upgradeClicked(shop, { plan: "pro" });
patrol.limitReached(shop, "products");
patrol.errorShown(shop, "sync_failed");
patrol.appOpened(shop); // at most once per shop per day
These names are a convention; track accepts any name.
Typed events
type Events = {
reservation_created: { items: number };
feature_used: { feature: "bulk_edit" | "export" };
};
const patrol = new AppsPatrol<Events>({ apiKey: process.env.APPS_PATROL_KEY });
patrol.track({ shop, event: "reservation_created", properties: { items: 3 } }); // checked
patrol.track({ shop, event: "reservation_created", properties: { item: 3 } }); // compile error
Identify a shop
patrol.identify({
shop: session.shop,
name: "Example Store", country: "DE", shopifyPlan: "basic",
source: "app_store", utm: { utm_source: "newsletter" },
});
Shopify Remix and React Router apps
// app/shopify.server.ts
import { identifyAfterAuth } from "@apps-patrol/node";
import { patrol } from "./patrol.server";
const shopify = shopifyApp({
// …
hooks: { afterAuth: identifyAfterAuth(patrol, { source: "app_store" }) },
});
// app/routes/app.tsx — the layout every embedded page goes through
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { session } = await authenticate.admin(request);
patrol.appOpened(session.shop);
return null;
};
// in any action
patrol.featureUsed(session.shop, "bulk_edit");
Express apps
import { patrolMiddleware } from "@apps-patrol/node";
app.use("/api/*", shopify.validateAuthenticatedSession(), patrolMiddleware(patrol));
app.post("/api/products/bulk", (req, res) => {
res.locals.patrol.featureUsed("bulk_edit");
res.sendStatus(200);
});
The middleware sends the daily app_opened and puts track and featureUsed, bound to the session's shop, on res.locals.patrol. Pass { getShop: (req, res) => … } if the shop lives somewhere else.
Serverless platforms
A function can be frozen as soon as it responds, before a background timer fires. Either send immediately and hand the promise to the platform, or await the flush:
const patrol = new AppsPatrol({ apiKey: process.env.APPS_PATROL_KEY, flushAt: 1 });
patrol.track({ shop, event: "feature_used" });
ctx.waitUntil(patrol.flush()); // Vercel, Cloudflare, Netlify
// or: await patrol.flush();
How sending works
- Queued:
trackandidentifyadd to an in-memory queue and return. They never throw. - Batched: up to 100 events per request, when
flushAtitems are waiting or everyflushIntervalmilliseconds. - Retried: network errors,
5xxandrate_limitedare retried with backoff, honouringRetry-After. Items stay queued while the server is down. - Reported: events the server rejects, and requests it refuses, go to the logger and
onError. - Bad key: after a
401, sending stops until the process restarts. - Quota: after
quota_exceeded, events are dropped for an hour before the next attempt. - Exit: the timer never keeps the process alive, and the queue is flushed when the event loop empties.
await patrol.flush(); // send what is queued now; true when the queue is empty afterwards
await patrol.shutdown(); // the same, for symmetry with other clients
Testing your app
const patrol = new AppsPatrol({ test: true });
patrol.featureUsed("example.myshopify.com", "bulk_edit");
patrol.recorded.events; // [{ shop, name: "feature_used", properties: { feature: "bulk_edit" }, … }]
patrol.recorded.shops; // every identify call
In test mode nothing is sent and no key is needed.