Skip to main content

[JavaScript] Why do I see HeadlessChrome errors with Invalid or unexpected token?

Issue

I get JavaScript events from a HeadlessChrome user agent with Invalid or unexpected token. The stack location changes from event to event, and frames sometimes point at node_modules. I want to stop this noise.

Applies To

  • All SaaS Customers and Self-Hosted Users

  • JavaScript SDK

  • Inbound Filters

  • Error Monitoring

Resolution

Sentry is capturing a real exception from a browser whose user agent contains HeadlessChrome. That traffic is often a scraper running your JavaScript. Drop those events if they are not from your own tests.

If you want to filter known crawlers in the project:

In Settings > Projects > [your project] > Inbound Filters, enable Filter out errors known to be caused by web crawlers. That filter uses the user agent and covers named crawlers plus generic bots. HeadlessChrome can still get through. See Web Crawler Errors.

If HeadlessChrome is scraping your own site:

Allowed Domains will not drop it, because Origin and Referer are your domain. Drop the event in beforeSend by matching HeadlessChrome in the User-Agent header:

Sentry.init({
  beforeSend(event) {
    const userAgent = event.request?.headers?.["User-Agent"] || "";
    if (userAgent.includes("HeadlessChrome")) {
      return null;
    }
    return event;
  },
});

Match the User-Agent string, not contexts.browser.name. Headless Chrome often still reports as Chrome. See beforeSend.

If the scrape loads your script on someone else’s domain, use Allowed Domains instead. See How do I filter out errors caused by users scraping my site?.

If you run HeadlessChrome in your own tests:

Do not drop every HeadlessChrome event. Send test traffic with a distinct environment, or skip the filter for that environment.

If you see mechanism:onerror:

That tag means GlobalHandlers captured an uncaught exception. It does not mean the event is invalid. Filter on the user agent, not on that mechanism.

Did this answer your question?