|
| 1 | +--- |
| 2 | +title: Server side usage |
| 3 | +description: how to use nuxt-applicationinsights server side |
| 4 | +--- |
| 5 | + |
| 6 | +# Getting started server side |
| 7 | + |
| 8 | +## In pure nitro context. |
| 9 | + |
| 10 | +In a pure nitro context (in the server dir), you can access to applicationinsights which uses [nitro-opentelemetry](https://github.com/huang-julien/nitro-opentelemetry). |
| 11 | + |
| 12 | +`nitro-opentelemetry` is a small nitro module to correctly hook events from nitro to opentelemetry and applicationinsights (since v3) makes use of it. |
| 13 | + |
| 14 | +There is two ways of using applicationinsights in nitro. You can either access the singleton `Applicationinsights` by importing the default client (setup by [nitro-applicationinsights](https://nitro-applicationinsights.julien-huang.dev/)): |
| 15 | + |
| 16 | + |
| 17 | +```ts |
| 18 | +import Applicationinsights from "applicationinsights" |
| 19 | + |
| 20 | +export default defineTracedEventHandler((event) => { |
| 21 | + // ... |
| 22 | + |
| 23 | + Applicationinsights.trackEvent(/* ... */) |
| 24 | + |
| 25 | + // ... |
| 26 | +}) |
| 27 | +``` |
| 28 | + |
| 29 | +Either modify the `Span` within the event. |
| 30 | + |
| 31 | +```ts |
| 32 | +export default defineTracedEventHandler((event) => { |
| 33 | + // ... |
| 34 | + |
| 35 | + event.otel.span.addAttribute(/* ... */) |
| 36 | + |
| 37 | + // ... |
| 38 | +}) |
| 39 | +``` |
| 40 | + |
| 41 | +## Within a Nuxt app |
| 42 | + |
| 43 | +Within a Nuxt app, `nuxt-applicationinsights` will inject the `Applicationinsights` singleton to `useNuxtApp().$appInsights` server-side. |
| 44 | + |
| 45 | +Because `Applicationinsights` from `@microsoft/applicationinsights-web` has a very similar API to the server-side singleton of `applicationinsights`, `nuxt-applicationinsights` with create and inject `Applicationinsights` from `@microsoft/applicationinsights-web` to `useNuxtApp().$appInsights` client-side. |
| 46 | + |
| 47 | +```html |
| 48 | +<template> |
| 49 | + <!----> |
| 50 | +</template> |
| 51 | + |
| 52 | +<script setup lang="ts"> |
| 53 | +useNuxtApp().$appInsights.trackEvent(/* */) |
| 54 | +</script> |
| 55 | +``` |
| 56 | + |
| 57 | +Since components are universal in Nuxt (run server and client side), if you're `opentelemetry`, you will need to put everything behind a `import.meta.server` flag. |
| 58 | + |
| 59 | + |
| 60 | +```html |
| 61 | +<template> |
| 62 | + <!----> |
| 63 | +</template> |
| 64 | + |
| 65 | +<script setup lang="ts"> |
| 66 | +
|
| 67 | +if(import.meta.server) { |
| 68 | + useNuxtApp().ssrContext!.event.otel.span.addAttribute(/* */) |
| 69 | +} |
| 70 | +</script> |
| 71 | +``` |
0 commit comments