### Install Sentry using the wizard Source: https://docs.sentry.io/platforms/javascript/guides/nextjs Run this command in your terminal to start the Sentry installation wizard for Next.js. The wizard will guide you through selecting features like error monitoring, tracing, and session replay. ```bash npx @sentry/wizard@latest -i nextjs ``` -------------------------------- ### Verify Next.js Setup with Sample Error Source: https://docs.sentry.io/platforms/javascript/guides/nextjs Run your development server and visit the example page to test Sentry integration. This page includes a button to trigger a sample error for verification. ```bash npm run dev ``` -------------------------------- ### Implement the `setup` Hook in a Custom Integration Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/custom The `setup` hook is called during SDK initialization and receives the client instance. Use this hook to run code when the SDK is first set up. ```javascript const integration = { name: "MyAwesomeIntegration", setup(client) { setupCustomSentryListener(client); }, }; ``` -------------------------------- ### Install @sentry/node-native Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/event-loop-block Install the Sentry Node.js native package using npm, yarn, or pnpm. ```bash npm install @sentry/node-native ``` -------------------------------- ### Install Sentry SDK Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router Install the Sentry SDK for Next.js using npm. This command adds the necessary package to your project dependencies. ```bash npm install @sentry/nextjs --save ``` -------------------------------- ### Configure Default User Feedback Integration (NPM) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/user-feedback/configuration Use the default feedback integration, which is an alias for `feedbackSyncIntegration`, when installing via NPM. This setup includes basic SDK configuration. ```javascript import * as Sentry from "@sentry/browser"; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [ // Use the default strategy, an alias for `feedbackSyncIntegration` Sentry.feedbackIntegration({ // Additional SDK configuration goes in here, for example: colorScheme: "system", }), ], }); ``` -------------------------------- ### Install Node.js Profiling Package Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/profiling/node Install the `@sentry/profiling-node` package using npm. Ensure the version matches your main Sentry SDK package. ```bash npm install @sentry/profiling-node --save ``` -------------------------------- ### Install Sentry Testkit Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/best-practices/sentry-testkit Install the Sentry Testkit package as a development dependency using npm, yarn, or pnpm. ```bash npm install sentry-testkit --save-dev ``` -------------------------------- ### Initialize Sentry with Custom OpenTelemetry Setup Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/opentelemetry/custom-setup Use this snippet when you have a custom OpenTelemetry setup and want Sentry to integrate with it. Set `skipOpenTelemetrySetup: true` and manually configure Sentry's OpenTelemetry components. ```javascript const Sentry = require("@sentry/node"); const { SentrySpanProcessor, SentryPropagator, SentrySampler, } = require("@sentry/opentelemetry"); const { NodeTracerProvider } = require("@opentelemetry/sdk-trace-node"); const sentryClient = Sentry.init({ dsn: "https://@o.ingest.sentry.io/", skipOpenTelemetrySetup: true, // The SentrySampler will use this to determine which traces to sample tracesSampleRate: 1.0, }); // Note: This could be BasicTracerProvider or any other provider depending on // how you are using the OpenTelemetry SDK const provider = new NodeTracerProvider({ // Ensure the correct subset of traces is sent to Sentry // This also ensures trace propagation works as expected sampler: sentryClient ? new SentrySampler(sentryClient) : undefined, spanProcessors: [ // Ensure spans are correctly linked & sent to Sentry new SentrySpanProcessor(), // Add additional processors here ], }); provider.register({ // Ensure trace propagation works // This relies on the SentrySampler for correct propagation propagator: new SentryPropagator(), // Ensure context & request isolation are correctly managed contextManager: new Sentry.SentryContextManager(), }); // Validate that the setup is correct Sentry.validateOpenTelemetrySetup(); ``` -------------------------------- ### startSession Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/apis Starts a new session for tracking release health. Sessions help in monitoring the overall health of your application releases. ```APIDOC ## startSession ### Description Starts a new session for tracking release health. Sessions help in monitoring the overall health of your application releases. ### Method ```javascript function startSession(): Session ``` ``` -------------------------------- ### Manually Start Session Replay Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/session-replay/understanding-sessions Initialize Sentry with replay integration and manually start a replay session or buffer. This is necessary when sample rates are set to 0. ```javascript Sentry.init({ dsn: "...", // This initializes Replay without starting any session replaysSessionSampleRate: 0, replaysOnErrorSampleRate: 0, integrations: [Sentry.replayIntegration()], }); // You can access the active replay instance from anywhere in your code like this: const replay = Sentry.getReplay(); // This starts in `session` mode, regardless of sample rates replay.start(); // OR // This starts in `buffer` mode, regardless of sample rates replay.startBuffering(); ``` -------------------------------- ### startNewTrace Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/apis Starts a new trace that is active within the scope of the provided callback function. ```APIDOC ## startNewTrace ### Description Start a new trace that is active in the provided callback. ### Method ```javascript function startNewTrace(callback: () => T): T ``` ### Parameters #### Path Parameters - **callback** (() => T) - Required - The callback function within which the new trace will be active. ``` -------------------------------- ### Initialize Sentry with RewriteFrames (npm) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/rewriteframes This snippet shows how to initialize Sentry using npm and include the rewriteFramesIntegration. Ensure you have the SDK package installed. ```javascript import * as Sentry from ""; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [Sentry.rewriteFramesIntegration()], }); ``` -------------------------------- ### Initialize Sentry with ContextLines Integration (npm) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/contextlines Use this snippet to initialize Sentry with the ContextLines integration when using npm. Ensure you have the SDK package installed. ```javascript import * as Sentry from ""; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [Sentry.contextLinesIntegration()], }); ``` -------------------------------- ### Basic AI Agent Monitoring Setup Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/ai-agent-monitoring Integrate AI monitoring by adding the relevant AI library integration to your Sentry configuration. Ensure tracing is enabled. ```javascript import * as Sentry from ""; import { openAIIntegration } from ""; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", tracesSampleRate: 1.0, streamGenAiSpans: true, integrations: [openAIIntegration()], }); ``` -------------------------------- ### Initialize with CaptureConsole Integration (npm) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/captureconsole Use this snippet to initialize Sentry with the captureConsoleIntegration when using npm. Ensure you have the SDK package installed. ```javascript import * as Sentry from ""; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [Sentry.captureConsoleIntegration()], }); ``` -------------------------------- ### Initialize Sentry with Dedupe Integration (npm) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/dedupe Configure Sentry initialization using npm, including the dedupe integration. Ensure you have the SDK package installed. ```javascript import * as Sentry from ""; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [Sentry.dedupeIntegration()], }); ``` -------------------------------- ### Initialize Sentry with Statsig Integration Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/statsig Initialize the Statsig client and then use it to configure the Sentry SDK with the statsigIntegration. Ensure Statsig is installed and instrumented in your app before using this. ```javascript import * as Sentry from "@sentry/nextjs"; import { StatsigClient } from "@statsig/js-client"; const statsigClient = new StatsigClient( YOUR_SDK_KEY, {userID: "my-user-id"}, {}, ); // see Statsig SDK reference. Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [ Sentry.statsigIntegration({ featureFlagClient: statsigClient }), ], }); await statsigClient.initializeAsync(); // or statsigClient.initializeSync(); const result = statsigClient.checkGate("my-feature-gate"); Sentry.captureException(new Error("something went wrong")); ``` -------------------------------- ### Implement the `setupOnce` Hook for One-Time Initialization Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/custom The `setupOnce` hook runs only once, even if `Sentry.init()` is called multiple times. Use this for initialization logic that should not be repeated. ```javascript const integration = { name: "MyAwesomeIntegration", setupOnce() { wrapLibrary(); }, }; ``` -------------------------------- ### Manual Instrumentation with OpenAI Client Wrapper (Options) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/openai Demonstrates how to use the `instrumentOpenAiClient` helper with specific options for manual instrumentation. This allows fine-grained control over what data is captured. ```javascript const client = Sentry.instrumentOpenAiClient(openai, { // your options here }); ``` -------------------------------- ### Heartbeat Monitoring with Sentry.captureCheckIn() Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/crons Use a single check-in with `Sentry.captureCheckIn()` for heartbeat monitoring. This setup only notifies Sentry if the job fails to start. For detecting exceeded maximum runtime, use the two-step check-in method. ```javascript // Execute your scheduled task... // 🟢 Notify Sentry your job completed successfully: Sentry.captureCheckIn({ monitorSlug: "", status: "ok", }); ``` ```javascript // 🔴 Notify Sentry your job has failed: Sentry.captureCheckIn({ monitorSlug: "", status: "error", }); ``` -------------------------------- ### Use `afterAllSetup` Hook After All Integrations Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/custom The `afterAllSetup` hook is triggered after all other integrations have completed their `setupOnce` and `setup` hooks. It receives the client instance and is useful when your integration depends on other integrations having already run. ```javascript const integration = { name: "MyAwesomeIntegration", afterAllSetup(client) { // We can be sure that all other integrations // have run their `setup` and `setupOnce` hooks now startSomeThing(client); }, }; ``` -------------------------------- ### Start Span for Cache Get Operation Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/tracing/instrumentation/caches-module Use this snippet to manually create a Sentry span for retrieving data from a cache. Ensure you set appropriate attributes like 'cache.key', 'cache.hit', and 'op'. The 'cache.item_size' attribute is optional and should be used cautiously. ```javascript const key = "myCacheKey123"; Sentry.startSpan( { name: key, attributes: { "cache.key": [key], "network.peer.address": "cache.example.com/supercache", "network.peer.port": 9000, }, op: "cache.get", }, (span) => { // Set a key in your caching using your custom caching solution const value = my_caching.get(key); const cacheHit = Boolean(value); if (cacheHit) { span.setAttribute("cache.item_size", JSON.stringify(value).length, // Warning: if value is very big this could use lots of memory); } span.setAttribute("cache.hit", cacheHit); } ); ``` -------------------------------- ### init Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/apis Initializes the Sentry SDK with the provided options. Refer to the Options documentation for a full list of configurable parameters. ```APIDOC ## init ### Description Initializes the SDK with the given options. ### Method function init(options: InitOptions): Client | undefined ### Parameters #### Request Body - **options** (InitOptions) - Required - Configuration options for the SDK. See [Options](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options.md) for details. ``` -------------------------------- ### Example SourceMappingURL Comment Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/troubleshooting_js/legacy-uploading-methods This is an example of a sourceMappingURL comment found in a minified JavaScript file. ```javascript // -- end script.min.js (located at http://localhost:8000/scripts/script.min.js) //# sourceMappingURL=script.min.js.map ``` -------------------------------- ### Automatic Instrumentation Examples Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/tracing Examples of operations that create spans automatically in different Next.js runtimes. ```tsx // All of these create spans automatically // Client: navigation creates a span Dashboard; // Server: API route creates a span export async function GET() { return Response.json({ data }); } // Server Component: creates a span export default async function Page() { const data = await fetchData(); return
{data}
; } ``` -------------------------------- ### Monitor Alert Filter Example Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/crons An example filter to match monitor slugs for Sentry alerts. ```text The event's tags match monitor.slug equals my-monitor-slug-here ``` -------------------------------- ### Initialize Sentry with Async Feedback Integration (CDN) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/user-feedback/configuration Configure Sentry using the CDN installation method and explicitly use the feedbackAsyncIntegration. This strategy loads the feedback widget asynchronously, minimizing initial bundle size. ```javascript import * as Sentry from "@sentry/browser"; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [ // Use the async strategy so everything is bundled for page load Sentry.feedbackAsyncIntegration({ // Additional SDK configuration goes in here, for example: colorScheme: "system", }), ], }); ``` -------------------------------- ### Initialize Sentry with FileSystem Integration Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/fs Use this to enable filesystem instrumentation. This integration only works in Node.js and Bun runtimes. ```javascript Sentry.init({ integrations: [Sentry.fsIntegration()], }); ``` -------------------------------- ### Prisma Schema Configuration for Tracing Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v8-to-v9 For Prisma versions prior to 6, enable the `tracing` preview feature in your `schema.prisma` file to support performance instrumentation. ```bash generator client { provider = "prisma-client-js" previewFeatures = ["tracing"] } ``` -------------------------------- ### Install source-map globally Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/troubleshooting_js Install the Mozilla source-map library globally to enable local validation of source map files. ```bash npm install -g source-map ``` -------------------------------- ### Initialize Sentry and LaunchDarkly SDKs Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/launchdarkly This snippet shows how to initialize both the Sentry SDK with the LaunchDarkly integration and the LaunchDarkly client. Ensure you have installed both SDKs and have your DSN and LaunchDarkly client ID. ```javascript import * as Sentry from "@sentry/nextjs"; import * as LaunchDarkly from "launchdarkly-js-client-sdk"; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [Sentry.launchDarklyIntegration()], }); const ldClient = LaunchDarkly.initialize( "my-client-ID", { kind: "user", key: "my-user-context-key" }, { inspectors: [Sentry.buildLaunchDarklyFlagUsedHandler()] }, ); // Evaluate a flag with a default value. You may have to wait for your client to initialize first. ldClient?.variation("test-flag", false); Sentry.captureException(new Error("Something went wrong!")); ``` -------------------------------- ### Initialize Sentry with Dedupe Integration (CDN) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/dedupe Set up Sentry using CDN bundles, including the main bundle and the dedupe bundle. Initialize Sentry with the DSN and the dedupe integration. ```html ``` -------------------------------- ### Initialize Sentry with RewriteFrames (CDN) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/rewriteframes This example demonstrates initializing Sentry with the rewriteFramesIntegration using CDN links for both the main bundle and the rewriteframes module. It includes the necessary script tags and Sentry.init configuration. ```html ``` -------------------------------- ### Configure HttpClient Integration with CDN Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/httpclient This example shows the configuration for the HttpClient integration when using Sentry's CDN. It includes loading the necessary bundles and initializing Sentry with the integration. ```html ``` -------------------------------- ### Example Usage of LinkedErrors Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/linkederrors This example demonstrates how an error with a 'cause' property can be captured by Sentry, leveraging the LinkedErrors integration to include the underlying error information. ```APIDOC ## Example: Capturing Linked Errors ### Description This example shows a common scenario where an error is thrown during an asynchronous operation (like fetching data). A new error is created, and the original error is assigned to its `cause` property. Sentry's LinkedErrors integration will then capture both errors. ### Method Event Listener and Error Handling ### Endpoint N/A (Client-side JavaScript execution) ### Request Example ```javascript document .querySelector("#get-reviews-btn") .addEventListener("click", async (event) => { const movie = event.target.dataset.title; try { const reviews = await fetchMovieReviews(movie); renderMovieReviews(reviews); } catch (e) { const fetchError = new Error( `Failed to fetch reviews for: ${movie}`, ); fetchError.cause = e; // Assigning the original error as the 'cause' Sentry.captureException(fetchError); renderMovieReviewsError(fetchError); } }); ``` ### Response N/A (Error captured by Sentry, not a direct API response) ``` -------------------------------- ### Start and Stop Manual Profiling Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/profiling/browser In manual profiling mode, you can explicitly start and stop the profiler around specific code blocks you want to analyze. ```javascript Sentry.uiProfiler.startProfiler(); // Code here will be profiled Sentry.uiProfiler.stopProfiler(); ``` -------------------------------- ### Configure HttpClient Integration with Loader (v7) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/httpclient This example shows how to configure the HttpClient integration using the Sentry Loader script (v7). The `sentryOnLoad` function must be configured before the loader script is added. ```html ``` -------------------------------- ### Control Sampling Based on Environment with tracesSampler Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/tracing/configure-sampling This example demonstrates how to adjust sampling rates based on the application's environment (e.g., development, production, staging). It ensures higher sampling in development and a controlled rate in production. ```javascript tracesSampler: (samplingContext) => { const { inheritOrSampleWith } = samplingContext; // Sample all transactions in development if (process.env.NODE_ENV === "development") { return 1.0; } // Sample 5% in production if (process.env.NODE_ENV === "production") { return 0.05; } // Sample 20% in staging return inheritOrSampleWith(0.2); } ``` -------------------------------- ### Install Mastra Sentry Exporter Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/ai-agent-monitoring/mastra Install the Mastra Sentry exporter package using npm. Other package managers like yarn or pnpm can also be used. ```bash npm install @mastra/sentry@latest ``` -------------------------------- ### Start New Trace in Callback Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/apis Starts a new trace that is active for the duration of the provided callback function. Any spans created within this callback will belong to this new trace. ```typescript function startNewTrace(callback: () => T): T ``` -------------------------------- ### Install source-map library globally Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/troubleshooting_js/legacy-uploading-methods Install the `source-map` npm module globally to use it for local verification of your generated source maps. This is a prerequisite for running the local testing script. ```bash npm install -g source-map ``` -------------------------------- ### Configure ExtraErrorData with CDN Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/extraerrordata This example demonstrates setting up ExtraErrorData using Sentry's CDN. It involves loading the main bundle and the specific extraerrordata bundle, followed by initialization. ```html ``` -------------------------------- ### Start Browser Tracing Navigation Span Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/apis Manually starts a navigation span on the client-side. The span is automatically ended when the page is considered idle. Primarily used if `browserTracingIntegration` is opted out of. ```typescript function startBrowserTracingNavigationSpan(client: Client, options: StartSpanOptions): Span | undefined ``` -------------------------------- ### Initialize ReportingObserver with Loader (v8) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/reportingobserver Set up the ReportingObserver integration with the Sentry Loader script version 8. This uses `sentryOnLoad` and lazy loads the integration. ```html ``` -------------------------------- ### Start Execute Tool Span Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/ai-agent-monitoring This snippet demonstrates how to start and complete an 'execute_tool' span in Sentry. It captures the tool's name, operation, and arguments, and then sets the result after the tool execution. ```javascript await Sentry.startSpan( { op: "gen_ai.execute_tool", name: "execute_tool get_weather", attributes: { "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "get_weather", "gen_ai.tool.call.arguments": JSON.stringify({ location: "Paris" }), }, }, async (span) => { const result = await getWeather({ location: "Paris" }); span.setAttribute("gen_ai.tool.call.result", JSON.stringify(result)); }, ); ``` -------------------------------- ### Start Browser Tracing Page Load Span Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/apis Manually starts a page load span on the client-side. The span is automatically ended when the page is considered idle. Primarily used if `browserTracingIntegration` is opted out of. ```typescript function startBrowserTracingPageLoadSpan(client: Client, options: StartSpanOptions): Span | undefined ``` -------------------------------- ### Initialize Sentry with DSN Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options Provide your Sentry DSN to initialize the SDK and direct events to your project. This is the minimum required configuration. ```javascript Sentry.init({ dsn: "https://@o.ingest.sentry.io/", }); ``` -------------------------------- ### Zero-Config Mastra Setup with Sentry Exporter Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/ai-agent-monitoring/mastra Configure Mastra to use the Sentry exporter with minimal setup, relying on environment variables for configuration. Ensure the necessary Sentry environment variables are set. ```javascript import { Mastra } from "@mastra/core"; import { Observability } from "@mastra/observability"; import { SentryExporter } from "@mastra/sentry"; export const mastra = new Mastra({ observability: new Observability({ configs: { sentry: { serviceName: "my-service", exporters: [new SentryExporter()], }, }, }), }); ``` -------------------------------- ### Initialize Sentry with ModuleMetadata (npm) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/modulemetadata Configure Sentry using npm by importing the SDK and the moduleMetadataIntegration. This snippet shows the basic initialization with a DSN and the integration. ```javascript import * as Sentry from ""; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [Sentry.moduleMetadataIntegration()], }); ``` -------------------------------- ### Configure Async User Feedback Integration (NPM) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/user-feedback/configuration Implement the async strategy for user feedback integration to maintain a lower bundle size. This approach is beneficial for NPM installations where bundle size is a concern. ```javascript import * as Sentry from "@sentry/browser"; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [ // Use the async strategy to keep bundle size lower Sentry.feedbackAsyncIntegration({ // Additional SDK configuration goes in here, for example: colorScheme: "system", }), ], }); ``` -------------------------------- ### getFeedback Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/apis Get the feedback integration if it has been added. ```APIDOC ## getFeedback ### Description Get the feedback integration, if it has been added. This can be used to access the feedback integration in a type-safe way. ### Method ``` function getFeedback(): ReturnType | undefined ``` ``` -------------------------------- ### Start Application with Event Loop Monitoring Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/event-loop-block Launch a Node.js application using the --import flag to automatically apply Sentry's event loop block instrumentation to all worker threads. ```bash node --import instrument.mjs app.mjs ``` -------------------------------- ### Crontab Schedule Example Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/crons Defines a cron job schedule using the crontab format. ```json {"type": "crontab", "value": "0 * * * *"} ``` -------------------------------- ### Initialize Sentry with ContextLines Integration (CDN) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/contextlines This snippet shows how to initialize Sentry with the ContextLines integration using CDN links. It includes loading the main bundle and the contextlines module separately. ```html ``` -------------------------------- ### Interval Schedule Example Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/crons Defines a cron job schedule using an interval with a specified unit. ```json {"type": "interval", "value": 2, "unit": "hour"} ``` -------------------------------- ### Configure Sentry with Google Gen AI Wrapper (Manual) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/google-genai Wrap your Google Gen AI client instance with `instrumentGoogleGenAIClient` for manual instrumentation, passing any desired configuration options. ```javascript const client = Sentry.instrumentGoogleGenAIClient(genAI, { // your options here }); ``` -------------------------------- ### Start an active span Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/tracing/instrumentation Use startSpan to automatically manage the lifecycle of a span during a synchronous or asynchronous callback. ```javascript const result = Sentry.startSpan({ name: "Important Function" }, () => { return expensiveFunction(); }); ``` ```javascript const result = await Sentry.startSpan( { name: "Important Function" }, async () => { const res = await doSomethingAsync(); return updateRes(res); }, ); ``` ```javascript const result = await Sentry.startSpan( { name: "Important Function", }, async () => { const res = await Sentry.startSpan({ name: "Child Span" }, () => { return expensiveAsyncFunction(); }); return updateRes(res); }, ); ``` -------------------------------- ### Example Zod Error Data Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/zodErrors Representation of the enhanced error information captured by the integration when a Zod validation fails. ```json [ { "code": "too_small", "path": ["name"], "message": "Name is required", "minimum": 1, "type": "string", "inclusive": true, "received": "" }, { "code": "invalid_string", "path": ["email"], "message": "Invalid email format", "validation": "email", "received": "invalid-email" } ] ``` -------------------------------- ### Instrument with startSpan Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v7-to-v8/v8-new-performance-api Starts a span that automatically ends when the provided callback completes. Supports both synchronous and asynchronous callbacks. ```JavaScript Sentry.startSpan( { name: "my-span", attributes: { attr1: "my-attribute", attr2: 123, }, }, (span) => { // do something that you want to measure // once this is done, the span is automatically ended } ); ``` ```JavaScript Sentry.startSpan( { name: "my-span", attributes: {}, }, async (span) => { // do something that you want to measure await waitOnSomething(); // once this is done, the span is automatically ended } ); ``` -------------------------------- ### Initialize with CaptureConsole Integration (CDN) Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/captureconsole This snippet shows how to initialize Sentry with the captureConsoleIntegration when using CDN links. It includes loading the main bundle and the captureconsole bundle. ```html ``` -------------------------------- ### Initialize ReportingObserver with npm Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/reportingobserver Integrate the ReportingObserver into your Sentry setup when using npm. Ensure Sentry is initialized with your DSN. ```javascript import * as Sentry from ""; Sentry.init({ dsn: "https://@o.ingest.sentry.io/", integrations: [Sentry.reportingObserverIntegration()], }); ``` -------------------------------- ### Manually Set Up Browser Client in Shared Environments Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/best-practices/shared-environments Use this approach to set up a Sentry BrowserClient manually in shared environments. It filters out integrations that rely on global state and initializes the client after setting it on the scope. This method is suitable for browser extensions, VSCode extensions, and other scenarios with multiple Sentry instances. ```javascript import { BrowserClient, defaultStackParser, getDefaultIntegrations, makeFetchTransport, Scope, } from "@sentry/browser"; // filter integrations that use the global variable const integrations = getDefaultIntegrations({}).filter( (defaultIntegration) => { return ![ "BrowserApiErrors", "BrowserSession", "Breadcrumbs", "ConversationId", "GlobalHandlers", "FunctionToString", ].includes(defaultIntegration.name); }, ); const client = new BrowserClient({ dsn: "https://@o.ingest.sentry.io/", transport: makeFetchTransport, stackParser: defaultStackParser, integrations: integrations, }); const scope = new Scope(); scope.setClient(client); client.init(); // initializing has to be done after setting the client on the scope // You can capture exceptions manually for this client like this: scope.captureException(new Error("example")); ``` -------------------------------- ### Setting Tags and Context on Scope Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v7-to-v8/v8-new-performance-api Use `Sentry.withScope` to set tags on the scope before starting a span. These tags will be available on the span. ```JavaScript Sentry.withScope((scope) => { scope.setTag("my-tag", "tag-value"); Sentry.startSpan({ name: "my-span" }, (span) => { // do something here // span will have the tags from the containing scope }); }); ``` -------------------------------- ### Initialize Sentry with Pino Integration Source: https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/pino Enable the Pino integration for Sentry by including `Sentry.pinoIntegration()` in your Sentry.init configuration. This captures all Pino logs. ```javascript Sentry.init({ enableLogs: true, integrations: [Sentry.pinoIntegration()], }); ```