Skip to content

add support for nextjs instrumentation #975

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

zshannon
Copy link

Add support for Next.js instrumentation.ts file

Summary

This PR adds support for Next.js
https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation file convention in
next-on-pages, enabling developers to use custom instrumentation and error monitoring in their
Cloudflare Pages applications.

Features

  • Automatic detection: Finds instrumentation.ts/js files in standard Next.js locations (/,
    /src/, /app/)
  • Edge runtime compilation: Compiles instrumentation files with esbuild for Cloudflare Workers
    compatibility
  • Full API support: Implements both register() and onRequestError() functions from the Next.js
    instrumentation API
  • Environment access: Provides access to environment variables through getRequestContext() for
    configuration
  • Error handling: Graceful fallbacks when instrumentation fails to load or execute

Implementation Details

Build Process

  • Detects instrumentation files during the build step
  • Compiles with esbuild using ESM format for edge runtime compatibility
  • Stubs out server-only imports to prevent client component errors
  • Stores compiled instrumentation in the next-on-pages-dist directory

Runtime Execution

  • Loads instrumentation module during worker initialization
  • Defers register() call until first request when environment context is available
  • Calls onRequestError() automatically when request errors occur
  • Provides full request and context information to error handlers

Example Usage

Basic Sentry Integration

// src/instrumentation.ts
import { type Instrumentation } from 'next'
import * as Sentry from '@sentry/browser'
import { getRequestContext } from '@cloudflare/next-on-pages'

export const register = async () => {
const { env } = getRequestContext()

Sentry.init({
    dsn: env.SENTRY_DSN,
    environment: env.NODE_ENV,
    tracesSampleRate: 1.0,
})

console.log('Sentry initialized')
}

export const onRequestError: Instrumentation.onRequestError = async (
error,
request,
context
) => {
Sentry.captureException(error, {
    tags: {
    path: request.path,
    method: request.method,
    },
    contexts: {
    request: {
        url: request.path,
        method: request.method,
        headers: request.headers,
    },
    nextjs: {
        routerKind: context.routerKind,
        routePath: context.routePath,
        routeType: context.routeType,
    },
    },
})

await Sentry.flush()
}

Custom Error Monitoring

// src/instrumentation.ts
import { type Instrumentation } from 'next'
import { getRequestContext } from '@cloudflare/next-on-pages'

export const register = async () => {
console.log('Custom instrumentation registered')
}

export const onRequestError: Instrumentation.onRequestError = async (
error,
request,
context
) => {
const { env } = getRequestContext()

// Send to custom error tracking service
await fetch(env.ERROR_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
    error: {
        message: error.message,
        stack: error.stack,
        digest: error.digest,
    },
    request: {
        url: request.path,
        method: request.method,
        headers: request.headers,
    },
    context,
    timestamp: new Date().toISOString(),
    }),
})
}

References

Test Plan

  • Detects instrumentation files in all standard locations
  • Compiles TypeScript and JavaScript instrumentation files
  • Handles compilation errors gracefully
  • Calls register() on first request with environment access
  • Calls onRequestError() when request errors occur
  • Works with edge-compatible packages like @sentry/browser
  • Provides full request context to error handlers

🤖 Generated with https://claude.ai/code

Co-Authored-By: Claude [email protected]

Copy link

changeset-bot bot commented Jul 24, 2025

⚠️ No Changeset found

Latest commit: 652258d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant