Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

8.0 KB
Raw Blame

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 build
  • pnpm run lint – ESLint
  • pnpm run format – Prettier format
  • pnpm 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-key header if present β€” resolved via api/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 ID
  • time – selected time range (modes: day, range, week, month, year, past-minutes, all-time)
  • previousTime – comparison period
  • bucket – time bucketing (hour, day, week, month)
  • selectedStat – active metric (pageviews, sessions, users, bounce_rate, etc.)
  • filters – active analytics filters
  • timezone – IANA timezone (persisted to localStorage)
  • Helpers: resetStore(), goBack(), goForward(), addFilter(), removeFilter()

User store (lib/userStore.ts) via Zustand:

  • User session data and isPending flag

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, minimal useEffect
  • Naming: camelCase variables/functions, PascalCase components/types, UPPER_SNAKE_CASE constants
  • API hooks: prefix with use, e.g. useGetSites; endpoint functions prefix with fetch/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 in messages/
  • 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.