getsentry / sentry-javascript

Official Sentry SDKs for JavaScript
https://sentry.io
MIT License
7.89k stars 1.56k forks source link

Trace pageloads on Next.js app router #9571

Closed lforst closed 4 months ago

lforst commented 10 months ago

We would like to trace page loads for the Next.js app router. This would involve somehow passing trace data for Next.js app router SSR to the client for the initial page load.

Currently, we are blocked here by React/Next.js because there is no real way to transparently transfer trace data to the client.


Update (Jan 23, 2024)

We have identified a way to pass trace data from Server Components to the client for page loads. It involves using the useServerInsertedHTML hook. One thing that is important to know up-front is that this hook can only be used in client components ("use client").

In an ideal world, the implementation would look as follows:

We automatically wrap all of the user's server components and make their server components render a client component which returns null (so we're not actually putting anything in the users page) but are calling userServerInsertedHTML inside to render <meta /> tags containing sentry-trace and baggage data. The <meta /> tag data can then be picked up by the browser SDK to continue the trace.

What blocks us?

MrLoh commented 8 months ago

Hi, I'm working on coming up with an error-handling strategy for a Next.js 14 app. I'm wondering why this can’t be achieved with cookies or headers today already.

lforst commented 8 months ago

@MrLoh What do you mean exactly? Out of principle, we cannot have the SDK set cookies. Also, I don't see how cookies would help pass a value from SSR to the client. All that aside, Next.js doesn't let you write to cookies in server components.

Similar goes for headers. You generally cannot read headers from within JS for the initial document request (only exception being the Server-Timing) header. Additionally, Next.js doesn't let you write headers from within server components.

If I am missing something or you have concrete suggestions on how to solve this let me know!

lforst commented 8 months ago

Yesterday I stumbled on Next.js' useServerInsertedHTML which is pretty much undocumented except for being included here: https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components

I have a stupid idea that we can use this to solve our problems.

lforst commented 5 months ago

I opened an upstream PR that would solve this issue: https://github.com/vercel/next.js/pull/64256

lforst commented 4 months ago

Resolved by https://github.com/getsentry/sentry-javascript/pull/12157