Next.js SDK
@cohorly/nextjs re-exports <CohorlyProvider> / useCohorly() from the React SDK and adds createCohorlyProxy(), a first-party ingestion route handler so your project token never has to leave the server.
Install
bashpnpm add @cohorly/nextjs# or: npm install @cohorly/nextjs
Requires Next.js 13+ and React 18+ (peer dependencies).
Two token modes
There are two ways to attach your project token to ingested data. Pick one.
1. Client-side (token in the browser bundle)
Pass token directly to <CohorlyProvider>. Simplest, but the token is
visible in your client JS.
tsx// app/layout.tsximport { CohorlyProvider } from "@cohorly/nextjs";export default function RootLayout({children,}: {children: React.ReactNode;}) {return (<html><body><CohorlyProvider token="YOUR_PROJECT_TOKEN" trackPageviews>{children}</CohorlyProvider></body></html>);}
2. Server-side proxy (token never leaves your server)
Point the client SDK at a first-party API route and let the route handler
inject the token server-side. Create the route with createCohorlyProxy():
ts// app/api/cohorly/[...path]/route.tsimport { createCohorlyProxy } from "@cohorly/nextjs/server";export const { POST } = createCohorlyProxy({token: "YOUR_PROJECT_TOKEN", // injected server-side into every forwarded body// apiHost defaults to the hosted Cohorly API; set it to target a different deployment.});
Then point apiHost at your own route and omit token on the client:
tsx// app/layout.tsx<CohorlyProvider apiHost="/api/cohorly" trackPageviews>{children}</CohorlyProvider>
The proxy forwards POST /api/cohorly/track, /engage, and /alias
upstream, stamping token into each forwarded body server-side. This keeps
the token out of the browser bundle, hides apiHost, and dodges
ad-blockers that block direct requests to third-party analytics hosts.
createCohorlyProxy(options)
| Option | Type | Notes |
|---|---|---|
apiHost | string | Required. Upstream Cohorly server URL. |
token | string | Injected into every forwarded body. |
allowedPaths | string[] | Defaults to ["track", "engage", "alias"]. |
Returns a { POST } route handler. Use the client provider and
useCohorly() exactly as in the React SDK.