Skip to main content
All Integrations/Stack Guide · Next.js 14 / 15 App Router·Setup time: 3 minutes

Next.js App Router Analytics, AI Crawler Middleware & CSP Integration Guide

Architecture Summary

Add PrismUV to any Next.js 14 or 15 App Router project using one deferred `<script>` tag inside `app/layout.tsx`, then attach a lightweight `middleware.ts` beacon (`event.waitUntil`) so `OAI-SearchBot`, `Claude-SearchBot`, `PerplexityBot`, and `Googlebot` crawls log cleanly across every SSR/SSG route.

Auto-tracks App Router soft navigations (`history.pushState`) cleanly without custom hooks
Measures real visitor P75 LCP, INP & CLS plus `data-release` frontend crashes
Captures non-JS AI crawlers (`OAI-SearchBot`, `ClaudeBot`, `PerplexityBot`) via `middleware.ts`
Zero cookie banners — cookieless SHA-256 daily IP hashing

1. Drop the 3.9 KB single-line SDK into app/layout.tsx

Add the site-scoped bundle inside your root `<head>` (or via `next/script` with `strategy="afterInteractive"`). Using `data-release` tags frontend JS exceptions by commit or semver version.

src/app/layout.tsx
import Script from 'next/script';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src="https://prismuv.com/s/YOUR_SITE_ID/prismuv.js"
          strategy="afterInteractive"
          data-release={process.env.NEXT_PUBLIC_RELEASE || 'v1.0.0'}
        />
      </body>
    </html>
  );
}

2. Track AI & Search crawlers with non-blocking middleware.ts

Because OAI-SearchBot and Claude-SearchBot often parse raw SSR HTML without firing analytics JS, detect their User-Agent in Edge/Node middleware and dispatch `event.waitUntil()` to `/t/edge` with zero added TTFB latency.

src/middleware.ts
import { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';

const AI_CRAWLERS = [
  'oai-searchbot', 'chatgpt-user', 'gptbot',
  'claudebot', 'claude-searchbot', 'claude-user',
  'perplexitybot', 'googlebot', 'bingbot',
];

export function middleware(request: NextRequest, event: NextFetchEvent) {
  const ua = request.headers.get('user-agent') || '';
  if (ua && AI_CRAWLERS.some((t) => ua.toLowerCase().includes(t))) {
    event.waitUntil(
      fetch('https://prismuv.com/t/edge', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Prism-Edge-Secret': process.env.PRISMUV_EDGE_SECRET || '',
        },
        body: JSON.stringify({
          site_id: 'YOUR_SITE_ID',
          path: request.nextUrl.pathname || '/',
          status_code: 200,
          ua: ua.slice(0, 300),
        }),
      }).catch(() => {})
    );
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon\.).*)'],
};

3. Allow PrismUV in Content-Security-Policy (if strict CSP is enabled)

If your Next.js headers or Nginx gateway enforce Content-Security-Policy directives, permit `https://prismuv.com` inside `script-src` and `connect-src` (or skip third-party CSP entirely by using our `/_t/*` first-party proxy pattern).

next.config.ts CSP Snippet
// CSP directives when loading directly from prismuv.com:
script-src 'self' https://prismuv.com;
connect-src 'self' https://prismuv.com;

Common Production Pitfalls to Avoid

  • Never wrap `middleware.ts` `matcher` to skip inner tool or blog routes—use negative lookaheads excluding `_next/static` and `_next/image` so new pages automatically emit AI crawler logs.
  • Do not commit `PRISMUV_EDGE_SECRET` into `NEXT_PUBLIC_*` variables; keep `PRISMUV_EDGE_SECRET` strictly server-side inside middleware/Worker env vars.
  • Remember to pair `layout.tsx` metadata `title.template` length limits (`<= 55` raw title chars) so `<title>` stays cleanly inside 70 chars for Google & GEO checks.

Instant Verification Check

Verify live header delivery and crawler visibility right after deploying:

curl -A "Claude-SearchBot/1.0" -sI https://yourdomain.com/docs

Next.js (App Router) Integration FAQ

Does PrismUV automatically count Next.js Link client-side transitions?

Yes. The 3.9 KB script intercepts `history.pushState` and `popstate` automatically so App Router navigations count accurately without React context wrappers.

Does middleware.ts tracking slow down SSR page TTFB for human users?

No. Non-crawler user requests skip telemetry completely in microseconds, and crawler beacons execute asynchronously inside `event.waitUntil()`.

Can I configure PrismUV completely via first-party /_t proxy on Next.js?

Yes. Either use Next.js rewrites or place a Cloudflare Worker on `/_t/*` forwarding to PrismUV upstream so zero third-party requests leave your domain.

How do I trigger custom Next.js conversion events from client buttons?

Call `(window as { pvuv?: (...a: unknown[]) => void }).pvuv?.("event", "signup_clicked", { plan: "pro" })` cleanly with zero blocking overhead.

Does Next.js static export (`output: "export"`) work with PrismUV?

Yes. Static Next.js sites load `prismuv.js` normally, and when deployed on Cloudflare Workers / Pages you can pair our `/integrations/cloudflare-workers` `/t/edge` beacon.

How quickly can I verify Next.js setup inside PrismUV?

Run `Verify Install` in your PrismUV site settings to test live HTML script resolution and non-stub ingestion inside seconds.