Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Avoiding Sentry Impact on Client-side bundle size in Next JS via sending error data to the server route #17427

stepan-twnty started this conversation in Show and tell
Discussion options

To avoid increasing bundle size, I created a route that I use for sending all Errors from the client. Here is an example:

// /pages/api/glitchtip/exception.TS
import * as Sentry from '@sentry/nextjs'
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
 if (req.method === 'POST') {
 Sentry.captureException(new Error(JSON.stringify(req.body)))
 res.status(200).json({})
 }
 res.status(200).json({})
}
//UTILS.TS
export const addExceptionToLog = async (message: unknown) => {
 let body: { name: string; message: string; stack?: string } | undefined
 if (message instanceof Error) {
 body = {
 name: message.name,
 message: message.message,
 stack: message.stack,
 ...(message.cause ? { cause: message.cause } : {}), // Spread `cause` only if it exists
 }
 }
 if (typeof message === 'string') {
 body = {
 name: '',
 message,
 }
 }
 await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}api/glitchtip/exception/`, {
 method: 'POST',
 headers: {
 'Content-Type': 'application/json',
 },
 body: JSON.stringify(body || message),
 }).catch(() => null)
}
//SOME CLIENT FILE
...
 const submitHandler = handleSubmit(async (data) => {
 try {
 setInternalStatus(Status.loading)
 const verifyResponseData = await verifyToken(data['cf-turnstile-response'])
 if (!verifyResponseData.success) {
 void addExceptionToLog(`Captcha verify failed ${JSON.stringify(verifyResponseData)}`)
 return void setInternalStatus(Status.failed)
 }
 onSubmit({ email: data.email, firstName: data.firstName })
 } catch (error) {
 void addExceptionToLog(`Contact form sending failed ${error}`)
 setInternalStatus(Status.failed)
 }
 })
 ...

I understand that a lot of features are not working, but actually, I only need the Error name, on what page it happened, and a simple trace (optional), and it looks like everything that I need, Sentry captured.

Maybe someone has some suggestions on how to improve this way of using Sentry on the client side?

You must be logged in to vote

Replies: 1 comment 1 reply

Comment options

hey @Lms24.
Maybe you have to add smth?

You must be logged in to vote
1 reply
Comment options

Hey @stepan-twnty thanks for the ping! If this works for you, I see nothing wrong with it :) As you already pointed out, this requires you to manually catch errors everywhere. So all the auto-instrumentation around errors (but also tracing fwiw), won't work with this setup. But I fully get the tradeoff here!

Some other side effects of this approach:

  • I'm not sure if stack traces will get parsed correctly. The stack trace format of browsers (chromium, FF, webkit, etc) differs from Node/server runtimes and if you capture the exception on the server, our Node/server stack parser will attempt to parse a browser-generated stack trace. You'll have to check if this works sufficiently well for you.
  • The point above also means that likely errors won't get source-mapped correctly back to the original source code. Again, a tradeoff you have to consider.
  • Sentry will treat this error as an error captured on the server-side. Probably not the end of the world but I could see this being confusing. Also quite confusing if you set up distributed tracing
  • Manually capturing errors will mark them as handled: true, (whereas automatic instrumentation usually sets handled: false) which in terms of accuracy really depends on if you actually handle the error or not :). You can override this though, if you wish, for example in beforeSend or directly in the captureException call.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /