Next.js APM
Get the most out of Middleware OpsAI for your Next.js applications by using the Middleware Next.js SDK (version 1.4.0
or newer).
🚀 Key Features
- Supports function code capturing for runtime exceptions
- Works seamlessly with Next.js Framework
- Automatic sourcemap handling for better error debugging
🛠️ APM Setup
1. Install the Middleware next.js apm package and sourcemap uploader:
npm i @middleware.io/agent-apm-nextjs @middleware.io/sourcemap-uploader
2. Modify Config file:
Add the following config to your next.config.js
file. The config covers the following things:
- Enables sourcemaps for browser and server side code.
- Sets up instrumentation and exception capturing for next.js.
- Sets up sourcemap-uploader sdk to upload sourcemaps.
const MiddlewareWebpackPlugin = require("@middleware.io/sourcemap-uploader/dist/webpack-plugin").default; const nextConfig = { // ... // Your existing config productionBrowserSourceMaps: true, // for client side webpack: (config, { isServer }) => { config.plugins.push( new MiddlewareWebpackPlugin( "<ACCOUNT-KEY>", // Account key of the application.
If you're using next.js version < 14.0
, remove serverComponentsExternalPackages
line.
3. Create Instrumentation file:
Create a custom instrumentation.ts (or .js) file in your project root directory or inside the src folder.
// @ts-expect-error: The NextJS APM does not currently have full type declarations import tracker from '@middleware.io/agent-apm-nextjs'; export function register() { tracker.track({ serviceName: "<SERVICE-NAME>", accessToken: "<MW_API_KEY>" }); }
// @ts-expect-error: The NextJS APM does not currently have full type declarations import tracker from '@middleware.io/agent-apm-nextjs'; export function register() { tracker.track({ serviceName: "<SERVICE-NAME>", accessToken: "<MW_API_KEY>", enableExceptionHandling: true, target: "https://<MW_UID>.middleware.io:443", customResourceAttributes: { "app.version": "1.0.0"
Manual Exception Capture
For pages-router in nextjs, you have to manually capture exceptions:
// @ts-ignore import tracker from '@middleware.io/agent-apm-nextjs'; try { // Your code that might throw an error riskyOperation(); } catch (error) { // Manually capture the exception with custom attributes tracker.captureException(error);
⚙️ VCS Metadata Configuration (Recommended)
If your app has a .git
directory, the APM will auto-fetch repository URL, commit SHA, and other metadata for OpsAI.
If your app is containerized or does not have a .git
directory, set these environment variables to send VCS info to OpsAI (this helps generate solution PRs):
MW_VCS_COMMIT_SHA=$(git rev-parse HEAD) MW_VCS_REPOSITORY_URL=$(git config --get remote.origin.url)
These are just example commands to fetch values from Git. You can set these environment variables in any way that fits your workflow, such as through your CI/CD pipeline or other automation tools.