---
title: 'Meta CAPI in Next.js App Router: Route Handler & Dedup (2026)'
description: 'Complete Next.js App Router Meta Conversions API setup: TypeScript Route Handler, 4th-arg fbq() eventID deduplication, unhashed _fbp/_fbc, and SHA-256 hashing.'
canonical: 'https://plainrouter.com/library/meta-capi-nextjs-setup'
format: Guide
last_updated: '2026-12-04'
---

Setting up Meta Conversions API (CAPI) in Next.js App Router cleanly requires two coordinated paths: a browser event carrying [eventID](</library/meta-event-id-deduplication>) in the 4th fbq() argument (when consented) and a server-side Route Handler or webhook sending the exact same event\_id, integer Unix seconds event\_time, unhashed \_fbp/\_fbc cookies, and SHA-256 hashed customer keys.

## Why Next.js Meta CAPI setups break in production

Client-side React navigation, Edge middleware redirects, and server/client hydration boundaries create four recurring failure modes in Next.js apps:

- **Independent random UUIDs per path: **Generating crypto.randomUUID() inside a React component and a second UUID inside app/api/checkout/route.ts causes Meta to double-count every Purchase.
- **3rd-argument fbq() eventID bug: **Passing \{ value, currency, eventID \} as the 3rd fbq('track', ...) argument sends cd\[eventID\] instead of eid, silently breaking deduplication.
- **Millisecond event\_time on the server: **Sending Date.now() (13 digits) instead of Math.floor(Date.now() / 1000) (10 digits) causes Meta Graph API to reject the event with HTTP 400.
- **Hashing \_fbp or \_fbc cookies: **Meta requires em, ph, fn, ln, and external\_id to be normalized and SHA-256 hashed, while fbp, fbc, client\_ip\_address, and client\_user\_agent MUST stay raw and unhashed.

## Step 1: Generate one deterministic event\_id on your server or checkout session

Tie event\_id to a durable business key such as your order ID or Stripe Checkout Session ID (for example, purchase\_cs\_live\_12345) rather than an ephemeral client UUID. Pass that same event\_id to both your thank-you page client component and your Stripe webhook or server action so retries stay idempotent within Meta's 48-hour deduplication window.

## Step 2: Read \_fbp and \_fbc cookies cleanly in a Next.js Route Handler

In Next.js App Router (app/api/meta-capi/route.ts), read \_fbp and \_fbc directly from cookies() and forward the visitor's real IP and User-Agent from headers() without hashing any of those four fields:

`` import crypto from 'node:crypto';
import { cookies, headers } from 'next/headers';
import { NextResponse } from 'next/server';

const sha256 = (value: string) =>
  crypto.createHash('sha256').update(value.trim().toLowerCase()).digest('hex');

export async function POST(req: Request) {
  const body = await req.json();
  const cookieStore = await cookies();
  const headerStore = await headers();

  const payload = {
    data: [{
      event_name: 'Purchase',
      event_time: Math.floor(Date.now() / 1000),
      event_id: body.eventId,
      action_source: 'website',
      event_source_url: body.sourceUrl,
      user_data: {
        em: body.email ? [sha256(body.email)] : undefined,
        fbp: cookieStore.get('_fbp')?.value,
        fbc: cookieStore.get('_fbc')?.value,
        client_ip_address: headerStore.get('x-forwarded-for')?.split(',')[0]?.trim(),
        client_user_agent: headerStore.get('user-agent') ?? undefined,
      },
      custom_data: {
        value: Number(body.value),
        currency: String(body.currency || 'USD').toUpperCase(),
      },
    }],
  };

  const res = await fetch(
    `https://graph.facebook.com/v22.0/${process.env.META_DATASET_ID}/events?access_token=${process.env.META_CAPI_TOKEN}`,
    { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }
  );
  return NextResponse.json({ ok: res.ok }, { status: res.ok ? 200 : 502 });
} ``

## Step 3: Pair your Next.js client component with 4th-argument \{ eventID \}

On your client confirmation component (only after checking your visitor's consent state), fire Meta Pixel with eventID in the 4th argument so Meta receives eid=\<eventId\> matching your server event\_id:

` window.fbq?.(
  'track',
  'Purchase',
  { value: order.total, currency: order.currency },
  { eventID: order.eventId }
); `

Also verify that your Next.js middleware or [next.config.ts redirects do not strip ?fbclid=](</library/fbp-fbc>) on landing pages, and check your Content-Security-Policy header so script-src allows connect.facebook.net and connect-src/img-src allow www.facebook.com.

## Step 4: Validate before deploying to production

Run all four checks before shipping to production:

- [Meta Tracking Health Checker](</tools/meta-tracking-checker>): scan your staging or production Next.js URL to detect duplicate fbevents.js loads, CSP header conflicts, and inline eventID placement.
- [Meta CAPI Payload Validator & SHA-256 Tool](</tools/meta-capi-validator>): paste your Route Handler JSON payload locally to catch millisecond timestamps, unhashed em/ph fields, or wrongly hashed fbp/fbc values.
- [Meta Pixel & CAPI Dedup Checker](</tools/event-id-dedup-checker>): compare your browser fbq() call side by side with your Route Handler JSON to verify exact event\_id and event\_name deduplication.
- [fbp, fbc & fbclid Debugger](</tools/fbp-fbc-debugger>): verify your \_fbc construction from ?fbclid= preserves exact click ID casing and 13-digit millisecond creation timestamps.

## When to use Plainrouter Signals instead of hand-rolling CAPI retries

A raw Route Handler works for a quick prototype, but production stores quickly need retry queues for Meta 5xx timeouts, Stripe checkout settlement verification, consent-state agreement across browser and server, and per-event delivery logs. [Plainrouter for Next.js](</solutions/nextjs>) provides the @plainrouter/sdk TypeScript client and browser snippet so you keep business events in your Next.js codebase without building delivery evidence or retry infrastructure from scratch.

## Frequently asked questions

### Should I call Meta Conversions API from a Next.js Server Action, Route Handler, or Stripe webhook?

For Purchase events, send from a verified server webhook (such as Stripe checkout.session.completed) or right after database order confirmation in a Route Handler, reusing the same deterministic event\_id passed to your thank-you page. Never rely solely on an unverified client fetch to report paid revenue.

### Why is my Next.js Meta Event Match Quality stuck below 6.0?

The most common causes in Next.js apps are dropping \_fbp/\_fbc when calling from a webhook without persisting them on the checkout session, forgetting x-forwarded-for or user-agent headers, or accidentally SHA-256 hashing fbp/fbc. Store consented \_fbp and \_fbc in Stripe metadata during checkout creation so your webhook can forward them unhashed.

### How do I stop Next.js App Router client navigation from double-firing PageView?

Initialize fbq('init', PIXEL\_ID) exactly once in your root layout script and trigger subsequent PageView events from a single usePathname() effect guarded against React Strict Mode double-invocation in development.

### Can I test my Next.js CAPI payloads in CI before deploying?

Yes. You can validate payloads locally in your browser with our [Meta CAPI Payload Validator](</tools/meta-capi-validator>) or run our zero-dependency open-source CLI ([plainrouter/meta-capi-check](<https://github.com/plainrouter/meta-capi-check>)) directly in GitHub Actions to validate JSON payloads, \_fbp/\_fbc cookies, and Pixel/CAPI deduplication pairs automatically.

## Related guides and tools

- [Meta conversion tracking for Next.js](</solutions/nextjs>): Plainrouter's Next.js SDK and Signals architecture overview.
- [Meta Conversions API: how it works and how to set it up](</library/meta-conversions-api>): end-to-end architecture and Events Manager verification.
- [Meta CAPI HTTP 400 error codes](</library/meta-capi-http-400-error-codes>): exact fixes for subcodes 2804050, 2804019, 190/463, and 2635.
- [Meta Event Match Quality stuck below 6.0](</library/meta-capi-event-match-quality-low>): exact user\_data hashing and IP/User-Agent payload fixes.
- [plainrouter/meta-capi-nextjs-starter (GitHub)](<https://github.com/plainrouter/meta-capi-nextjs-starter>): working open-source Next.js App Router starter with 4th-argument fbq() eventID deduplication, \_fbp/\_fbc middleware, and unit tests.
- [Meta CAPI with Stripe webhooks](</library/meta-capi-stripe-webhooks>): pair your Next.js storefront with verified Stripe checkout and renewal webhooks.
