> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-parallel-read-in-order-multi-part.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> SDK do Next.js para o ClickStack - a stack de observabilidade do ClickHouse

# Next.js

export const ClickStackIntegrates = ({signals = []}) => {
  const list = Array.isArray(signals) ? signals : String(signals).split(",");
  const supported = list.map(s => String(s).trim().toLowerCase());
  const pillStyle = {
    display: "inline-flex",
    alignItems: "center",
    padding: "0.125rem 0.625rem",
    borderRadius: "9999px",
    fontSize: "0.8125rem",
    fontWeight: 500,
    lineHeight: 1.6,
    color: "#161517",
    backgroundColor: "#faff69",
    border: "1px solid rgba(0, 0, 0, .1)",
    marginRight: "0.5rem"
  };
  return <div style={{
    margin: "0 0 1.25rem"
  }}>
      <span style={{
    marginRight: "0.5rem"
  }}>Este guia integra:</span>
      {supported.includes("logs") && <span style={pillStyle}>Logs</span>}
      {supported.includes("metrics") && <span style={pillStyle}>Métricas</span>}
      {supported.includes("traces") && <span style={pillStyle}>Rastreamentos</span>}
    </div>;
};

O ClickStack pode ingerir traces nativos do OpenTelemetry das suas
[funções serverless do Next.js](https://nextjs.org/docs/pages/building-your-application/optimizing/open-telemetry#manual-opentelemetry-configuration)
no Next 13.2+.

<ClickStackIntegrates signals={['logs', 'traces']} />

<Note>
  Se você estiver procurando por replay de sessão/monitoramento no navegador, instale a [integração Browser](/pt-BR/clickstack/ingesting-data/sdks/browser).
</Note>

<h2 id="installing">
  Instalação
</h2>

<h3 id="enable-instrumentation-hook">
  Habilite o hook de instrumentação (obrigatório para a v15 e anteriores)
</h3>

Para começar, você precisará habilitar o hook de instrumentação do Next.js definindo `experimental.instrumentationHook = true;` no arquivo `next.config.js`.

**Exemplo:**

```javascript theme={null}
const nextConfig = {
  experimental: {
    instrumentationHook: true,
  },
  // Ignorar avisos de pacotes otel 
  // https://github.com/open-telemetry/opentelemetry-js/issues/4173#issuecomment-1822938936
  webpack: (
    config,
    { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack },
  ) => {
    if (isServer) {
      config.ignoreWarnings = [{ module: /opentelemetry/ }];
    }
    return config;
  },
};

module.exports = nextConfig;
```

<h3 id="install-sdk">
  Instale o SDK OpenTelemetry do ClickHouse
</h3>

<Tabs>
  <Tab title="NPM">
    ```shell theme={null}
    npm install @hyperdx/node-opentelemetry 
    ```
  </Tab>

  <Tab title="Yarn">
    ```shell theme={null}
    yarn add @hyperdx/node-opentelemetry 
    ```
  </Tab>
</Tabs>

<h3 id="create-instrumentation-files">
  Criar arquivos de instrumentação
</h3>

Crie um arquivo chamado `instrumentation.ts` (ou `.js`) na raiz do seu projeto Next.js com o seguinte conteúdo:

```javascript theme={null}
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { init } = await import('@hyperdx/node-opentelemetry');
    init({
      apiKey: '<YOUR_INGESTION_API_KEY>', // optionally configure via `HYPERDX_API_KEY` env var
      service: '<YOUR_SERVICE_NAME>', // optionally configure via `OTEL_SERVICE_NAME` env var
      additionalInstrumentations: [], // optional, default: []
    });
  }
}
```

Isso permitirá que o Next.js importe a instrumentação do OpenTelemetry para qualquer invocação de função serverless.

<h3 id="configure-environment-variables">
  Configure as variáveis de ambiente
</h3>

Se você estiver enviando traces diretamente para o ClickStack por meio do OpenTelemetry, precisará iniciar seu
servidor Next.js com as seguintes variáveis de ambiente para direcionar os spans ao OTel collector:

<Tabs>
  <Tab title="Managed ClickStack">
    ```sh copy theme={null}
    OTEL_SERVICE_NAME=<YOUR_SERVICE_NAME> \
    OTEL_EXPORTER_OTLP_ENDPOINT=<YOUR_OTEL_COLLECTOR_HTTP_ENDPOINT>
    npm run dev
    ```
  </Tab>

  <Tab title="ClickStack Open Source">
    ```sh copy theme={null}
    HYPERDX_API_KEY=<YOUR_INGESTION_API_KEY> \
    OTEL_SERVICE_NAME=<YOUR_SERVICE_NAME> \
    OTEL_EXPORTER_OTLP_ENDPOINT=<YOUR_OTEL_COLLECTOR_HTTP_ENDPOINT>
    npm run dev
    ```
  </Tab>
</Tabs>

Se você estiver implantando na Vercel, certifique-se de que todas as variáveis de ambiente acima estejam configuradas
na sua implantação.
