Load Sentry asynchronously only on error

To prevent a performance penalty by loading Sentry even if no errors occur, we wrote a small handler that lazy loads Sentry.

As I need to homeschool kids nowadays, I don't have time to write tests. So as all hell breaks loose I use Sentry so that I at least will be bombarded with JS error reports to keep me sane. But... If for some miraculous reason I didn't make any mistake, you end up with almost 60kb of useless JavaScript. As your local internet plumber I don't want that so I wrote a small handler that lazy loads Sentry only when an error occurs:

if (process.env.NODE_ENV === 'production') {  // trust me, only do it in production
  const captureError = async error => {
    try {
      console.error(error) // Log error to console for clarification
      const Sentry = await import('@sentry/browser')
        dsn: `YOUR_DSN`,
        release: `YOUR_RELEASE`
    } catch (e) {
      // all fails, reset window.onerror to prevent infinite loop on window.onerror
      console.error('Logging to Sentry failed', e)
      window.onerror = null
  window.onerror = (message, url, line, column, error) => captureError(error)
  window.onunhandledrejection = event => captureError(event.reason)

There you go! Happy debugging 🐛

← Alle blogposts

Ook verliefd op het web?

Technologie en gebruikservaring. Snel, toegankelijk en een plezier om te gebruiken. Maar ook een plezier om te ontwikkelen. Geldt dit ook voor jou?

Kom ons versterken