@caravela-studio/glancy-next

中文文档
0.4.0发布于 2026/11/05MITTypeScriptES Module近 30 天下载 1797

Send product analytics from Next.js straight to Glancy

原始使用文档
文档目录7 节
  1. Install
  2. Browser
  3. Session replay and heatmaps
  4. Middleware
  5. Route handlers
  6. Server
  7. Example

@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 you track / identify / group / alias / reset. Messages are batched (20 messages or 2 s) and flushed with fetch(keepalive) when the tab is hidden or closed. Works with the App Router and the Pages Router.
  • Middleware: withGlancy() from @caravela-studio/glancy-next/middleware sends page views for page loads (shared with the browser, so each is stored once) and API Request events from the server — see below.
  • Server: glancy() from @caravela-studio/glancy-next/server for 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_id cookie, so server events can be tied to it with getAnonymousId(). identify merges 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-web for any web app, glancy.js for 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>;
}
MethodWhat 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 class glancy-mask) to mask an element's text, data-glancy-block (or glancy-block) to leave it out entirely.
sessionReplay optionDefault
sampleRate1Share of sessions recorded (decided once per session)
maskAllInputstrueMask what people type
maskAllTextfalseMask 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 fresh messageId that it hands to the browser in the short-lived glancy_pv cookie. 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 Request event (method, path) for paths matching api (default ["/api/"]), plus status when your middleware answered itself; middleware never sees the route's own response.
  • Sets glancy_anon_id on the first request (readable by the browser SDK), so both sides share the visitor.
  • Skips static files, prefetches, redirects and exclude; sends with event.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).

版本与发布记录

@caravela-studio/glancy-next 共发布 8 个版本,首次发布于 2026/10/23;过去 12 个月发布了 8 个版本。

版本发布日期距今
0.4.0latest2026/11/055 天前
0.3.12026/11/045 天前
0.2.02026/10/3011 天前
0.1.32026/10/2713 天前
0.1.22026/10/2713 天前
0.1.12026/10/2417 天前

关于 @caravela-studio/glancy-next 的常见问题

@caravela-studio/glancy-next 是什么?

Send product analytics from Next.js straight to Glancy

如何安装 @caravela-studio/glancy-next?

在项目目录运行 npm install @caravela-studio/glancy-next,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:next(>=13.4)、react(>=18)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@caravela-studio/glancy-next 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@caravela-studio/glancy-next 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@caravela-studio/glancy-next 可以商用吗?

@caravela-studio/glancy-next 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@caravela-studio/glancy-next 的下载量有多少?

根据 npm 官方下载统计,@caravela-studio/glancy-next 在 2026/10/09 – 2026/11/07 这 30 天内被下载 1,797 次,日均约 60 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@caravela-studio/glancy-next 还在维护吗?

最新版本 0.4.0 发布于 2026/11/05(5 天前);至今共发布 8 个版本,其中过去 12 个月发布了 8 个;首次发布于 2026/10/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。