add logsnag to next.js app in typescript

index.ts
// Install the necessary dependencies
npm install --save @lognag/node @logsnag/browser @types/logsnag__browser @types/logsnag__node

// Import Logsnag and create a new instance
import Logsnag from '@logsnag/node'
const logsnag = new Logsnag({ apiKey: process.env.LOGSNAG_API_KEY })

// Import the error handler
import { NextPage } from 'next'
import { withErrorLogging } from '@logsnag/next-plugin'

// Define a new Next.js page with the error handler higher order function
const IndexPage: NextPage = withErrorLogging(({ data }) => {
  return (
    <div onClick={() => { throw new Error('User clicked on something they shouldn\'t have') }}>
      Click here to throw an error
    </div>
  )
})

// Create a custom _app.tsx file
import { AppPropsType } from 'next/dist/next-server/lib/utils'
import { LogsnagErrorBoundary } from '@logsnag/browser'
import '../styles/globals.css'

function MyApp({ Component, pageProps }: AppPropsType) {
  return (
    <LogsnagErrorBoundary logsnag={logsnag}>
      <Component {...pageProps} />
    </LogsnagErrorBoundary>
  )
}

export default MyApp

1085 chars
36 lines

In the example above, we install the necessary dependencies, import Logsnag and create a new instance, import the withErrorLogging higher order function for Next.js pages, and define a new page using the withErrorLogging function.

We also create a custom _app.tsx file and wrap it in the LogsnagErrorBoundary component provided by Logsnag to capture errors that may occur throughout the application.

With these implementations, any errors that occur within the app will be captured by Logsnag and sent to the specified project.

gistlibby LogSnag