Navigate back to the homepage

Add Sentry to Vercel Next.js API Routes

Aryan Jabbari
May 10th, 2020 · 1 min read

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.ts
2import * as Sentry from '@sentry/node';
3import { NextApiRequest, NextApiResponse } from 'next';
4
5Sentry.init({ dsn: process.env.SENTRY_DSN });
6
7export default async (req: NextApiRequest, res: NextApiResponse) => {
8 try {
9 // ...your main business logic here
10 } 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';
3
4Sentry.init({ dsn: process.env.SENTRY_DSN });
5
6const 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};
18
19export default sentryHandler(async (req: NextApiRequest, res: NextApiResponse) => {
20 // ...your main business logic here
21});

You can extract the sentryHandler to its own file and wrap it around all the Next.js API routes you need Sentry to handle.

📧 Join my email list and get notified about new content

Stay updated with all my blog posts and future randomness!

More articles from The WebDev Coach

freeCodeCamp Pomodoro Clock 02: Lifting State Up and React Props

freeCodeCamp Pomodoro Clock 02: Lifting State Up and React Props This is the third installment of a tutorial series where I cover the…

February 10th, 2020 · 3 min read

freeCodeCamp Pomodoro Clock 01: React Functional Components and Local State Using Hooks

freeCodeCamp Pomodoro Clock 01: React Functional Components and Local State Welcome back! This tutorial is the second installment of a…

February 2nd, 2020 · 4 min read
© 2018–2020 The WebDev Coach
Link to $https://twitter.com/aryanjabbariLink to $https://www.youtube.com/c/thewebdevcoachLink to $https://dev.to/aryanjnycLink to $https://github.com/AryanJ-NYCLink to $https://www.linkedin.com/in/aryanjabbariLink to $https://www.instagram.com/thewebdevcoach/