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 🐛

← All blog posts

Also in love with the web?

For us, that’s about technology and user experience. Fast, available for all, enjoyable to use. And fun to build. This is how our team bands together, adhering to the same values, to make sure we achieve a solid result for clients both large and small. Does that fit you?

Join our team