Skip to content

Catch the JavaScript Errors Your Users See

Your server logs say everything is fine. Meanwhile a customer on Firefox can't open the payment form, because a script throws before it renders, and they leave without a word. Server logs only see the requests that arrive; the errors that stop a request from ever being sent happen in the browser, and nobody sees them unless the app reports them.

This post shows how to log what happens in your users' browsers and phones, cheaply, and without collecting data you shouldn't.

What to capture

Four kinds of events cover most of what goes wrong:

  • Uncaught errors and rejected promises, with their stack trace.
  • Failed and slow API calls: the method, the URL template (not the full URL), the status and the duration.
  • Performance of key pages, such as time to first byte and Largest Contentful Paint.
  • A few user events that explain the context: page loads, checkout started, payment submitted.

And the context once per session: the app and its version, the environment, the browser or device, the locale, and a session id that ties the events together.

Capture them in the browser

const queue = [];

function log(event) {
  queue.push({ timestamp: new Date().toISOString(), ...event });
  if (queue.length >= 100) flush();
}

window.addEventListener("error", (e) =>
  log({ severity: "error", eventType: "error", message: e.message, stackTrace: e.error?.stack }));

window.addEventListener("unhandledrejection", (e) =>
  log({ severity: "error", eventType: "error", message: String(e.reason), stackTrace: e.reason?.stack }));

Wrap your API client the same way, logging a warning for any response slower than you'd like and an error for any 5xx.

Send them in batches

One request per event is slow for the user and expensive for you. Collect events and send them together: every 30 seconds, when 100 have gathered, and when the user leaves the page.

ObjectsGrid frontend logging takes up to 1,000 events in one POST /log. What every event of the batch shares goes once in sourceInfo, and ObjectsGrid copies it into each event:

function flush() {
  if (queue.length === 0) return;
  const body = JSON.stringify({
    sourceInfo: {
      schemaVersion: "1.0.0",
      app: { name: "northpeak-shop", version: "4.2.0" },
      environment: "production",
      platform: "web",
      sentAt: new Date().toISOString(),
      session: { sessionId },
    },
    logEvents: queue.splice(0),
  });
  fetch("https://apis.objectsgrid.com/log", {
    method: "POST",
    keepalive: true,                       // survives the page closing
    headers: {
      "Content-Type": "application/json",
      "X-ObjectsGrid-AccessPoint": "EU",
      Authorization: `Bearer ${token}`,
    },
    body,
  });
}

setInterval(flush, 30_000);
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") flush();
});

keepalive: true lets the last batch go out even as the tab closes, which is exactly when the most telling errors happen. Browsers limit a keepalive request's body to 64 KB, so flush often enough that the last batch stays small.

Visitors who aren't signed in can send logs too, with your public service account's token. Let it create log events and nothing else in your access policy.

Find what broke

Logs are only useful when you can ask them questions. Log events are searchable within seconds, with the same where and orderBy as every other list. Every error of one customer's session:

curl -G https://apis.objectsgrid.com/log \
  -H 'X-ObjectsGrid-AccessPoint: EU' \
  -H "Authorization: Bearer $TOKEN" \
  --data-urlencode 'where={"session": {"sessionId": "s-8f2a91"}, "severity": "error"}' \
  --data-urlencode 'orderBy={"timestamp": "desc"}'

Which errors happen most, so you fix the one that hurts the most users first:

groupBy={"by": ["message"], "where": {"severity": "error"}, "_count": true,
         "orderBy": {"_count": {"_all": "desc"}}}

Filter by app version to see whether last night's release introduced it, or by browser to see whether it's only Firefox.

Don't log what you shouldn't

Frontend logs travel far and live long. Keep personal data out of them: no email addresses, names or card numbers in messages and context. Log ids instead, such as the user's account id, and look the person up when you need to. Messages copied from form fields and URLs with query strings are the usual leaks; log URL templates like /orders/{id}, not the URL.

What it costs

Each event counts as one request against your spending cap, so log what you will act on: errors and slow requests always, a sample of the rest. At 20 events per session, 2,000 sessions a month are 40,000 events, inside the 50,000 free requests a month, before your app's other requests.