Generated banner for Error Tracking Nextjs
Generated logo for Error Tracking Nextjs

Error Tracking Nextjs

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • No issues found

From the author

PostHog error tracking for Next.js
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides guidance and best practices for implementing PostHog error tracking within Next.js projects. It covers initialization, source map configuration, and manual error boundary handling to ensure effective monitoring of application exceptions. The skill emphasizes maintaining existing error handling structures while leveraging PostHog's autocapture and alerting capabilities to streamline debugging and issue resolution.

What it does

  • Provides setup instructions for PostHog error tracking in Next.js applications.
  • Explains how to configure source maps for readable stack traces.
  • Outlines best practices for using manual capture at error boundaries.
  • Details how to configure automated alerts for new or spiking issues.
  • Describes methods for assigning issues to team members or roles.
  • Offers guidelines for environment variable management and SDK initialization.

When to use it

  • When you need to implement robust error monitoring in a Next.js application.
  • When you want to automate alerts for application exceptions via Slack, Discord, or webhooks.
  • When you need to assign specific error types to team members for triage.
  • When you are troubleshooting minified stack traces and need to upload source maps.

Advantages

  • Enables centralized monitoring of application exceptions.
  • Supports automated issue assignment based on custom rules.
  • Provides clear guidance on integrating with Next.js-specific patterns.
  • Helps reduce mean time to resolution through better visibility and alerting.

Usage examples

“How do I set up PostHog error tracking in a Next.js 15 project?”
The agent will guide you to initialize PostHog in instrumentation-client.ts and ensure environment variables are configured correctly.
“How can I get notified when a specific error spikes in my app?”
The agent will explain how to configure spike alerts in the PostHog error tracking settings to monitor error rate baselines.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/error-tracking-nextjs/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip error-tracking-nextjs.zip -d .agents/skills

Documentation by PostHog

PostHog error tracking for Next.js

This skill helps you add PostHog error tracking to Next.js applications.

Reference files

  • references/nextjs.md - Next.js error tracking installation - docs

  • references/fingerprints.md - Fingerprints - docs

  • references/alerts.md - Send error tracking alerts - docs

  • references/monitoring.md - Monitor and search issues - docs

  • references/assigning-issues.md - Assign issues to teammates - docs

  • references/upload-source-maps.md - Upload source maps - docs

Consult the documentation for API details and framework-specific patterns.

Key principles

  • Environment variables: Always use environment variables for PostHog keys and host URLs. Never hardcode them.

  • Minimal changes: Add error tracking alongside existing error handling. Don't replace or restructure existing error handling code.

  • Autocapture first: Enable exception autocapture in the SDK initialization before adding manual captures.

  • Source maps: Upload source maps so stack traces resolve to original source code, not minified bundles.

  • Manual capture for boundaries: Use captureException() at error boundaries and catch blocks for errors that don't propagate to the global handler.

Framework guidelines

  • For Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup

  • For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically

  • Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes

  • Do NOT use useEffect for data transformation - calculate derived values during render instead

  • Do NOT use useEffect to respond to user events - put that logic in the event handler itself

  • Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler

  • Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler

  • To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect

  • useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions)

Files

references/nextjs.md

Next.js error tracking installation - Docs

  1. 1

    Install the package

    Required

    Install the PostHog JavaScript library using your package manager:

    PostHog AI

    npm
    npm install posthog-js
    yarn
    yarn add posthog-js
    pnpm
    pnpm add posthog-js
  2. 2

    Add environment variables

    Required

    Add your PostHog project token and host to your .env.local file and to your hosting provider (e.g. Vercel, Netlify). These values need to start with NEXT_PUBLIC_ to be accessible on the client-side.

    .env.local

    PostHog AI

    NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=<ph_project_token>
    NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
  3. 3

    Initialize PostHog

    Required

    Choose the integration method based on your Next.js version and router type.

    Next.js 15.3+

    If you're using Next.js 15.3+, you can use instrumentation-client.ts for a lightweight, fast integration:

    instrumentation-client.ts

    PostHog AI

    import posthog from 'posthog-js'
    posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
        api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
        defaults: '2026-01-30'
    })

    App router

    For the App router, create a providers.tsx file in your app folder. The posthog-js library needs to be initialized on the client-side using the 'use client' directive:

    app/providers.tsx

    PostHog AI

    'use client'
    import { usePathname, useSearchParams } from "next/navigation"
    import { useEffect } from "react"
    import posthog from 'posthog-js'
    import { PostHogProvider as PHProvider } from 'posthog-js/react'
    export function PostHogProvider({ children }: { children: React.ReactNode }) {
      useEffect(() => {
        posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN as string, {
          api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
          defaults: '2026-01-30'
        })
      }, [])
      return (
        <PHProvider client={posthog}>
          {children}
        </PHProvider>
      )
    }

    Then import the PostHogProvider component in your app/layout.tsx and wrap your app with it:

    app/layout.tsx

    PostHog AI

    import './globals.css'
    import { PostHogProvider } from './providers'
    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>
            <PostHogProvider>
              {children}
            </PostHogProvider>
          </body>
        </html>
      )
    }

    Pages router

    For the Pages router, integrate PostHog at the root of your app in pages/_app.tsx:

    pages/_app.tsx

    PostHog AI

    import { useEffect } from 'react'
    import { Router } from 'next/router'
    import posthog from 'posthog-js'
    import { PostHogProvider } from 'posthog-js/react'
    import type { AppProps } from 'next/app'
    export default function App({ Component, pageProps }: AppProps) {
      useEffect(() => {
        posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN as string, {
          api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
          defaults: '2026-01-30',
          loaded: (posthog) => {
            if (process.env.NODE_ENV === 'development') posthog.debug()
          }
        })
      }, [])
      return (
        <PostHogProvider client={posthog}>
          <Component {...pageProps} />
        </PostHogProvider>
      )
    }

    Defaults option

    The defaults option automatically configures PostHog with recommended settings for new projects. See SDK defaults for details.

  4. 4

    Accessing PostHog on the client

    Recommended

    Next.js 15.3+

    Once initialized in instrumentation-client.ts, import posthog from posthog-js anywhere and call the methods you need:

    app/checkout/page.tsx

    PostHog AI

    'use client'
    import posthog from 'posthog-js'
    export default function CheckoutPage() {
        function handlePurchase() {
            posthog.capture('purchase_completed', { amount: 99 })
        }
        return <button onClick={handlePurchase}>Complete purchase</button>
    }

    App/Pages router

    Use the usePostHog hook to access PostHog in client components:

    app/checkout/page.tsx

    PostHog AI

    'use client'
    import { usePostHog } from 'posthog-js/react'
    export default function CheckoutPage() {
        const posthog = usePostHog()
        function handlePurchase() {
            posthog.capture('purchase_completed', { amount: 99 })
        }
        return <button onClick={handlePurchase}>Complete purchase</button>
    }
  5. 5

    Capture client-side exceptions

    Required

    PostHog can automatically capture unhandled exceptions in your Next.js app using the JavaScript Web SDK.

    You can enable exception autocapture for the JavaScript Web SDK in the Error tracking section of your project settings.

    It is also possible to manually capture exceptions using the captureException method:

    JavaScript

    PostHog AI

    posthog.captureException(error, additionalProperties)

    Manual capture is very useful if you already use error boundaries to handle errors in your app:

    App router

    Next.js uses error boundaries to handle uncaught exceptions by rendering a fallback UI instead of the crashing components. To set one up, create a error.tsx file in any of your route directories. This triggers when there is an error rendering your component and should look like this:

    error.tsx

    PostHog AI

    "use client"
    import posthog from "posthog-js"
    import { useEffect } from "react"
    export default function Error({
      error,
      reset,
    }: {
      error: Error & { digest?: string }
      reset: () => void
    }) {
      useEffect(() => {
        posthog.captureException(error)
      }, [error])
      return (
        ...
      )
    }

    You can also create a Global Error component in your root layout to capture unhandled exceptions in your root layout.

    app/global-error.tsx

    PostHog AI

    'use client'
    import posthog from "posthog-js"
    import NextError from "next/error"
    import { useEffect } from "react"
    export default function GlobalError({
      error,
      reset,
    }: {
      error: Error & { digest?: string }
      reset: () => void
    }) {
      useEffect(() => {
        posthog.captureException(error)
      }, [error])
      return (
        // global-error must include html and body tags
        <html>
          <body>
            {/* `NextError` is the default Next.js error page component */}
            <NextError statusCode={0} />
          </body>
        </html>
      )
    }

    Pages router

    For Pages Router, you can use React's Error Boundaries to catch JavaScript errors anywhere in the component tree. Create a custom error boundary component and report errors to PostHog in the componentDidCatch method:

    components/ErrorBoundary.tsx

    PostHog AI

    componentDidCatch(error, errorInfo) {
      posthog.captureException(error)
    }

    Then wrap your app or specific components with the error boundary:

    pages/_app.tsx

    PostHog AI

    import type { AppProps } from 'next/app'
    import ErrorBoundary from '../components/ErrorBoundary'
    export default function App({ Component, pageProps }: AppProps) {
      return (
        <ErrorBoundary>
          <Component {...pageProps} />
        </ErrorBoundary>
      )
    }
  6. 6

    Installing PostHog SDK for server-side

    Required

    Next.js enables you to both server-side render pages and add server-side functionality. To integrate PostHog into your Next.js app on the server-side, you can use the Node SDK.

    First, install the posthog-node library:

    PostHog AI

    npm
    npm install posthog-node --save
    yarn
    yarn add posthog-node
    pnpm
    pnpm add posthog-node
    bun
    bun add posthog-node

    For the backend, we can create a lib/posthog-server.js file. In it, initialize PostHog from posthog-node as a singleton with your project token and host from your project settings.

    This looks like this:

    lib/posthog-server.js

    PostHog AI

    import { PostHog } from 'posthog-node'
    let posthogInstance = null
    export function getPostHogServer() {
      if (!posthogInstance) {
        posthogInstance = new PostHog(
          process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN,
          {
            host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
            flushAt: 1,
            flushInterval: 0,
          }
        )
      }
      return posthogInstance
    }

    You can now use the getPostHogServer function to capture exceptions in server-side code.

    JavaScript

    PostHog AI

    const posthog = getPostHogServer()
    try {
        throw new Error("This is a test exception for error tracking")
    } catch (error) {
        posthog.captureException(error, {
            source: 'test',
            user_id: 'test-user-123',
        })
    }
  7. Verify server-side exceptions

    Recommended

    You should also see events and exceptions in PostHog coming from your server-side code in the activity feed.

    Check for server events in PostHog

  8. 7

    Capturing server-side exceptions

    Required

    To capture errors that occur in your server-side code, you can set up an instrumentation.ts file at the root of your project. This provides a onRequestError hook that you can use to capture errors.

    Importantly, you need to:

    1. Set up a posthog-node client in your server-side code. See our doc on setting up Next.js server-side analytics for more.

    2. Check the request is running in the nodejs runtime to ensure PostHog works. You can call posthog.debug() to get verbose logging.

    3. Get the distinct_id from the cookie to connect the error to a specific user.

    This looks like this:

    JavaScript

    PostHog AI

    // instrumentation.js
    export function register() {
      // No-op for initialization
    }
    export const onRequestError = async (err, request, context) => {
      if (process.env.NEXT_RUNTIME === 'nodejs') {
        const { getPostHogServer } = require('./lib/posthog-server')
        const posthog = getPostHogServer()
        let distinctId = null
        if (request.headers.cookie) {
          // Normalize multiple cookie arrays to string
          const cookieString = Array.isArray(request.headers.cookie)
            ? request.headers.cookie.join('; ')
            : request.headers.cookie
          const postHogCookieMatch = cookieString.match(/ph_phc_.*?_posthog=([^;]+)/)
          if (postHogCookieMatch && postHogCookieMatch[1]) {
            try {
              const decodedCookie = decodeURIComponent(postHogCookieMatch[1])
              const postHogData = JSON.parse(decodedCookie)
              distinctId = postHogData.distinct_id
            } catch (e) {
              console.error('Error parsing PostHog cookie:', e)
            }
          }
        }
        await posthog.captureException(err, distinctId || undefined)
      }
    }

    You can find a full example of both this and client-side error tracking in our Next.js error monitoring tutorial.

  9. Verify error tracking

    Recommended

    Confirm events are being sent to PostHog

    Before proceeding, let's make sure exception events are being captured and sent to PostHog. You should see events appear in the activity feed.

    Image: Activity feed with eventsImage: Activity feed with events

    Check for exceptions in PostHog

  10. 8

    Upload source maps

    Required

    Great, you're capturing exceptions! If you serve minified bundles, the next step is to upload source maps to generate accurate stack traces.

    Let's continue to the next section.

    Upload source maps

Community questions

Ask a question

Was this page useful?

HelpfulCould be better

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/posthog/error-tracking/skills/nextjs · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
PostHog/skills

AutoGineer is not affiliated with or endorsed by PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download error-tracking-nextjs.zip