Skip to content

feat: support analytics().sendEvent() from Pages Router API routes#39

Merged
vklimontovich merged 1 commit into
mainfrom
feat/analytics-pages-router-api
Jun 5, 2026
Merged

feat: support analytics().sendEvent() from Pages Router API routes#39
vklimontovich merged 1 commit into
mainfrom
feat/analytics-pages-router-api

Conversation

@vklimontovich

Copy link
Copy Markdown
Collaborator

What

analytics() now accepts an optional request so analytics().sendEvent() works in both routers:

analytics(req?: NextRequest | NextApiRequest) => Promise<NextlyticsServerSide>
  • App Router (server components, server actions, route handlers): call analytics() with no args — unchanged, context comes from next/headers.
  • Pages Router API routes: call analytics(req). next/headers throws there, so context is built from req.headers / req.cookies / req.url.
  • A NextRequest (App Router route handler) is also accepted.

Why

The server API was App-Router-only because analytics() reads from next/headers, which throws in Pages Router API routes (req/res). There was no nextlytics-native way to emit a server event from those routes — e.g. email pixel / redirect endpoints that genuinely need to be Pages Router.

How

The three context sources are unified behind a NormalizedRequest shape, then buildServerContext() consumes it (replacing the App-Router-only createServerContextFromHeaders). Standalone routes with no preceding page render (email pixels, redirects) now send without a parent page-view — parentEventId is omitted rather than failing. The "middleware not configured" hard error is preserved only for the no-arg App Router path.

Server context method is now the real request method instead of a hardcoded "GET".

Notes

  • No change to anon-cookie behavior: like the existing App Router analytics(), no new anon cookie is written (existing cookies are read; GDPR-hash mode works).

typecheck, lint, build, tests, and format check all pass.

🤖 Generated with Claude Code

analytics() now accepts an optional request (NextRequest | NextApiRequest).
Pages Router API routes pass req, since next/headers throws there; App Router
keeps calling it with no args. Standalone routes with no page render (email
pixels, redirects) send without a parent page-view.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@vklimontovich vklimontovich merged commit b70ec61 into main Jun 5, 2026
3 checks passed
@vklimontovich vklimontovich deleted the feat/analytics-pages-router-api branch June 5, 2026 14:55
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