Examples

Complete examples of @sophonz/nextjs in an App Router project — minimal setup, adding attributes in Route Handlers and Server Actions, and database query tracing.

Every example below targets the App Router and works as written. Why each file belongs where it does is covered in Installation; this page shows only the finished shape.

Minimal setup

Four files, and it does not get smaller than this.

.env
NEXT_PUBLIC_SOPHONZ_COLLECTOR_URL=https://in.sophonz.ai
NEXT_PUBLIC_SOPHONZ_APP_NAME=my-app
NEXT_PUBLIC_SOPHONZ_APP_KEY=app-key-replace-me
NEXT_PUBLIC_SOPHONZ_PROJECT=my-project
NEXT_PUBLIC_SOPHONZ_ENVIRONMENT=production
instrumentation.ts
export { register } from '@sophonz/nextjs/server';
app/layout.tsx
import { SophonzProvider } from '@sophonz/nextjs/client';
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <SophonzProvider>{children}</SophonzProvider>
      </body>
    </html>
  );
}
next.config.js
module.exports = {
  serverExternalPackages: ['@sophonz/nextjs', '@sophonz/node-sdk'],
};

instrumentation.ts goes at the project root, not inside app/. In a project using a src/ directory it is src/instrumentation.ts.

Configuring in code

The same setup with the values in code rather than environment variables. Each side takes its own configuration.

instrumentation.ts
import { register as sophonz } from '@sophonz/nextjs/server';
 
export const register = () =>
  sophonz({
    appName: 'my-app',
    appKey: process.env.SOPHONZ_APP_KEY,
    project: 'my-project',
    deploymentEnvironment: process.env.NODE_ENV,
    server: {
      advancedNetworkCapture: true,
    },
  });
app/layout.tsx
import { SophonzProvider } from '@sophonz/nextjs/client';
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <SophonzProvider
          appName="my-app"
          appKey={process.env.NEXT_PUBLIC_SOPHONZ_APP_KEY}
          project="my-project"
        >
          {children}
        </SophonzProvider>
      </body>
    </html>
  );
}

Client-side values have to reach the browser bundle, so they must come from NEXT_PUBLIC_-prefixed variables. The server side can read unprefixed ones directly.

Checking that it started

register() returns a result. Use it to narrow things down when no telemetry arrives after a deploy.

instrumentation.ts
import { register as sophonz } from '@sophonz/nextjs/server';
 
export async function register() {
  const result = await sophonz({ appName: 'my-app' });
 
  if (!result.started) {
    // 'edge-runtime' is expected. The server SDK does not run on the Edge
    // runtime, and this branch is removed from that bundle.
    if (result.reason !== 'edge-runtime') {
      console.warn('[sophonz] did not start:', result.reason, result.missing);
    }
  }
}

reason is one of edge-runtime, already-started, or incomplete-config. In the last case missing names the fields that were absent.

Adding attributes in a Route Handler

Next.js has no middleware chain, so the Express, Koa, and Fastify helpers do not apply. Attach attributes inside the handler instead.

app/api/orders/[id]/route.ts
import { setTraceAttributes } from '@sophonz/node-sdk';
 
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
 
  // Attaches to this request's active span, which is what lets you filter the
  // trace list by order or by user.
  setTraceAttributes({
    'order.id': id,
    'user.id': request.headers.get('x-user-id') ?? 'anonymous',
  });
 
  const order = await loadOrder(id);
  return Response.json(order);
}

This only reaches the active span while server.betaMode is on. The package enables it by default, so no extra configuration is needed.

Server Actions

The same approach works in a Server Action. Wrapping the action in a span gives the form submission its own interval in the trace.

app/actions.ts
'use server';
 
import { trace, setTraceAttributes } from '@sophonz/node-sdk';
 
export async function submitOrder(formData: FormData) {
  setTraceAttributes({ 'action.name': 'submitOrder' });
 
  // The SDK re-exports the OpenTelemetry API as-is. Spans you create yourself
  // use the standard API; there is no wrapper of our own.
  return trace.getTracer('app').startActiveSpan('submitOrder', async (span) => {
    try {
      const order = await createOrder(formData);
      await sendConfirmation(order);
      return order.id;
    } finally {
      span.end();
    }
  });
}

Database query tracing

Extends a trace that started in the browser all the way into the database query plan. Apart from enabling SQLCommenter in instrumentation.ts, the application code is unchanged.

instrumentation.ts
import { register as sophonz } from '@sophonz/nextjs/server';
 
export const register = () =>
  sophonz({
    appName: 'my-app',
    server: {
      instrumentations: {
        // Append the W3C traceparent to every statement as a comment. Without
        // this the trace stops at the pg client.
        '@opentelemetry/instrumentation-pg': {
          addSqlCommenterCommentToQueries: true,
        },
      },
    },
  });

The trace a single request produces:

SpanDepthEmitted by
Route change1Browser SDK
GET /api/orders/1232Next.js server instrumentation
pg.query3pg instrumentation
Planner, ExecutorRun4pg_tracing

The last row appears only where the database has the pg_tracing extension. See Self-hosted PostgreSQL for installing it, or Cloud-managed PostgreSQL where it cannot be installed.

Turning individual instrumentations off

server and browser pass straight through to the underlying SDKs. Here a noisy instrumentation is disabled.

instrumentation.ts
import { register as sophonz } from '@sophonz/nextjs/server';
 
export const register = () =>
  sophonz({
    appName: 'my-app',
    server: {
      instrumentations: {
        '@opentelemetry/instrumentation-fs': { enabled: false },
      },
    },
  });

The full option lists are in Node.js SDK configuration and Browser SDK configuration.

Verifying

Start the dev server, move between a few routes, then find the trace in the dashboard. The browser and the server should appear in the same trace.

If only the server side is empty, check serverExternalPackages first. A module inlined into the bundle is never required at runtime, so the instrumentation hook misses it.