Skip to content

    Frontend System Design

    Error Reporting and Source Maps

    Catch the errors your users hit, turn minified stack traces back into source lines with source maps, and report them without leaking code or personal data.

    By Published 13 min read

    Share

    Standard lessonintermediateFrontend System Design

    Before this: Logging, Tracing and Correlation IDs, Error Boundaries and Global Error Handling

    What you'll learn: By the end of this lesson you will be able to list where a browser app can catch errors (the error event, unhandledrejection, framework hooks), explain what a source map contains and how a stack frame is mapped back to a source line, ship maps without exposing your code to the public, send a report that survives a closing tab, and keep reports useful with a release tag, grouping, rate limits and scrubbing of personal data.

    Think of a bug report written in a shorthand only the writer understands: "p, line 1, column 47". A minified bundle writes exactly that, and your users never file a report at all, they just leave. Error reporting collects those notes automatically, and a source map translates the shorthand back into "src/cart/total.js, line 2".

    The running example is the checkout page of a grocery marketplace (the front end of the ShopStream marketplace used in this course), shipped as a minified bundle several times a week.

    The core idea

    1. Errors happen on machines you do not control. If the app does not report them, the first you hear is a drop in orders.
    2. A report is only as good as its context. A stack trace of minified frames, with no release, no route and no way to group duplicates, is noise.
    3. The map that makes traces readable is also your source code. Keep it out of public reach and give it only to the tool that needs it.

    Where errors can be caught

    A browser gives you a few global hooks, and a framework adds its own. Each one sees a different slice.

    • The error event. MDN says it fires on window when a resource fails to load or cannot be used, for example a script with an execution error, and that it is only generated for script errors thrown synchronously. The window.onerror form receives five arguments: message, source URL, line number, column number and the error object.
    • The unhandledrejection event. A rejected promise with no handler fires this event instead. MDN says rejections that originate from a cross-origin script do not fire it, because it could leak data.
    • A framework hook. React's documentation says a componentDidCatch method in an error boundary lets you log render errors to an error reporting service, and that createRoot accepts onCaughtError, onUncaughtError and onRecoverableError callbacks that receive the error and a componentStack. React also states that error boundaries do not catch errors in event handlers, in server rendering, in the boundary itself, or in asynchronous callbacks such as setTimeout. Error, Loading and Empty States covers what to show the user, and the lesson on error boundaries and global error handling goes deeper on these hooks; this lesson covers what to send.

    Figure 1. Four sources, one reporter

    Error sources converge on one reporter in the browsererror event to Reporter; Rejections to Reporter; Framework hook to Reporter; Reporter to Intake (beacon)error event: sync script errorserror eventsync scripterrorsRejections: unhandled promisesRejectionsunhandledpromisesFramework hook: render errorsFramework hookrender errorsReporter: enrich, group, limitReporterenrich, group,limitIntake: server or vendorIntakeserver or vendorbeacon

    How to read this: the three hooks on the left see different failures and none sees everything. They share one reporter (the accent box), so enrichment, deduplication and limits are written once. The dashed arrow is a send that must not block the page.

    A caution about stacks. MDN marks Error.prototype.stack as non-standard: every engine has its own format, and you cannot rely on the precise content of the string. Treat the stack as text to store and map, not to parse with one regular expression and trust everywhere. Newer code can also set cause when re-throwing (new Error("Checkout failed", { cause: error })), which keeps the original error attached to the wrapper.

    What a source map is

    A bundler turns many source files into one or a few minified ones. A source map is a JSON file that records how to get back. The format is standardised as ECMA-426, whose version field is always the integer 3. The fields you will meet:

    Field Meaning
    sources The original files, as possibly relative URLs
    sourcesContent Optional text of those files, in the same order
    names Optional original identifiers that the mappings may name
    mappings The encoded position data
    ignoreList Optional indices of third-party sources tools may skip when stepping

    The mappings string is base64 VLQ: one group per generated line separated by semicolons, segments separated by commas, each segment holding a generated column, a source index, an original line, an original column and an optional name, mostly as differences from the previous value. Lines and columns in the map are zero-based, whereas a stack trace shows one-based numbers, so a consumer has to convert.

    Illustration 1: the minimal example

    A four-line source file with a bug (the second cart line has no product) is minified by esbuild, run, and its stack frame mapped back. Run it after npm install esbuild in an empty folder:

    import { transformSync } from "esbuild";
    import { SourceMap } from "node:module";
    import vm from "node:vm";
    
    const source = `export function total(lines) {
      const prices = lines.map((line) => line.product.price * line.qty);
      return prices.reduce((sum, p) => sum + p, 0);
    }
    globalThis.run = () => total([{ qty: 2, product: { price: 3 } }, { qty: 1 }]);
    `;
    
    const out = transformSync(source, {
      loader: "js",
      format: "iife",
      minify: true,
      sourcemap: "external",
      sourcefile: "src/cart/total.js",
    });
    console.log("minified:", out.code.trim());
    
    const sandbox = {};
    vm.createContext(sandbox);
    vm.runInContext(out.code, sandbox, { filename: "app.min.js" });
    try {
      sandbox.run();
    } catch (error) {
      const frame = error.stack.split("\n").find((l) => l.includes("app.min.js"));
      console.log("error:  ", error.message);
      console.log("frame:  ", frame.trim());
      const [, line, col] = frame.match(/app\.min\.js:(\d+):(\d+)/);
      const origin = new SourceMap(JSON.parse(out.map)).findOrigin(Number(line), Number(col));
      console.log("origin: ", `${origin.fileName}:${origin.lineNumber}:${origin.columnNumber}`);
    }

    Output, from running it in Node 26.13.1 with esbuild 0.21.5:

    minified: (()=>{function p(t){return t.map(r=>r.product.price*r.qty).reduce((r,c)=>r+c,0)}globalThis.run=()=>p([{qty:2,product:{price:3}},{qty:1}]);})();
    error:   Cannot read properties of undefined (reading 'price')
    frame:   at app.min.js:1:47
    origin:  src/cart/total.js:2:51

    The minified frame points at line 1, column 47. findOrigin takes one-based numbers like those in an error message (the Node documentation says findEntry uses zero-indexed offsets) and returns line 2, column 51 of src/cart/total.js, the price read in the original. A reporting service runs this lookup for every frame.

    Finding and protecting the map

    A browser finds a map by a //# sourceMappingURL= comment at the end of the file or by a SourceMap HTTP response header; the specification says the header takes precedence when both are present. Developer tools then show your original code to anyone who opens them. That is the trade-off, and the build tools give three postures. The webpack documentation, for example, describes: a full map with a reference comment, where it warns that you should configure your server to disallow access to the map file for normal users; hidden-source-map, which does not add the comment and is useful when the map is only for error reports; and nosources-source-map, which leaves out sourcesContent, though it still exposes file names and structure. Vite's build.sourcemap offers 'hidden' with the same meaning (a separate file, no comment), and the option is off by default.

    Figure 2. Build once, split the map from the bundle

    The bundle goes to the CDN, the map goes to the error toolCI build to CDN (deploy); CI build to Error tool (upload map); CDN to Browser (serve bundle); Browser to Intake (minified stack); Intake to Error tool (look up map)CI build: bundle + hidden mapCI buildbundle + hiddenmapCDN: bundle onlyCDNbundle onlyError tool: private map storeError toolprivate map storeBrowser: runs the bundleBrowserruns the bundleIntake: gets raw reportsIntakegets raw reportsdeployupload mapserve bundleminified stacklook up map

    How to read this: the map is built with the bundle but never reaches the CDN. Reports arrive with minified frames, and the tool maps them server side. This is the arrangement the webpack page recommends for hidden maps.

    Sentry's documentation shows one concrete version: you upload source maps during the build, it links them to builds by injecting a debug ID into your output by default, and it says hosting maps publicly is possible for browser apps but uploading during the build is strongly recommended. The principle holds for any tool: the map must match the exact build. A map for last week's bundle gives wrong lines for this week's.

    Making a report worth reading

    A bare stack is not enough. Each report should carry:

    • A release identifier (a version or commit) so the map can be matched and so you can see which deploy introduced a problem.
    • Where it happened: the route, with secrets stripped, and the component stack from the framework hook. React's documentation says that in production the component names are minified, and that the component stack can be decoded with source maps like an ordinary stack.
    • A fingerprint for grouping: the error name plus the top frames with line numbers removed, so one bug reported by ten thousand users is one issue with a count.
    • A correlation id, when you have one, to join the report to server logs (see Correlation IDs and Trace Context Across Services).

    And a report must leave out what you should not collect: email addresses, tokens in query strings, form values. Scrub in the browser, before sending, because once data reaches an intake endpoint it is stored. Also limit volume: one render loop can send thousands of identical events.

    Illustration 2: the realistic example

    A small reporter that normalises an error, scrubs it, groups by fingerprint, drops duplicates and enforces a send budget. It is plain Node (the send is replaced by a queue so it runs anywhere):

    import { createHash } from "node:crypto";
    
    const scrub = (text) =>
      text
        .replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, "[email]")
        .replace(/([?&](?:token|session|email)=)[^&\s]+/g, "$1[removed]");
    
    function frames(stack) {
      return stack
        .split("\n")
        .slice(1)
        .map((l) => l.trim().replace(/^at\s+/, "").replace(/:\d+:\d+\)?$/, "").replace(/\?.*$/, ""));
    }
    
    function fingerprint(report) {
      const top = frames(report.stack).slice(0, 3).join("|");
      return createHash("sha256").update(report.name + "|" + top).digest("hex").slice(0, 8);
    }
    
    function makeReporter({ perMinute, release }) {
      const seen = new Map();
      let sent = 0;
      const queue = [];
      return {
        report(error, context) {
          const entry = {
            name: error.name,
            message: scrub(error.message),
            stack: error.stack,
            release,
            url: scrub(context.url),
          };
          entry.fingerprint = fingerprint(entry);
          seen.set(entry.fingerprint, (seen.get(entry.fingerprint) ?? 0) + 1);
          if (seen.get(entry.fingerprint) > 1) return "deduplicated";
          if (sent >= perMinute) return "rate limited";
          sent += 1;
          queue.push(entry);
          return "queued";
        },
        queue,
        seen,
      };
    }
    
    const reporter = makeReporter({ perMinute: 2, release: "web@2026.12.01" });
    function boom(who) {
      return new TypeError(`Cannot read properties of undefined (user ${who})`);
    }
    const attempts = [
      [boom("ada@example.com"), { url: "https://shop.example/cart?token=abc123" }],
      [boom("bo@example.com"), { url: "https://shop.example/cart?token=zzz999" }],
      [new RangeError("Invalid array length"), { url: "https://shop.example/orders" }],
      [new SyntaxError("Unexpected token"), { url: "https://shop.example/help" }],
    ];
    for (const [error, context] of attempts) {
      console.log(error.name.padEnd(11), reporter.report(error, context));
    }
    console.log(JSON.stringify(reporter.queue[0], ["name", "message", "release", "url"], 2));
    console.log("occurrences by fingerprint:", [...reporter.seen.values()].join(","));

    Output, from running it in Node 26.13.1:

    TypeError   queued
    TypeError   deduplicated
    RangeError  queued
    SyntaxError rate limited
    {
      "name": "TypeError",
      "message": "Cannot read properties of undefined (user [email])",
      "release": "web@2026.12.01",
      "url": "https://shop.example/cart?token=[removed]"
    }
    occurrences by fingerprint: 2,1,1

    The two TypeErrors share a fingerprint although they name different users, so the second adds to a count and is not sent. The third distinct error is queued; the fourth is held back by the budget of two per period (a toy value). The email and the token are gone from the stored entry. The regular expressions are examples, not a complete personal-data filter.

    Sending the report

    The page can be closing exactly when it fails. MDN describes navigator.sendBeacon() as an asynchronous POST of a small amount of data that does not delay unload or the next navigation; the queued data is limited to 64 KiB; it returns true when the browser queued the data, which is not the same as the server receiving it. MDN also says the most reliable moment to send is the visibilitychange event, because unload and beforeunload often do not fire, especially on mobile. For other methods or response access it points to fetch() with keepalive. Send to your own origin or a single known intake, and expect that some reports will be lost: this channel is best effort.

    Figure 3. From a thrown error to a readable issue

    sequenceDiagram accTitle: From a thrown error to a readable issue accDescr: A user's browser throws an error in a minified bundle. The reporter scrubs it, adds the release and sends it with a beacon. The intake stores the raw event, looks up the source map uploaded by CI for that release, maps each frame to a source line, groups the event by fingerprint and shows an issue with a count. participant B as Browser reporter participant I as Intake participant M as Map store participant D as Developer B->>B: scrub, add release, fingerprint B->>I: beacon with minified stack I->>M: find map for release M-->>I: source map I->>I: map frames, group by fingerprint D->>I: opens issue (readable frames, count)

    How to read this: mapping happens on the server, after the browser has sent a minified stack. The browser never needs the map, which is why it can stay private.

    Illustration 3: a failure, three silent ways

    • "Script error." and nothing else. MDN says normal script elements pass minimal information to window.onerror for scripts that do not pass the standard CORS checks, and that the crossorigin attribute on the script enables error logging for sites that serve static files from a separate domain. The static host must also send CORS headers (see Same-Origin Policy and CORS); without both, reports from a CDN-hosted bundle carry no useful location.
    • The wrong map. A report from release A looked up against the map for release B gives plausible but wrong lines. The cure is the release tag and a build-time upload of every build.
    • Old bundles. A long-lived tab can keep running a retired release, so keep old maps while old bundles can still run.

    Trade-offs

    Choice Gain Cost
    Public full source maps Easy debugging by anyone Your source is readable by everyone
    Hidden maps uploaded to a tool Readable reports, source stays private An upload step, a release tag to keep right
    Group, dedupe and sample Few clear issues A rare bug may be under-counted; sampling hides single events
    Third-party tool Mapping, grouping and alerts built Data leaves your boundary; a script to load

    Build it

    This lesson has no lab. The two Node scripts above are self-contained. The first needs esbuild (installed in an empty folder), the second needs nothing. Both were run and their output is shown unedited. The browser hooks, sendBeacon, and the behaviour of any hosted service were not run here.

    In practice: the checkout page

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The marketplace ships its web app as a minified bundle. Support hears that "checkout sometimes does nothing" on certain phones. There is no error reporting, and the only data is the order count per hour, which dips after a release.

    Starting architecture

    Figure 4. No reporting

    Starting architecture: errors vanish in the browserCheckout to Orders API (requests); Orders API to Order count (counts)Checkout: no hooksCheckoutno hooksOrders API: only sees requestsOrders APIonly seesrequestsOrder count: hourly totalOrder counthourly totalrequestscounts

    How to read this: a script error before the request is sent never reaches the API, so the only signal is a lower count afterwards.

    Options considered

    Option What it fixes What it costs Risk
    Hosted error tool with uploaded maps Mapping, grouping, alerts Vendor, data transfer, a script Personal data in events
    Own beacon endpoint and map store Control Build and run it Weeks of work, grouping quality

    The decision

    Field Decision record
    Context Failures on real devices are invisible; releases are frequent.
    Decision Add a reporter on error, unhandledrejection and the React root callbacks. Build hidden maps in CI and upload them keyed by release. Scrub, fingerprint and cap reports in the browser. Send with a beacon on visibilitychange.
    Consequences, good Readable issues with counts per release; a regression is visible within one deploy.
    Consequences, bad An upload step in CI, a data-protection review, some lost reports.
    Revisit when Volume or cost grows, or a privacy review changes what may be collected.

    Rollout and verification

    1. Throw a test error in a staging build and confirm the issue shows the original file and line, not app.min.js.
    2. Confirm the release tag matches the map: deploy twice and check each report maps to its own release.
    3. Check the CDN does not serve the .map file and the bundle has no sourceMappingURL comment.
    4. Read ten stored events for emails and tokens before widening the rollout.

    The 2 a.m. failure

    After a deploy, the alert channel fills with one issue repeated tens of thousands of times, all with unreadable frames. The upload step failed silently in CI, so no map exists for the new release, and a render loop is reporting on every frame.

    First three checks: (1) look up the release tag and see whether a map exists for it; (2) check the reporter's rate limit and deduplication are active; (3) check whether the old release still produces the same error. Mitigation: roll back the release, or disable the failing component, and re-run the upload. Follow-up: make the pipeline fail when the map upload fails, and test the rate limiter.

    Architect's notes

    • Make the map upload part of the deploy. A release without its map is half-blind.
    • Treat reports as data you store. Scrub before sending, and decide retention.
    • Pair with traces. An error report says what broke; a correlation id says where in the request path.

    Common mistakes

    • Serving public source maps by accident because the bundler default adds the comment.
    • Forgetting crossorigin on scripts from a CDN domain, so errors show no location.
    • No release tag, so a map cannot be matched and regressions cannot be dated.
    • Sending full URLs and form values, which carry tokens and personal data.
    • No rate limit on the reporter.
    • Relying on unload to send.

    Key takeaways

    • Browsers expose error and unhandledrejection; frameworks add hooks; together they feed one reporter.
    • A source map (ECMA-426, version 3) is a lookup from generated positions to original ones; it must match the exact build.
    • Keep maps private: generate hidden maps and upload them to the tool that needs them.
    • A report needs a release, a route, a fingerprint and scrubbed data.
    • Send with a beacon on visibilitychange; accept that delivery is best effort.
    • Cross-origin scripts need crossorigin and CORS headers to give details to onerror.

    Practice exercises

    Exercise 1: Starter (30 min). Run the first script, then change the bug so that a different line fails and predict the mapped line before running it.

    Exercise 2: Intermediate (2 hours). Extend the reporter so that a duplicate increments a stored count and the count is sent once at the end of the period. Test the three paths: new, duplicate, over budget.

    Exercise 3: Advanced (half day). Write a short design for map handling on your own app: where maps are built and stored, who can read them, and what happens when an upload fails.

    The other side of this topic

    On the server, errors arrive with stack traces that need no mapping, and the problem is to attach the same request id and trace id as the browser report. The back end counterpart is covered by Correlation IDs and Trace Context Across Services and Problem Details Error Model.

    In this course:

    Planned in this module, named in plain text: logging, tracing and correlation ids for the front end; error boundaries and global error handling; OpenTelemetry in the browser; end-to-end observability from browser to database.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments