Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JavaScript] Nuxt SDK #20

Open
hiroshinishio opened this issue Oct 6, 2024 · 44 comments
Open

[JavaScript] Nuxt SDK #20

hiroshinishio opened this issue Oct 6, 2024 · 44 comments

Comments

@hiroshinishio
Copy link
Owner

Important

This issue is tracking progress on the Nuxt SDK. If you find bugs or problems with the @sentry/nuxt package please open a separate issue. Thank you!

New SDK for https://nuxt.com/

There is an existing discussion: Sentry SDK for Nuxt

Nuxt uses nitro as their server, this means we'll need to have nitro support. It might make sense for us to create an OpenTelemetry instrumentation for nitro. It will also be valuable to add similar instrumentation for the other libraries Nuxt relies on:

### Alpha
- [ ] https://github.com/getsentry/sentry-javascript/issues/12572
- [x] Add client (vue) instrumentation
- [x] sentryNuxtPlugin for error handling
- [ ] https://github.com/getsentry/sentry-javascript/issues/12795
- [ ] https://github.com/getsentry/sentry-javascript/issues/12759
- [x] Add E2E tests
- [x] Add craft entry for Nuxt SDK
- [ ] https://github.com/getsentry/sentry-javascript/issues/13017
- [ ] https://github.com/getsentry/sentry-javascript/issues/13067
- [ ] https://github.com/getsentry/sentry-javascript/issues/13097
### Beta
- [ ] Create Nuxt Platfrom in Sentry
- [ ] https://github.com/getsentry/sentry-javascript/issues/13383
- [ ] https://github.com/getsentry/sentry-javascript/issues/13239
- [ ] https://github.com/getsentry/platformicons/issues/174
- [ ] https://github.com/getsentry/sentry-javascript/issues/13380
- [ ] https://github.com/getsentry/sentry-javascript/pull/13583
- [x] Nuxt: Vue component tracking https://github.com/getsentry/sentry-javascript/pull/13633
### Stable Release
- [ ] Nitro Route Parametrization
- [ ] Nuxt Setup Wizard
- [ ] Ensure deployment to Netlify works
- [ ] Nuxt 4 Support
### Nice to have/Stretch Goals
- [ ] Add Nuxt pages router instrumentation
- [ ] https://github.com/getsentry/sentry-javascript/issues/13813
- [ ] Add support for Nuxt Layers
- [ ] Add worker runtime support
- [ ] (if needed) Add native Nitro server engine support
- [ ] (if needed) Instrument Nuxt $fetch
- [ ] Instrument `useError` composable
- [ ] https://github.com/getsentry/sentry-javascript/issues/13341
@hiroshinishio
Copy link
Owner Author

See getsentry#6929

@hiroshinishio
Copy link
Owner Author

If you need insights from the Nuxt team at any time, please don't hesitate to reach out! 🙏

Copy link

gitauto-ai bot commented Oct 6, 2024

Click the checkbox below to generate a PR!

  • Generate PR

@hiroshinishio, You have 2 requests left in this cycle which refreshes on 2024-11-04 02:56:25+00:00.
If you have any questions or concerns, please contact us at info@gitauto.ai.

Copy link

Click the checkbox below to generate a PR!

  • Generate PR - gitauto-wes

@hiroshinishio, You have 3 requests left in this cycle which refreshes on 2024-11-05 22:45:17+00:00.
If you have any questions or concerns, please contact us at info@gitauto.ai.

@hiroshinishio
Copy link
Owner Author

This is such a great news!

It would be ideal that it would work on all envs.
Nuxt works very well on the edge (cloudflare workers, netlify edge, etc), however not all libraries are compatible as there are some restrictions (no eval, no new Function(), etc).

It would be great if sentry/nuxt would work everywhere from day one.

@hiroshinishio
Copy link
Owner Author

Thanks for the input! Which libraries do you mean with "not all libraries are compatible"?

@hiroshinishio
Copy link
Owner Author

Thanks for the input! Which libraries do you mean with "not all libraries are compatible"?

Hi , I don't have an extensive list, but for example AJV doesn't work. Workers don't use node, they use their own runtime (workerd) which is limited to web standards (similarly to deno).

I think if you use only sentry/core it should work as it's used by toucan-js which is an unofficial client for cloudflare workers. I think sentry/node won't work by default, but I might be wrong here.

@hiroshinishio
Copy link
Owner Author

This is of course for the backend part of nuxt, i.e. nitro. On the frontend sentry/vue should work perfectly.

@hiroshinishio
Copy link
Owner Author

I use Sentry on my APIs (fullstack Nuxt 3 deployment to Cloudflare pages) with the sentry/browser package on the API side to get around edge restrictions.

The context Sentry devs, for cosbgn's comment, is that Nuxt 3 was built with the "deploy anywhere" ethos, so all the core packages and (new) community modules are designed to be runtime agnostic. That's where https://unjs.io/ was born from.

I initially followed this guide if it helps at all with the PR in general https://www.lichter.io/articles/nuxt3-sentry-recipe (written by a core Nuxt 3 dev)

@hiroshinishio
Copy link
Owner Author

While we may not support worker (WinterCG) runtimes from the start we will look into it eventually. We are planning to release the SDK iteratively and in stages. Prioritization of worker runtime support depends of course a bit on the demand. I added an item to the list to track. Technically we have all the building blocks available.

@hiroshinishio
Copy link
Owner Author

I don't have any specific data, but from my understanding a big percent of nuxt apps are deployed on the edge (vercel-edge, workers, netlify edge, etc) as you get better performance for lower costs, and Nuxt pretty much "guarantees" that it will work on the edge, so it's an obvious solution.

I understand if you decide not to prioritize it, I just wanted to let you know that it would be great to have it from day one. It might be as simple as using sentry/core rather than sentry/node (I don't know, just an example).

Anyways, thanks for the first party package, love sentry and I would love to be able to add it to Nuxt easily!

@hiroshinishio
Copy link
Owner Author

Great initiative!

Could we also make sure that errors before the hydration are also handled?

@hiroshinishio
Copy link
Owner Author

We want to monitor as many as possible. The first release of the SDK will cover monitoring the majority of errors and we will definitely improve it over time

@hiroshinishio
Copy link
Owner Author

It would be great if this module could integrate /vite-plugin.
There could be a flag uploadSourcemaps, which automatically sets sourcemap: true in Nuxt config and configures sentryVitePlugin to upload sourcemaps. An option to delete public source maps at the end of the build would be appreciated. The sourcemaps.filesToDeleteAfterUpload option only deletes files after uploading the sourcemaps, but sourcemaps should always be removed when the flag is set, even if no sourcemaps were uploaded.

@hiroshinishio
Copy link
Owner Author

matching how our SvelteKit SDK works with vite plugin and our Next.js SDK works with our webpack plugin, we'll definitely have 1st class integration with the vite plugin in the Nuxt SDK!

For now you can use the sentry wizard which will automatically add the vite plugin to your vite config, but you'll still have to supply the options yourself.

npx /wizard -i sourcemaps

@hiroshinishio
Copy link
Owner Author

Hi, great initiative! Is there any ETA on this project? 🙂

@hiroshinishio
Copy link
Owner Author

Good news 🎉 You can already use the Nuxt SDK, there should not be breaking changes as of now. Version 8.23.0 is a good version to start using it and it offers new enhancements like filtering out transactions of build assets (_nuxt). Keep in mind the SDK is optimized for the production build (nuxt build -> nuxt preview). The readme gives you the setup instructions for the time being. The official docs are coming this week.

I would say it is in late alpha state as some features are still being implemented/tested and by having people already using the SDK we can get a solid understanding of which features are still missing or not working correctly.

@hiroshinishio
Copy link
Owner Author

Awesome, good news indeed! Thank you!

@hiroshinishio
Copy link
Owner Author

Maybe this is not the place to ask, feel free to delete, but I can't get past the part where you import the instrument when running yarn preview:

TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module ".output/public/instrument.server.mjs" is not a valid package name imported from ...

Any ideas?

"nuxt": "^3.12.4",
"/nuxt": "^8.24.0",

--- EDIT ---

I tried it on a clean project and it seems to work fine, so there's something up in my project!

--- EDIT 2 ---

Fixed with:

    "preview": "cross-env NODE_OPTIONS=\"--import file://$(pwd)/.output/public/instrument.server.mjs\" nuxt preview",

@hiroshinishio
Copy link
Owner Author

Thanks for reporting! Please open a new issue as it helps us avoid some back and fourth asking what you did and how you set up the SDK and so on. We'll take a look!

@hiroshinishio
Copy link
Owner Author

Any updates on when sourcemap support will be added to the SDK?

@hiroshinishio
Copy link
Owner Author

Source maps should already work for the client-side issues (docs here). Server-side source maps are coming soon.

@hiroshinishio
Copy link
Owner Author

"Add an --import flag to the NODE_OPTIONS environment variable wherever you run your application. For local previews, update your nuxt preview script in the package.json (see below). Also, ensure this environment variable is set in your deployment environment, such as on Netlify or Vercel."

Does this mean i should add it

"build": "NITRO_PORT=4000 NITRO_HOST=0.0.0.0 nuxt build",
"dev": "NITRO_PORT=3000 NITRO_HOST=0.0.0.0 NODE_TLS_REJECT_UNAUTHORIZED=0 nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"start": "NITRO_PORT=4000 NITRO_HOST=0.0.0.0 node .output/server/index.mjs"

To all of these??

@hiroshinishio
Copy link
Owner Author

Would be great if, within the sentry.client.config.ts file, we would able to use the runtime config:

https://nuxt.com/docs/api/composables/use-runtime-config

Example from other module:
https://formkit.com/getting-started/installation#using-environment-variables-in-formkitconfigts

The code below

import * as Sentry from '/nuxt'

Sentry.init({
  enabled: process.env.NUXT_PUBLIC_SENTRY_ENABLED,
})

Would then become:

import * as Sentry from '/nuxt'

export default defineSentryConfig(() => {

  const config = useRuntimeConfig()

  Sentry.init({
    enabled: config.public.sentry.enabled,
  })
})

@hiroshinishio
Copy link
Owner Author

Would be great if, with the sentry.client.config.ts file, we would able to use the runtime config

Ideally I'd prefer it if the sentry.client.config.ts was not required at all and all configutation was done in the 'sentry' key of the Nuxt Config.

@hiroshinishio
Copy link
Owner Author

you would have to update those two scripts:

"preview": "NODE_OPTIONS='--import ./public/instrument.server.mjs' nuxt preview",
"start": "NITRO_PORT=4000 NITRO_HOST=0.0.0.0 node  --import .output/public/instrument.server.mjs .output/server/index.mjs"

Those scripts are using the generated build output of nuxt. The Sentry Nuxt SDK is optimized for the production build, so you only have to add it here. Without this, the server-part is not fully instrumented.


We opted for having an external file as this gives you the possibility to pass functions like beforeSend (docs here). This would not be possible in the nuxt config. The nuxt config is only intended for Sentry build-time options like sourcemaps.

And thanks for providing the formkit example, this looks like a nice API. We are going to have a look at this and see if we can implement something like this as well!

@hiroshinishio
Copy link
Owner Author

Hi , thank you for the hard work so far :-) I have two questions with regard to the server instrumentation:

  1. I'd like to better understand the reasoning behind putting the server instrumentation into a file in the public folder. Nuxt hosts all files in public on the root of the project, e.g. ~/public/logo.svg would be available in the browser at http://localhost:3000/logo.svg (or at the respective production URL). Is there any need to publish the instrumentation file via a web server if it's only used when running the start or preview scripts from package.json? I guess the idiosyncratic way would be to put it into a scripts folder.

  2. Also, did you consider the alternative to initialize Sentry inside of the server-plugin as did here? We could pass all options from the nuxt config file, which could include functions as well?

@hiroshinishio
Copy link
Owner Author

Hey, thank you for your feedback!

is out today, she can answer in more detail on Monday!
Generally speaking, the main challenge we have is that we need to run Sentry in an --import flag, in order for ESM instrumentation to work. This means that you cannot just inject some script in v8 of the SDK into the server and have everything instrumented correctly, but you need to configure this at app boot time - which means you need to have the file to reference/import at the time that the nuxt server is started.

I am not saying that the public/ folder is necessarily the ideal solution, but this is the main constraint we have to work around - if we find a better way to do this, we'd definitely be happy to! We are still investigating different approaches here :)

@hiroshinishio
Copy link
Owner Author

Would be great if, within the sentry.client.config.ts file, we would able to use the runtime config:

https://nuxt.com/docs/api/composables/use-runtime-config

Example from other module: https://formkit.com/getting-started/installation#using-environment-variables-in-formkitconfigts

The code below

import * as Sentry from '/nuxt'

Sentry.init({
enabled: process.env.NUXT_PUBLIC_SENTRY_ENABLED,
})

Would then become:

import * as Sentry from '/nuxt'

export default defineSentryConfig(() => {

const config = useRuntimeConfig()

Sentry.init({
enabled: config.public.sentry.enabled,
})
})

Yeah, because right now there is no way to use Nuxt public config right?

@hiroshinishio
Copy link
Owner Author

It is in the public folder right now, because the file needs to be added to the build output as it is (to reference it in the node option input). But I agree that this is not 100% ideal and this will be changed probably.

About your 2. point: Do you mean creating a server-plugin yourself? The SDK already adds a server-plugin with the necessary hooks. But the initialization takes place in the instrument file and is loaded with the node option import. It has to be added with import to initialize sentry at the very start. This is needed for the otel instrumentation to work correctly in ESM (which Nuxt is). Without initializing the SDK at the very start, only the basic http instrumentation will work.

@hiroshinishio
Copy link
Owner Author

It is in the public folder right now, because the file needs to be added to the build output as it is (to reference it in the node option input). But I agree that this is not 100% ideal and this will be changed probably.

About your 2. point: Do you mean creating a server-plugin yourself? The SDK already adds a server-plugin with the necessary hooks. But the initialization takes place in the instrument file and is loaded with the node option import. It has to be added with import to initialize sentry at the very start. This is needed for the otel instrumentation to work correctly in ESM (which Nuxt is). Without initializing the SDK at the very start, only the basic http instrumentation will work.

Hi ,

can't we use late initiliazation to solve this?
When I understand the article correctly that would mean we can invoke Sentry.init at a later point, even within a server plugin removing the need for the file inside the public folder directory.

@hiroshinishio
Copy link
Owner Author

Yes, something like this could work. I am just trying different approaches.

@hiroshinishio
Copy link
Owner Author

some feedback from someone testing out the Nuxt SDK. Some of this feedback i think holds true regarding the file requirements for config of most of our JS SDKs, especially the meta frameworks.

running in dev, i notice that Nuxt has a dev tool bar, slightly (un)related but i wonder if Sentry could interact there? Like you could get more info about the error in browser in dev mode?

Tried it out today. Looking great! Here are just a few things I found that could use improvement IMO:

  1. having the instrument.server.mjs file in the public folder is kind of weird. Feels more natural in the root. Maybe can copy to public folder on build? Changing the commands for the build is also weird. I'm sure Daniel Roe or Alex Lichter could point you towards a better solution.

  2. Would be nice if you could do all the config in the nuxt.config.ts file instead of spread out across 3 different files

  3. I trigger an error in a server API endpoint and didn't see it reported in Sentry (https://nuxt.com/docs/guide/directory-structure/server)

  4. Would be cool if you could detect the app running in dev vs running in prod and automatically set the environment in sentry

  5. Didn't see an error with the fatal option set to true reported to sentry( throw createError({ fatal: true, message: "etc..." }) https://nuxt.com/docs/api/utils/create-error

Hope it helps!

@hiroshinishio
Copy link
Owner Author

I tested it for server, i use startSpan but nothing sent to "Performance".

@hiroshinishio
Copy link
Owner Author

thanks for trying out the SDK. Would you mind opening a new issue with reproduction steps? Thank you!

@hiroshinishio
Copy link
Owner Author

Hello,

Thank you for your work!

I'm encountering two significant issues while integrating Sentry into my Nuxt.js project:

1 - Sourcemap Upload Fails on Staging:

Local Build: When building the project locally, the sourcemap is successfully uploaded to Sentry. (
Only when the sentry.client.config.ts file is successfully created)
Staging Environment: On my staging environment (a test environment similar to production), the sourcemap upload fails with the following warning:

caused by: [60] SSL peer certificate or SSH remote key was not OK (SSL certificate problem: unable to get local issuer certificate)
error: API request failed

This may be due to server configuration, I will investigate

2 - Environment Variables Not Accessible:
I'm unable to access environment variables in both sentry.client.config.ts and instrument.server.mjs.
I've tried various approaches, but variables remain undefined.
Is there a known solution for this, or is it currently not feasible to access environment variables in these specific files?

3 - Attempted Solution with Nuxt Plugin:

I attempted to create a custom Nuxt plugin to cleanly manage the Sentry configuration, but in this case, the sourcemap upload doesn’t even trigger as the file seems to be unrecognized.

Thank you in advance for your feedback :)

@hiroshinishio
Copy link
Owner Author

I transferred your comment into a separate issue because otherwise this issue is gonna get messy af

@hiroshinishio
Copy link
Owner Author

Not sure what exactly from /node does not work in workers envs, but exactly for this runtimes there is https://github.com/robertcepa/toucan-js, check what it does differently.

How I use Sentry in Nuxt currently (without frontend logging):

nuxt.config.ts:

import { sentryVitePlugin } from "/vite-plugin";

const sentryReleaseName = process.env.CF_PAGES_COMMIT_SHA ?? 'unknown commit'

export default defineNuxtConfig({
  ...

  runtimeConfig: {
    public: {
      sentryDsn: 'xxx,
      sentryReleaseName,
    },
  },

  vite: {
    build: {
      sourcemap: true,
    },
    plugins: [
      // Put the Sentry vite plugin after all other plugins
      sentryVitePlugin({
        authToken: process.env.SENTRY_AUTH_TOKEN,
        org: "nuxt.config.ts",
        project: "xxx",
        release: {
          name: sentryReleaseName,
        },
      }),
    ],
  },
})

server/plugins/sentry.ts:

import { Toucan } from 'toucan-js'

export default defineNitroPlugin((nitroApp) => {
	const { public: { sentryDsn, sentryReleaseName } } = useRuntimeConfig()

	nitroApp.hooks.hook('error', (err, context) => {
		const incomingMessage = context.event?.node.req;
		const request = incomingMessage?.url ? new Request(incomingMessage.url, {
			method: incomingMessage.method,
		}) : undefined;

		const sentry = new Toucan({
			dsn: sentryDsn,
			release: sentryReleaseName,
			context: context.event,
			request,
			requestDataOptions: {
				allowedSearchParams: true,
			},
		})

		sentry.setTag('server', true)

		sentry.captureException(err)
	})
})

@hiroshinishio
Copy link
Owner Author

I don't know if this is of any help but nuxt scripts provides some options for better performance loading scripts (also npm scripts). Maybe adding a registry script could provide some features and help with the performance.

@hiroshinishio
Copy link
Owner Author

I haven't tested /nuxt with cloudflare workers so far as this feature will be included a little bit later. But feel free to open a separate issue (to better keep track of it) if you encounter any problems :)

Thanks for the input! I'm not quite sure how nuxt scripts can be used here. Perhaps you could explain a little more about how you thought this could be used in the SDK :)

@hiroshinishio
Copy link
Owner Author

Hi, site maps are not being generated, or at least not being read correctly when viewing an error.

Does Sentry automatically generate sitemaps via nuxt.config's sentry options (as listed in the docs), or is another command required?

@hiroshinishio
Copy link
Owner Author

If there is an issue with the experimental SDK feel free to open a new issue in our repository as it makes it easier to keep track of things 🙌

I am not sure what you mean with "sitemaps" - we don't generate sitemaps. In case you mean source maps: Yes, they are generated and uploaded automatically if you provide the sourceMapsUploadOptions and you don't need another command :)

@hiroshinishio
Copy link
Owner Author

Thanks for the input! I'm not quite sure how nuxt scripts can be used here. Perhaps you could explain a little more about how you thought this could be used in the SDK :)

So the idea is to optimize the page loading performance by using nuxt scripts and prevent possible errors with SSR. For example it provides a proxy object to track events and will fire them when it is fully set up.
The slogan on the page says

Nuxt Scripts lets you load third-party scripts with better performance, privacy, security and DX

and

Nuxt Scripts provides an abstraction layer on top of third-party scripts, providing SSR support and type-safety and while still giving you full low-level control over how a script is loaded.

But as mentioned before: I am not sure if it would be possible to adapt the logic so it could be integrated.

@hiroshinishio
Copy link
Owner Author

Re: nuxt scripts. I think we need to look into it a bit further. Superficially I can say that the upside it gives is probably very slim since the Sentry SDK needs to load very early on in the pageload for a bunch of important features (errors, performance, replay). The DX is definitely an argument.

For now, I think we'll try to focus on shipping a robust SDK without using nuxt scripts but there is nothing that prevents us from migrating to that pattern later on. (also note that nuxt scripts are in beta - to some degree atleast)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant