Guide

Step 1: Install Next.js APM package

Run the command below in your terminal to install Middleware’s Next.js APM package:

npm install @middleware.io/agent-apm-nextjs

Step 2: Modify the next.config.js file

As this feature is experimental, you need to explicitly opt-in by adding the following code to your next.config.js file:

const nextConfig = {
     ---
     ---
     experimental: {
         instrumentationHook: true
     }
     ---
     ---
}
module.exports = nextConfig

Step 3: Create an Instrumentation file

Create a custom instrumentation.ts file in your project root directory, and add the following code as per your choice:

  • If you are using Vercel platform to deploy your projects, then use the code snippet below for serverless functions:
// @ts-ignore
import { track } from '@middleware.io/agent-apm-nextjs';

export function register() {
    track({
        projectName: "<PROJECT-NAME>",
        serviceName: "<SERVICE-NAME>",
        target: "vercel",
    });
}
After Deploying your project on Vercel, you need to integrate the Middleware from the marketplace. You can find more details here. To get a better idea, you can clone the sample project from the GitHub repository.
// @ts-ignore
import { track } from '@middleware.io/agent-apm-nextjs';

export function register() {
    track({
        projectName: "<PROJECT-NAME>",
        serviceName: "<SERVICE-NAME>",
    });
}
  • If you want to instrument your project without installing any host, then use the code snippet below:
// @ts-ignore
import { track } from '@middleware.io/agent-apm-nextjs';

export function register() {
    track({
        projectName: "<PROJECT-NAME>",
        serviceName: "<SERVICE-NAME>",
        accountKey: "{ACCOUNT_KEY}",
        target: "https://{ACCOUNT-UID}.middleware.io"
    });
}

Note for APM inside Kubernetes

If you are using APM in a Kubernetes cluster make sure to follow these 2 steps:

Step 1 : Find your Middleware Service namespace

For older setup, your “mw-service” can be inside mw-agent-ns-{FIRST-5-LETTERS-OF-API-KEY} namespace For newer setup, we simplified the namespace name to mw-agent-ns

Step 2 : Set this ENV variable in your application deployment YAML

MW_AGENT_SERVICE=mw-service.NAMESPACE.svc.cluster.local
Please replace “NAMESPACE” with the correct value that you found from Step 1.