Next.js
@stancelens/next: App Router page views and hooks, a script-tag alternative, and server-side tracking.
Built on the JavaScript and React SDKs. Prefer no npm package at all? Load the script tag with `next/script`.
Install from source
The packages aren't on npm yet. Build tarballs of all three from the Stancelens repository, then install them in your app:
cd stancelens/packages
(cd js && bun install && bun run build && bun pm pack)
(cd react && bun install && bun run build && bun pm pack)
(cd next && bun install && bun run build && bun pm pack)
# in your app
npm install /path/to/stancelens/packages/js/stancelens-js-0.1.0.tgz \
/path/to/stancelens/packages/react/stancelens-react-0.1.0.tgz \
/path/to/stancelens/packages/next/stancelens-next-0.1.0.tgzQuick start
import { StancelensAnalytics } from "@stancelens/next";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<StancelensAnalytics site="SITE_ID">{children}</StancelensAnalytics>
</body>
</html>
);
}In client components, useStancelens() and useFlag(key) use that client, and so does track() imported from @stancelens/js.
Server: Route Handlers, Server Actions, middleware
import { after } from "next/server";
import { trackServer } from "@stancelens/next/server";
export async function POST(request: Request) {
const user = await createUser(request);
after(() =>
trackServer({ name: "signup", userId: user.id, props: { plan: user.plan } }, { request }),
);
return Response.json(user);
}after() needs Next 15.1 or later; on older versions, await trackServer(…). Set STANCELENS_API_KEY (owner or admin key from Account → API keys) and STANCELENS_SITE in the server environment. @stancelens/next/server is never imported by the client component, so the key stays on the server.
Middleware and Edge
trackServer uses only fetch, AbortController and crypto.randomUUID, so it runs in middleware and Edge Route Handlers. Don't await it on the request path; hand the promise to event.waitUntil():
import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
import { trackServer } from "@stancelens/next/server";
export function middleware(request: NextRequest, event: NextFetchEvent) {
if (request.nextUrl.pathname.startsWith("/api/")) {
event.waitUntil(trackServer({ name: "api_call", path: request.nextUrl.pathname }, { request }));
}
return NextResponse.next();
}API
@stancelens/next (client)
| Export | What it does |
|---|---|
<StancelensAnalytics site? host? pageviews? …options> | Initialises the shared client and provides it to the hooks. With pageviews (default true) it sends a page view on load and whenever usePathname() or useSearchParams() change, inside its own <Suspense> so static pages still prerender. site defaults to NEXT_PUBLIC_STANCELENS_SITE, host to NEXT_PUBLIC_STANCELENS_HOST. Takes every JavaScript SDK option except autoPageviews. |
<StancelensScript site? host? data?> | Loads the script-tag tracker (<host>/e.js) with next/script instead of bundling the SDK. Use window.stancelens for custom events. data adds data-* options, e.g. { replay: "0.25" }. |
useStancelens, useFlag, TrackPageviews | Re-exported from `@stancelens/react`. |
@stancelens/next/server
| Export | What it does |
|---|---|
trackServer(event | events, options?) | Sends 1 to 100 events to POST /api/v1/events and resolves to { ok, status, accepted, dropped, error? }. Never throws. |
clientIp(headers) | First X-Forwarded-For address, else X-Real-IP or CF-Connecting-IP. |
- Event fields:
name,props,userId,anonymousId,pathorurl,referrer,revenue(number or{ amount, currency }),timestamp(up to 30 days back),traits(withname: "$identify"). - Options:
apiKey(defaultSTANCELENS_API_KEY),site(defaultSTANCELENS_SITE, thenNEXT_PUBLIC_STANCELENS_SITE),host(defaultSTANCELENS_HOST, thenNEXT_PUBLIC_STANCELENS_HOST, thenhttps://stancelens.com),request(its User-Agent, client IP andAccept-Languageare sent so device and browser describe the end user; country is estimated from the language region, such asde-DE, since the IP isn't used for it),fetch,timeout(default 10000 ms). - Events are sent with
platform: "server". A page view that carries a browser's user agent is recorded asweb, so server-side page views count with browser traffic; everything else isserver. trackServermakes one request per call and doesn't batch or retry, since server code may stop right after it returns.- To link server events to a browser visitor, send the browser's anonymous ID (
useStancelens().getAnonymousId()) to your server and pass it asanonymousId.