> ## Documentation Index
> Fetch the complete documentation index at: https://mw-docs.middleware.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js

> Next.js APM - Setup & Installation Docs | Middleware

<a target="_blank" href="https://www.npmjs.com/package/@middleware.io/agent-apm-nextjs">
  <span
    style={{
    background: "url(https://img.shields.io/npm/v/%40middleware.io%2Fagent-apm-nextjs) no-repeat",
    width: "125px",
    height: "20px",
    display: "inline-block",
}}
  />
</a>

| Traces | Metrics | App Logs | Custom Logs | Profiling |
| :----: | :-----: | :------: | :---------: | :-------: |
|    ✅   |    ✖️   |    ✖️    |      ✅      |     ✅     |

This guide walks you through setting up Application Performance Monitoring (APM) on a Next.js application. These instructions can also be found on the Installation page in your Middleware Account. View example code [here](https://github.com/middleware-labs/demo-apm/tree/master/nextjs).

# Prerequisites

<Steps>
  <Step title="Infra Agent">
    Infrastructure Agent (Infra Agent). To install the Infra Agent, see our [Installation Guide](https://docs.middleware.io/docs/agent-installation/overview).

    <Note> Although the Infra Agent is not required for the Next.js APM, we recommend installing it for improved performance. </Note>
  </Step>

  <Step title="Next.js Version">
    `Next.js version 13.4` or above. Check your Next.js version with the following command:

    ```bash Shell theme={null}
    npx next --version
    ```
  </Step>

  <Step title="OpenTelemetry Version">
    `@opentelemetry/api` package version >= `v1.3.0` and \< `v1.5.0`:

    ```bash Shell theme={null}
    npm install @opentelemetry/api”>=1.3.0 <1.5.0”
    ```
  </Step>
</Steps>

# Install

### Step 1: Install `Next.js` APM Package

Run the following command in your terminal:

```bash Shell  theme={null}
npm install @middleware.io/agent-apm-nextjs
```

### Step 2: Modify Config File

Add the following code to your `next.config.js` file:

```javascript Next.js theme={null}
const nextConfig = {
    experimental: {
        instrumentationHook: true,
        serverComponentsExternalPackages: ['@middleware.io/agent-apm-nextjs']
    }
}
module.exports = nextConfig
```

### Step 3: Container Variables

Applications running in a container require an additional environment variable. If your application is not running in a container, move to [Step 4](/apm-configuration/next-js#step-4-create-instrumentation-file).

#### Docker

Add the following environment variable to your application:

```bash Shell theme={null}
MW_AGENT_SERVICE=<DOCKER_BRIDGE_GATEWAY_ADDRESS>
```

<Note> The `DOCKER_BRIDGE_GATEWAY_ADDRESS` is the IP address of the gateway between the Docker host and bridge network. This is `172.17.0.1` by default.
Learn more about Docker bridge networking [here](https://docs.docker.com/network/network-tutorial-standalone/) </Note>

#### Kubernetes

Add the following environment variable to your application deployment YAML file:

```bash Shell theme={null}
MW_AGENT_SERVICE=mw-service.mw-agent-ns.svc.cluster.local

```

For Kubernetes clusters, add the following environment variable to your application:

```bash Shell theme={null}
kubectl get service --all-namespaces | grep mw-service
```

### Step 4: Create Instrumentation File

1. Create a custom `instrumentation.ts (or .js)` file in your project `root` directory or inside the `src` folder

<Warning>The `instrumentation.ts` file must be located at the `root` of your project unless you are using the `src` directory. If you are using the `src` directory, ensure the `instrumentation.ts` file is placed within the `src` directory, alongside the pages and app directories.</Warning>

2. Synchronize your instrumentation filename if you are using the `pagesExtension` config option to add suffixes

<Note> Example: If you use `pagesExtension: ['ts']`, the instrumentation file should be named `instrumentation.ts`. </Note>

3. Add the below code snippet depending on your current setup:

<Tabs>
  <Tab title="Infra Agent Installed">
    ```javascript Next.js theme={null}
        // @ts-ignore
        import tracker from '@middleware.io/agent-apm-nextjs';
        export function register() {
            tracker.track({
                serviceName: "<SERVICE-NAME>",
                accessToken: "<xxxxxxxxxx>"
            });
        }
    ```
  </Tab>

  <Tab title="Infra Agent NOT Installed">
    ```javascript Next.js theme={null}
        // @ts-ignore
        import tracker from '@middleware.io/agent-apm-nextjs';
        export function register() {
            tracker.track({
                serviceName: "<SERVICE-NAME>",
                accessToken: "<ACCESS-TOKEN>",
                target: "https://{ACCOUNT-UID}.middleware.io"
            });
        }
    ```
  </Tab>
</Tabs>

### Step 5: Enable Logging

Ingest custom logs by using the following functions based on desired log severity levels:

```javascript Next.js theme={null}
// @ts-ignore
import tracker from '@middleware.io/agent-apm-nextjs';
export default async function handler(req, res) {
    // ...
    // Your existing code
    tracker.info("Info Sample");
    tracker.warn("Warn Sample", {
        "tester": "Alex",
    });
    tracker.debug("Debug Sample");
    tracker.error("Error Sample");
    // ...
    // Your existing code
}
```

### Step 6: Deploy your Project

<Note>If you’re looking to set up a sample Next.js project with API routes, you can use the following command in your terminal: `npx create-next-app@latest --example api-routes`</Note>

# Continuous Profiling

Continuous profiling captures real-time performance insights from your application to enable rapid identification of resource allocation, bottlenecks, and more. Navigate to the [Continuous Profiling](https://docs.middleware.io/workflow/profiling#continuous-profiling) section to learn more about using Continuous Profiling with the Next.js APM.

<Note> Need assistance or want to learn more about Middleware? Contact us at support\[at]middleware.io. </Note>
