πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
CLAUDE.md β Rybbit Client
This file provides guidance to Claude Code when working in the /client directory.
Commands
Install with pnpm install at the repository root. Root pnpm dev:client and
pnpm build:client build shared first. Commands below run from client/.
pnpm run devβ Start dev server (Next.js + Turbopack, port 3002)pnpm run buildβ Production buildpnpm run lintβ ESLintpnpm run formatβ Prettier formatpnpm exec tsc --noEmitβ Type-check without emitting
Stack
- Framework: Next.js 16 (App Router), React 19
- Styling: Tailwind CSS v4, Shadcn UI (New York style), Lucide icons
- State: Zustand 5 (app/user stores), Jotai (atomic state)
- Server state: TanStack React Query 5
- Auth: Better-auth (admin, organization, emailOTP, apiKey plugins)
- Forms: React Hook Form + Zod
- i18n: next-intl (10 locales: en, de, fr, zh, es, pl, it, ko, pt, ja)
- Charts: Nivo (bar, calendar, line), D3, Mapbox GL
- Date/time: Luxon, date-fns
- URL state: nuqs (query string), vaul (drawer)
- HTTP: Axios via
authedFetch<T>()wrapper
Project Structure
src/
βββ api/ # API layer
β βββ analytics/ # Analytics endpoints + React Query hooks
β βββ admin/ # Admin endpoints + hooks
β βββ gsc/ # Google Search Console
β βββ types.ts # Shared types (CommonApiParams, Filter, etc.)
β βββ utils.ts # authedFetch, buildApiParams
βββ app/ # Next.js App Router pages
β βββ [site]/ # Per-site analytics dashboard
β βββ admin/ # Admin panel
β βββ auth/ # Auth flows
β βββ settings/ # User settings
β βββ layout.tsx # Root layout
β βββ Providers.tsx # Provider stack
βββ components/
β βββ ui/ # Shadcn UI primitives (41 files)
β βββ charts/ # Chart components
β βββ DateSelector/ # Date/time picker
β βββ Sessions/ # Session replay
β βββ sidebar/ # Navigation sidebar
β βββ [feature components]
βββ hooks/ # Custom hooks
βββ lib/
β βββ store.ts # Main Zustand store
β βββ userStore.ts # User/auth Zustand store
β βββ auth.ts # Better-auth client
β βββ utils.ts # cn(), formatters, helpers
β βββ dateTimeUtils.ts # Luxon-based date helpers
β βββ urlParams.ts # URL param management
βββ types/ # TypeScript definitions
βββ i18n/request.ts # next-intl config
βββ proxy.ts # Next.js middleware (routing)
messages/ # Translation files (en.json, de.json, etc.)
API Layer Pattern
Analytics reads go through one query module. A hook declares a descriptor β what differs between endpoints β and nothing else:
export function useGetEventNames() {
return useAnalyticsQuery<EventName[]>({ key: "event-names", path: "events/names" });
}
useAnalyticsQuery / useAnalyticsInfiniteQuery (api/analytics/useAnalyticsQuery.ts) resolve the store context through selectors, serialise the time window, build the queryKey from the same request object they send (so key and request cannot drift), unwrap the { data } envelope, and own the same-site placeholder policy, staleTime, and enabled: !!site. Non-React callers (CSV export, useQueries fan-outs) use buildAnalyticsRequest / fetchAnalytics from api/analytics/analyticsRequest.ts directly. Never hand-assemble a queryKey listing store inputs, and never call authedFetch for an analytics read.
Everything else (admin, gsc, stripe β and analytics writes) keeps two layers:
1. Endpoints (api/[domain]/endpoints/*.ts) β pure async functions, no React:
export async function fetchSomething(siteId: string): Promise<SomeType> {
return authedFetch<SomeType>(`/api/something?siteId=${siteId}`);
}
2. Hooks (api/[domain]/hooks/*.ts) β React Query wrappers:
export function useGetSomething(siteId?: string) {
return useQuery({
queryKey: ["get-something", siteId],
queryFn: () => fetchSomething(siteId!),
enabled: !!siteId,
});
}
authedFetch<T>(url, params?, config?) (api/utils.ts):
- Prepends
BACKEND_URL - Sends
credentials: "include" - Adds
x-private-keyheader if present β resolved viaapi/requestContext.ts, so the HTTP layer imports neither the store nor routing - Converts array params to JSON strings
- Extracts and throws backend errors from
response.data.error
buildApiParams(time, { timeZone, filters? }) (api/utils.ts) is a pure function returning a CommonApiParams object; toQueryParams (api/analytics/endpoints/types.ts) converts it to snake_case wire params. The timezone is injected, never read from the store β use useTimezone() in components, getTimezone() outside React.
State Management
Main store (lib/store.ts) via Zustand:
siteβ current site IDtimeβ selected time range (modes:day,range,week,month,year,past-minutes,all-time)previousTimeβ comparison periodbucketβ time bucketing (hour,day,week,month)selectedStatβ active metric (pageviews,sessions,users,bounce_rate, etc.)filtersβ active analytics filterstimezoneβ IANA timezone (persisted to localStorage)- Helpers:
resetStore(),goBack(),goForward(),addFilter(),removeFilter()
User store (lib/userStore.ts) via Zustand:
- User session data and
isPendingflag
Only timezone is persisted; everything else is session-only.
Routing
/[site]/mainβ analytics dashboard (middleware redirects/{siteId}β/{siteId}/main)/[site]/[privateKey]/mainβ public/shared analytics/adminβ admin panel/login,/signupβ auth pages/settingsβ user settings
Middleware in proxy.ts handles redirects and OAuth callbacks (/auth/callback/github, /auth/callback/google).
Code Conventions
- TypeScript strict mode throughout; use Zod for runtime validation
- Components: functional,
"use client"where needed, minimaluseEffect - Naming:
camelCasevariables/functions,PascalCasecomponents/types,UPPER_SNAKE_CASEconstants - API hooks: prefix with
use, e.g.useGetSites; endpoint functions prefix withfetch/create/update/delete - Query keys: descriptive arrays, e.g.
["get-site", siteId] - Imports: external first, then internal; alphabetical within groups
- Dark mode: default theme; class-based, CSS HSL variables
- i18n: use
useTranslations()from next-intl; translation files inmessages/ - Error handling: try/catch with specific error types; let React Query surface API errors
- Do not add unnecessary abstractions, extra error handling for impossible cases, or docstrings to unchanged code
i18n: the t translation function
t is the value returned by next-intl's useTranslations(). useTranslations() is a React hook, so it can only be called inside a React component or a custom hook β never at module scope, in a plain utility function, or in a regular (non-hook) callback. Calling it elsewhere violates the Rules of Hooks.
To translate inside a non-component/non-hook helper, call useTranslations() in the component/hook and pass t down as a parameter (typically as an optional t?: TranslationFunction, the shared type in lib/events.ts). Example: getEventTypeLabel(type, t) in app/[site]/events/components/EventLog/eventLogUtils.tsx.
Also: only pass real message keys to t(...). Passing an arbitrary string (e.g. a display label like "Input Change") throws MISSING_MESSAGE: Could not resolve β¦. If a value isn't a key in messages/, return it as-is instead of running it through t.