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
pnpm add @cohorly/nextjs
# or: npm install @cohorly/nextjsRequires 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.
// app/layout.tsx
import { CohorlyProvider } from "@cohorly/nextjs";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<body>
<CohorlyProvider
apiHost="https://api.cohorly.com"
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():
// app/api/cohorly/[...path]/route.ts
import { createCohorlyProxy } from "@cohorly/nextjs/server";
export const { POST } = createCohorlyProxy({
apiHost: "https://api.cohorly.com",
token: "YOUR_PROJECT_TOKEN", // injected server-side into every forwarded body
});Then point apiHost at your own route and omit token on the client:
// 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.