@caravela-studio/glancy-next
Send product analytics from a Next.js app straight to Glancy — no Segment in between.
- Browser:
<GlancyProvider>sends a page view on every route change,useGlancy()gives youtrack/identify/group/alias/reset. Messages are batched (20 messages or 2 s) and flushed withfetch(keepalive)when the tab is hidden or closed. Works with the App Router and the Pages Router. - Middleware:
withGlancy()from@caravela-studio/glancy-next/middlewaresends page views for page loads (shared with the browser, so each is stored once) andAPI Requestevents from the server — see below. - Server:
glancy()from@caravela-studio/glancy-next/serverfor route handlers, server actions and middleware. - Session replay & heatmaps (opt-in): record sessions to watch them back, and collect clicks and scroll depth per page — see below.
- One visitor across both: the browser's anonymous id lives in the
glancy_anon_idcookie, so server events can be tied to it withgetAnonymousId().identifymerges the anonymous history into the user.
Messages follow the Segment spec, so they look exactly like the events Glancy already receives from Segment.
Not on Next.js? See all the SDKs:
@caravela-studio/glancy-webfor any web app,glancy.jsfor any site, React Native, Swift and Kotlin. This package is built on@caravela-studio/glancy-web.
Install
Public on npm, no token needed:
npm install @caravela-studio/glancy-next # brings @caravela-studio/glancy-web with it
.env.local of your app (the write key is on the bucket's Setup page):
NEXT_PUBLIC_GLANCY_WRITE_KEY=glc_prod_…
# Only when self-hosting (default https://ingest.heyglancy.com):
# NEXT_PUBLIC_GLANCY_HOST=https://analytics.example.com
The write key can only add events to one bucket, never read them, so it's fine to ship it to the browser.
Browser
// app/layout.tsx
import { GlancyProvider } from "@caravela-studio/glancy-next";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<GlancyProvider>{children}</GlancyProvider>
</body>
</html>
);
}
"use client";
import { useGlancy } from "@caravela-studio/glancy-next";
export function BuyButton() {
const analytics = useGlancy();
return <button onClick={() => analytics.track("Order Completed", { revenue: 42, currency: "EUR" })}>Buy</button>;
}
| Method | What it sends |
|---|---|
track(event, properties?) | A named event |
page(name?, properties?) | Page Viewed with path, url, title, referrer, search (automatic with the provider) |
identify(userId, traits?) | Links this browser to a user and stores traits on the profile (call after sign in) |
group(groupId, traits?) | Associates the user with a company / team |
alias(userId, previousId?) | Merges a previous id into userId |
reset() | Forgets the user, starts a new anonymous id and a new session (call on sign out) |
flush() | Sends the queue now |
stopRecording() | Stops session replay and heatmaps (e.g. consent withdrawn); events keep working |
getSessionId() | The current session id (also sent as context.sessionId on every event) |
Provider props: writeKey, host (default to the env vars above), trackPageViews (default true),
flushAt (20), flushInterval (2000 ms), debug (logs every message), sessionReplay, heatmaps.
Every message carries context.page, userAgent, os.name, locale, timezone and screen, so breakdowns
like by OS work out of the box.
Session replay and heatmaps
Both are off by default and turned on with a prop:
<GlancyProvider sessionReplay heatmaps>{children}</GlancyProvider>
// or with options
<GlancyProvider sessionReplay={{ sampleRate: 0.25, maskAllText: false }} heatmaps>
Session replay records the DOM with rrweb and sends it in compressed chunks every few seconds. Watch sessions under Replays in Glancy (with the session's events on a timeline), or from a person's profile. The recorder is loaded on demand, so it isn't in your bundle when replay is off.
- A session is one browser tab; it ends after 30 minutes of inactivity or on
reset(). - Privacy defaults: everything typed in inputs is masked (passwords always are). Add
data-glancy-mask(or classglancy-mask) to mask an element's text,data-glancy-block(orglancy-block) to leave it out entirely.
sessionReplay option | Default | |
|---|---|---|
sampleRate | 1 | Share of sessions recorded (decided once per session) |
maskAllInputs | true | Mask what people type |
maskAllText | false | Mask every piece of text on the page |
maskTextSelector | — | More elements to mask |
blockSelector | — | More elements to leave out |
Heatmaps collect every click (where on the page, and which element) and the deepest scroll of each page view.
Glancy draws them over your live page in a frame, per page and device class (desktop / tablet / mobile), and
lists the most clicked elements. Give important elements a data-testid or data-glancy-name to get stable names.
For the page to show, your site must allow being framed by the dashboard's origin (no X-Frame-Options: DENY /
restrictive frame-ancestors); the SDK doesn't track inside that frame.
Middleware
On Next.js 16 and later the file is proxy.ts (Next.js renamed middleware to proxy); earlier, middleware.ts.
// proxy.ts (middleware.ts before Next.js 16)
import { withGlancy } from "@caravela-studio/glancy-next/middleware";
export default withGlancy({ exclude: ["/api/health"], userId: (req) => req.cookies.get("uid")?.value });
export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
- A page view for every page load (
Sec-Fetch-Dest: document), with a freshmessageIdthat it hands to the browser in the short-livedglancy_pvcookie. The browser SDK's first page view of that page reuses it, and ingestion stores one row, filling in what the server's copy lacked (title, screen, the browser session). Client-side navigations stay with<GlancyProvider>: Next.js strips the RSC / prefetch headers before middleware, so a navigation can't be told from a prefetch there. - An
API Requestevent (method, path) for paths matchingapi(default["/api/"]), plusstatuswhen your middleware answered itself; middleware never sees the route's own response. - Sets
glancy_anon_idon the first request (readable by the browser SDK), so both sides share the visitor. - Skips static files, prefetches, redirects and
exclude; sends withevent.waitUntil. withGlancy(options, yourMiddleware)runs yours first and keeps its response.
Route handlers
withGlancyRoute(handler, options?) from @caravela-studio/glancy-next/server sends an API Request with the
response's status and duration_ms (a throw counts as 500 and is rethrown). Options: event, userId(req),
writeKey, host, onError. It sends with after() when available. Use api: false in withGlancy() (or
exclude the routes) so requests aren't counted twice.
export const POST = withGlancyRoute(async (req) => Response.json(await createOrder(req), { status: 201 }));
Server
Set GLANCY_HOST and GLANCY_WRITE_KEY (the NEXT_PUBLIC_ ones are used as a fallback).
// app/api/checkout/route.ts
import { glancy, getAnonymousId } from "@caravela-studio/glancy-next/server";
import { cookies } from "next/headers";
import { after } from "next/server";
export async function POST() {
const anonymousId = getAnonymousId(await cookies());
after(() => glancy().track({ userId: user.id, anonymousId, event: "Order Completed", properties: { revenue: 42 } }));
return Response.json({ ok: true });
}
Server calls (track, identify, page, group, alias, batch) need a userId or an anonymousId. Each
one is sent right away and resolves once it's stored, so serverless functions don't drop events; after() keeps
it off the response time. Sending never throws — failures go to onError (default console.error, at most once a minute).
new ServerClient({ writeKey, host }) creates a client with explicit config.
Example
examples/nextjs is a small app using both sides: npm install && npm run dev (port 3048).