@vacer/analytics
v1.1.0
Published
First-party, privacy-preserving analytics SDK for Next.js applications.
Maintainers
Readme
@vacer/analytics
A drop-in, first-party analytics SDK for Next.js applications. It mirrors the frontend ergonomics of Vercel Analytics while remaining self-hostable and backend-agnostic.
import { Analytics } from '@vacer/analytics';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<Analytics />
</>
);
}import { track } from '@vacer/analytics';
track('signup');
track('purchase', { plan: 'pro', value: 49 });Installation
npm install @vacer/analyticsThe package has a single peer dependency on React and ships as an ESM package with TypeScript declarations.
Setup
The easiest way to set up @vacer/analytics in your Next.js project is by using our automated initialization command:
npx @vacer/analytics initThis will automatically create the required route handler at app/api/vacer/analytics/route.ts and guide you through updating your next.config.mjs for the necessary rewrites.
Manual Setup (Alternative)
If you prefer to set it up manually:
- Add a route handler in
app/api/vacer/analytics/route.ts:
import { createAnalyticsRouteHandler } from '@vacer/analytics/server';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export const POST = createAnalyticsRouteHandler();- Expose the public SDK path by adding
analyticsRewritesto yournext.config.mjs:
import { analyticsRewrites } from '@vacer/analytics/server';
export default {
async rewrites() {
return analyticsRewrites();
},
};Next.js treats folders prefixed with _ as private, so the public SDK path /_vacer/analytics must be rewritten to /api/vacer/analytics.
Configure the intake destination with VACER_ANALYTICS_INTAKE_URL. Runway injects this automatically for deployed projects. For local development against a deployed project, also set VACER_ANALYTICS_PROJECT_ID and optionally VACER_ANALYTICS_FORWARD_HOST.
Configure a different same-origin endpoint when your deployment vacer exposes one:
<Analytics endpoint="/_analytics/intake" projectId="project_123" />Analytics is disabled automatically when NODE_ENV=development. To force behavior in tests or previews, pass enabled or mode:
<Analytics enabled mode="production" />Next.js App Router
Place the component in app/layout.tsx or a shared provider that renders once per page tree:
import { Analytics } from '@vacer/analytics';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Analytics webVitals />
</body>
</html>
);
}The component is a client component and automatically records the initial page load and client-side route transitions.
Next.js Pages Router
Add the component to pages/_app.tsx:
import type { AppProps } from 'next/app';
import { Analytics } from '@vacer/analytics';
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
<Analytics />
</>
);
}Custom Events
import { track } from '@vacer/analytics';
track('upgrade_clicked');
track('purchase', { sku: 'pro_monthly', value: 49 });Metadata must be JSON serializable. The SDK sanitizes unsupported values, redacts sensitive key names by default, and enforces configurable payload limits.
URL and Event Redaction
Use beforeSend to modify or drop any event before it is queued:
import { Analytics, redactUrl } from '@vacer/analytics';
<Analytics
beforeSend={(event) => ({
...event,
url: redactUrl(event.url),
path: redactUrl(event.path),
})}
/>Custom events can also provide per-call redaction:
track('purchase', payload, {
beforeSend(event) {
return { ...event, metadata: { plan: event.metadata?.plan ?? 'unknown' } };
},
});Web Vitals
Enable optional browser-only Core Web Vitals collection:
<Analytics webVitals />The SDK collects LCP, CLS, INP, FCP, and TTFB via PerformanceObserver where supported.
Privacy
The frontend never creates third-party cookies, fingerprints visitors, or stores persistent user identifiers. identifyAnonymousVisitor() exposes only the in-memory SDK session ID. The backend contract specifies a daily rotating anonymous visitor hash that must be generated server-side from request context and a daily secret.
Performance
The SDK avoids React state, lazily starts in the browser, batches events, debounces flushes, uses sendBeacon during unload when possible, and falls back to a bounded memory/localStorage retry queue when the network is unavailable.
Backend
This repository intentionally does not implement backend services. See BACKEND_CONTRACT.md for the required Redis ingestion, worker, PostgreSQL, MinIO, bot filtering, and anonymous visitor contracts.
Public API
<Analytics />
Configures automatic page tracking, batching, retry behavior, redaction hooks, endpoint resolution, and optional web vitals.
track(name, metadata?, options?)
Queues a custom analytics event. options.beforeSend can modify or cancel that event before transmission.
identifyAnonymousVisitor()
Returns the current in-memory SDK context. The durable anonymous visitor hash is intentionally backend-generated only.
flush()
Immediately attempts to send queued events. This is useful in tests or before known hard navigations.
Redaction helpers
stripQuery(url)removes query strings and hashes.maskDynamicSegments(path)replaces numeric, UUID, and long hex path segments with[id].redactUrl(url)combines both helpers.sanitizeMetadata(metadata)returns a JSON-safe metadata object.
