Add Sentry to Vercel Next.js API Routes
To add Sentry to Next.js, you can wrap your entire route in a try
block and have the Sentry reporting done in the catch
block:
1// /pages/api/someRoute.ts2import * as Sentry from '@sentry/node';3import { NextApiRequest, NextApiResponse } from 'next';45Sentry.init({ dsn: process.env.SENTRY_DSN });67export default async (req: NextApiRequest, res: NextApiResponse) => {8 try {9 // ...your main business logic here10 } catch (error) {11 Sentry.captureException(error);12 await Sentry.flush(2000);13 return error;14 }15};
Of course, writing that catch
block over and over is bad programming practice. We can wrap the try/catch
in a higher order function:
1import * as Sentry from '@sentry/node';2import { NextApiRequest, NextApiResponse, NextApiHandler } from 'next';34Sentry.init({ dsn: process.env.SENTRY_DSN });56const sentryHandler = (apiHandler: NextApiHandler) => {7 return async (req: NextApiRequest, res: NextApiResponse) => {8 try {9 return await apiHandler(req, res);10 } catch (error) {11 console.error(error);12 Sentry.captureException(error);13 await Sentry.flush(2000);14 return error;15 }16 };17};1819export default sentryHandler(async (req: NextApiRequest, res: NextApiResponse) => {20 // ...your main business logic here21});
You can extract the sentryHandler
to its own file and wrap it around all the Next.js API routes you need Sentry to handle.