• /
  • EnglishEspañolFrançais日本語한국어Português
  • EntrarComeçar agora

Esta tradução de máquina é fornecida para sua comodidade.

Caso haja alguma divergência entre a versão em inglês e a traduzida, a versão em inglês prevalece. Acesse esta página para mais informações.

Criar um problema

Next.js instrumentation with the Hybrid Agent

The recommended way to monitor a Next.js application is to rely on the native OpenTelemetry spans emitted by Next.js together with the Node.js agent's Hybrid Agent feature, rather than the agent's built-in Next.js instrumentation. This page explains how to enable the Hybrid Agent, points to example applications, and covers common questions about injecting the browser agent and deploying to cloud providers.

Importante

Native Next.js OpenTelemetry support requires Node.js agent version 14.1.0 or later. The Hybrid Agent only instruments the Node.js runtime; the Next.js edge runtime is not supported, which is why the register() example below exits early unless NEXT_RUNTIME is nodejs.

In addition, we currently only support the Hybrid Agent approach for Next.js versions 16 and above.

The Node.js agent has had Next.js instrumentation since 2022 through @newrelic/next, and that instrumentation was bundled into the agent in 12.0.0. However, it was limited and didn't work when deploying to cloud providers like Vercel, AWS Amplify, Netlify, or Azure Static Web Apps. With the introduction of the Hybrid Agent, the Node.js agent can intercept OpenTelemetry spans and synthesize the telemetry that drives the New Relic experience. Native Next.js OpenTelemetry instrumentation was added in 14.1.0.

Enable the Hybrid Agent

To enable the Hybrid Agent and disable the agent instrumentations that conflict with Next.js, set the following configuration in newrelic.js:

'use strict'
exports.config = {
app_name: ['Your application name'],
license_key: 'your-license-key',
opentelemetry: {
enabled: true
},
instrumentation: {
http: {
enabled: false
},
next: {
enabled: false
},
undici: {
enabled: false
}
}
}

Dica

Se você fizer chamadas nativas do fetch, deverá desabilitar a instrumentação do undici, conforme mostrado acima. O Next.js envolve o fetch e cria seus próprios spans de cliente, portanto, deixar o undici habilitado produz spans de cliente duplicados em seus traces.

Se você preferir usar variáveis de ambiente:

NEW_RELIC_LICENSE_KEY=<your-license-key>
NEW_RELIC_APP_NAME=<your-application-name>
NEW_RELIC_OPENTELEMETRY_ENABLED=true
NEW_RELIC_INSTRUMENTATION_NEXT_ENABLED=false
NEW_RELIC_INSTRUMENTATION_HTTP_ENABLED=false
NEW_RELIC_INSTRUMENTATION_UNDICI_ENABLED=false

Você também deve adicionar um arquivo instrumentation.js (ou instrumentation.ts para TypeScript) para carregar o agente antes do restante do seu aplicativo:

async function loadNewRelicAgent() {
const { default: newrelic } = await import('newrelic')
const agent = newrelic?.agent
if (!agent || agent.collector?.isConnected?.()) {
return
}
await new Promise((resolve) => {
const done = () => {
clearTimeout(timer)
agent.removeListener('started', done)
agent.removeListener('errored', done)
resolve()
}
const timer = setTimeout(done, 8000)
agent.once('started', done)
agent.once('errored', done)
})
}
export async function register() {
// The agent only instruments the Node.js runtime, not the edge runtime.
if (process.env.NEXT_RUNTIME !== 'nodejs') {
return
}
await loadNewRelicAgent()
}

Confira o aplicativo de exemplo Next.js App Router para ver um exemplo mais completo dessa configuração.

Next.js instrumentação em Vercel

Implantar no Vercel divide as páginas estáticas e dinâmicas em ambientes diferentes. Em vez de depender de .env e newrelic.js para carregar a configuração do agente, defina as seguintes variáveis de ambiente no console do Vercel em Environment Variables:

NEW_RELIC_LICENSE_KEY=<your-license-key>
NEW_RELIC_APP_NAME=<your-application-name>
NEW_RELIC_OPENTELEMETRY_ENABLED=true
NEW_RELIC_INSTRUMENTATION_NEXT_ENABLED=false
NEW_RELIC_INSTRUMENTATION_HTTP_ENABLED=false
NEW_RELIC_INSTRUMENTATION_UNDICI_ENABLED=false

Você ainda precisa do arquivo instrumentation.js descrito acima; apenas a origem da configuração muda no Vercel.

Confira o aplicativo de exemplo Next.js App Router para ver um exemplo mais completo dessa configuração.

Injete o agente do browser

Como o Next.js é um framework full-stack, a maioria dos clientes deseja observabilidade tanto no cliente quanto no servidor. O exemplo a seguir mostra como injetar o agente do browser do New Relic em todas as páginas.

Edite o arquivo de layout raiz dentro de app/ e adicione o seguinte:

import Script from 'next/script';
async function loadNewRelicAgent() {
const { default: newrelic } = await import('newrelic')
const agent = newrelic?.agent
if (!agent || agent.collector?.isConnected?.()) {
return newrelic
}
await new Promise((resolve) => {
const done = () => {
clearTimeout(timer)
agent.removeListener('started', done)
agent.removeListener('errored', done)
resolve()
}
const timer = setTimeout(done, 8000)
agent.once('started', done)
agent.once('errored', done)
})
return newrelic
}
export default async function RootLayout({
children,
}){
// Wait for the agent to connect before requesting the browser timing header.
const newrelic = await loadNewRelicAgent()
const browserTimingHeader = newrelic.getBrowserTimingHeader({
hasToRemoveScriptWrapper: true,
allowTransactionlessInjection: true,
})
return (
<html lang="en">
<body className="min-h-full flex flex-col">{children}</body>
<Script
// Inline scripts require an id.
// See https://nextjs.org/docs/app/building-your-application/optimizing/scripts#inline-scripts
id='nr-browser-agent'
// "beforeInteractive" loads the script before the page becomes interactive.
strategy='beforeInteractive'
// The script body is the browser timing header generated above. Because
// `hasToRemoveScriptWrapper` is true, the header is raw JavaScript with no
// surrounding <script> tag, so we inject it with `dangerouslySetInnerHTML`.
dangerouslySetInnerHTML={{ __html: browserTimingHeader }}
/>
</html>
);
}

Confira o aplicativo de exemplo Next.js App Router para ver um exemplo mais completo dessa configuração.

Copyright © 2026 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.