@shopkit/observability
v0.3.1
Published
Frontend observability for storefronts and the editor: browser errors, failed requests, web vitals and flows, sent as OTLP traces
Readme
@shopkit/observability
Frontend monitoring for storefronts and the editor. Browser errors, failed requests, broken images and web vitals are sent as OTLP traces to a relay on the app's own server, which forwards them to SigNoz.
The package knows no framework: each app passes its own paths and values.
Browser: @shopkit/observability/client
import { initObservability } from "@shopkit/observability/client";
initObservability({
app: "storefront",
serviceName: "storefront-web",
relayUrl: "/api/obs",
ignore: { params: ["previewKey"], errors: [/ResizeObserver loop/] },
});About 4.6 KB gzip up front; web-vitals loads after page load. Never throws into the page. Each page view is its own trace; same-origin API calls join it. Next.js link prefetches are marked unsampled, so the server doesn't trace them.
Every signal carries page.type (from the optional pageType(path) callback) and, where the browser knows it, network.effective_type. Other options: ignore.paths / ignore.cookies (non-shopper traffic), slowFetchMs (default 2000), sessionCap (default 100 per page; capRefillMs refills it for pages open for hours, e.g. the editor), apiOrigins (URLs of your own APIs on other domains, e.g. the commerce backend: their 5xx and slow calls count as yours).
Business flows (checkout, add to cart):
import { startFlow } from "@shopkit/observability/client";
const flow = startFlow("checkout"); // later: flow.success() or flow.fail("checkout_api", err)Each flow is recorded once as flow.<name> with flow.outcome and flow.failure_reason.
When the user is known only after start-up (e.g. the editor's sign-in): identify({ merchantId, userId }) names every span from then on. Internal ids only, never an email; on storefronts the relay's trusted merchant.id still wins.
Before the app starts: @shopkit/observability/head-stub
import { headStubScript } from "@shopkit/observability/head-stub";
// First child of <head>, server-rendered
<script dangerouslySetInnerHTML={{ __html: headStubScript({ relayUrl, serviceName, app }) }} />An inline ES5 script (~1.2 KB gzip). It queues errors that happen before the app's JS runs, and initObservability sends them on. If the app never starts (its scripts failed), the stub itself reports browser.app_not_started with what it caught, once the page has loaded.
Containing crashes: @shopkit/observability/react
import { ObservabilityBoundary } from "@shopkit/observability/react";
<ObservabilityBoundary kind="widget" id={widget.id} type={widget.type}>
{widget}
</ObservabilityBoundary>A crash renders nothing (or fallback); the rest of the page stays up, and the crash is reported as browser.render_error with the component's kind, id and type. Plain React, already marked "use client". Reports go through initObservability; before it runs, crashes are still contained.
For Next.js error.tsx / global-error.tsx: useReportError(error, "app-error") (the id names which boundary caught it). An app's own boundary (one that, say, resets itself) reports with reportRenderError(error, { kind, id, componentStack }) from componentDidCatch.
Relay: @shopkit/observability/relay (Node)
import { createRelayHandler, fileSourceMaps } from "@shopkit/observability/relay";
export const POST = createRelayHandler({
endpoint: "http://collector:4318/v1/traces",
// Set by the server; overwrites anything the browser sent.
// Release and environment belong here too: the head stub's reports carry neither.
trusted: { "merchant.id": merchantId, "service.version": release, "deployment.environment": env },
sourceMaps: fileSourceMaps({ urlPath: "/_next/static/", dir: ".next/obs-sourcemaps" }),
});Checks size (64 KB) and shape, rate-limits per server instance (client IPs can be faked), drops bots, strips query strings, URL fragments, emails and phone numbers, stamps trusted plus device.type and browser.in_app from the User-Agent, resolves minified stacks (at most 30 new maps a minute), forwards to the collector.
Server tracing: @shopkit/observability/server (Node)
Generic OpenTelemetry pieces for the app's own SDK setup (e.g. @vercel/otel's registerOTel). Needs @opentelemetry/api.
registerOTel({
serviceName: "storefront-server",
traceSampler: skipPathsSampler(/^\/(api\/obs$|_next\/)/, {
dropSpans: ["start response"], // never record these span names
}), // never trace these paths
spanProcessors: [scrubSpanProcessor(), "auto"], // strip query strings, emails, phones
});
// Next's instrumentation hook: an error in a streamed page render is otherwise unrecorded.
export const onRequestError = (err: unknown) => recordServerError(err);recordServerError puts the error in the request's trace with error.digest, the same digest the browser's useReportError report carries.
dropSpans skips spans by name, e.g. Next's zero-time internal spans. A dropped span's children are dropped with it, so list leaf spans only.
Keeping source maps private: shopkit-move-sourcemaps
shopkit-move-sourcemaps <public build dir> <private dir>
# e.g. after next build:
shopkit-move-sourcemaps .next/static .next/obs-sourcemapsMoves every *.map out of the served folder. Fails (exit 1) if it can't, so maps are never shipped publicly.
With Sentry, set sourcemaps: { deleteSourcemapsAfterUpload: false } in withSentryConfig: by default Sentry deletes the maps at the end of the build, before this command runs, and browser stacks stay minified.
