Project Architecture

DataHub.io is a multitenant Next.js app for publishing data and data-driven content. Users create publications (like a Substack newsletter but for data), add posts (datasets, Observable notebooks) synced from GitHub, and readers can subscribe, like, and browse.

Tech stack

  • Framework: Next.js 14 (App Router) with TypeScript
  • Database: PostgreSQL (Neon on Vercel in prod, Docker locally) with Prisma ORM
  • Storage: Cloudflare R2 (prod/staging), MinIO (local) for raw content files and trees
  • Authentication: NextAuth v4 with GitHub OAuth
  • Background Jobs: Inngest for sync/delete workflows
  • Search: Typesense for content indexing
  • API Layer: tRPC v10 with React Query
  • Styling: Tailwind CSS with Headless UI components
  • Deployment: Vercel
  • Content Processing: Cloudflare Worker (external repo) for markdown parsing and metadata extraction
image

High-level data flow

  1. User authenticates via GitHub OAuth and creates a publication.
  2. User adds posts to the publication, each linked to a GitHub repository/branch.
  3. A sync is triggered (manual or GitHub webhook) via app/api/webhook/route.ts.
  4. Inngest sync function pulls files from GitHub, writes raw files to R2/MinIO, and creates/updates Blob rows in Postgres.
  5. Each markdown upload to storage triggers the Cloudflare Worker via queue.
  6. The worker parses markdown, updates Blob metadata, and indexes in Typesense.
  7. Next.js serves pages at /<publication-slug>/<post-name> using metadata from Postgres and raw content from storage.

Directory structure

app/                        # Next.js App Router pages
  [publication]/             # Public publication pages
    [post]/[[...slug]]/      # Post content renderer (dataset/notebook pages)
    subscribe/               # Publication subscription page
  api/                       # API route handlers
    auth/[...nextauth]/      # NextAuth endpoints
    inngest/                 # Inngest webhook handler
    trpc/[trpc]/             # tRPC endpoint
    webhook/                 # GitHub webhook intake
    generate/                # AI content generation
  dashboard/                 # Authenticated dashboard (sidebar shell)
    api-keys/                # API keys
    posts/                   # Your posts across publications, post overview, settings, new
    publications/            # Publications list, posts table, settings, new
    settings/                # Account settings (profile)
    subscriptions/           # User subscription management
  home/                      # Marketing/landing pages
    collections/             # Data collections browser
    commons/                 # Commons index (the `commons` publication)
    publications/            # Featured publications
    solutions/               # Solution pages
  login/                     # Authentication page
    email/                   # Magic-link confirmation page
  user/[username]/           # Public user profile page
components/                  # React components
  auth/                      # Authentication components
  dashboard/                 # Dashboard: shell/ (sidebar, breadcrumbs), ui/ (shadcn, Tailwind v3), page-kit.tsx
  form/                      # Form components
  front/                     # Public-facing site components
  icons/                     # Icon components
  layouts/                   # Layout components
  preview/                   # Content preview components
  MDX.tsx                    # MDX compilation component
  mdx/                       # Components exposed to MDX content (e.g. request-data-cta.tsx)
  mdx-components-factory.tsx # MDX component mappings
middleware.ts                    # URL routing for multitenant app (rewrites, auth guards)
lib/                         # Shared utilities
  __tests__/                 # Unit tests for lib functions
  front/                     # Frontend-specific utilities
  hooks/                     # React hooks
  markdown.ts                # Markdown processing pipeline
  content-store.ts           # S3/MinIO storage abstraction
  github.ts                  # GitHub API client helpers
  actions.ts                 # Server actions
  app-config.ts              # Application configuration loader
server/                      # Server-side code
  api/
    routers/                 # tRPC router definitions
      __tests__/             # Router unit tests
      post.ts                # Post CRUD, sync, settings
      publication.ts         # Publication CRUD
      like.ts                # Like/unlike posts
      subscription.ts        # Publication subscriptions
      user.ts                # User profile management
      api-key.ts             # The Account's API keys (list, create, revoke)
      home.ts                # Homepage data (featured posts, collections)
    root.ts                  # tRPC router composition
    trpc.ts                  # tRPC context and middleware
  auth.ts                    # NextAuth configuration
  db.ts                      # Prisma client singleton
inngest/                     # Background job definitions
  client.ts                  # Inngest client and event types
  functions.ts               # Sync and delete function implementations
prisma/
  schema.prisma              # Database schema
  migrations/                # Prisma migrations
e2e/                         # End-to-end tests (Playwright)
  renderer/                  # Public page rendering tests
  fixtures/                  # Test fixtures and helpers
  global-setup.ts            # Test seeding and setup

Domain model

Entities defined in prisma/schema.prisma:

ModelPurpose
UserAuthenticated user (GitHub, Google or magic-link sign-in)
PublicationA named publication owned by a user (like a Substack)
PostA content item (dataset or Observable notebook) linked to a GitHub repo, belongs to a Publication
BlobA file record (metadata + sync status) belonging to a Post
LikeUser-to-Post like relationship
PostStatDaily views/downloads stats per Post
PostAuthorMany-to-many Post-to-User author relationship
PublicationSubscriptionUser subscription to a Publication
Account, Session, VerificationTokenNextAuth authentication models
ApiKeyAn Account's API key: sha256 hash, display prefix, label, last used, revoked (lib/api-key.ts)
UserCliToken, CliDeviceCodeCLI tokens and the dh login handshake (team only)

Key relationships:

  • User 1->N Publication (owner)
  • Publication 1->N Post
  • Post 1->N Blob
  • Post N<->N User (via PostAuthor)
  • Post 1->N Like
  • Post 1->N PostStat
  • Publication 1->N PublicationSubscription
  • User 1->N ApiKey

Post types (enum PostType):

  • DATAPACKAGE - standard markdown/data dataset
  • OBSERVABLE - Observable Framework notebook

Major components

Authentication

  • NextAuth config: server/auth.ts
  • Email linking rules: server/auth-identity.ts. User.email is citext, so the unique index and every lookup ignore case: one address belongs to at most one user.
  • OAuth and magic-link endpoints: app/api/auth/[...nextauth]/route.ts
  • Login page: app/login/page.tsx (sign-in options in components/auth/sign-in-options.tsx). When API_KEYS_ENABLED, /login?ref=<source> is the target of "get a free API key" links: it says "Sign up free to get an API key." (and that the API is coming) and returns to the API keys page; middleware keeps ref in the datahub-sign-up-ref cookie for a day (lib/sign-up-ref.ts), and account_created and api_key_created carry it. A signed-in visitor goes straight to the keys. With the flag off, ?ref= is ignored.
  • Magic-link handoff: app/login/email/link/route.ts (cookie helpers in lib/sign-in-link.ts), confirmation page app/login/email/page.tsx

Sign-in methods: GitHub, Google (only where NEXT_PUBLIC_AUTH_GOOGLE_ID and AUTH_GOOGLE_SECRET are set; env validation fails if only one is) and an emailed one-time link (Resend, 1 hour, at most one per address per minute, and at most 5 per IP per hour where Vercel KV is configured: server/sign-in-link-limit.ts, ?error=EmailIpRateLimited). Sign-ups are open: an identity or address no user has creates a new user, who can't publish (only the team can). Its username comes from generateUsername in lib/username.ts (the GitHub login, the Google name or the email's local part, made a valid slug, with -2, -3… if taken; a clash between simultaneous sign-ups retries), and its name defaults to the username; both can be changed in Settings. account_created records the method (github, google, email). A new account gets the welcome email; it is not added to the Brevo list (only the newsletter form does that). Transactional email (the sign-in link, the welcome email, the premium download link) goes out over Resend from lib/email.ts; its words and design, which follow the public site, are in lib/email-templates.ts. The welcome email offers an API key only when API_KEYS_ENABLED is set.

  • A new Google or GitHub identity is linked to the user who already has the same email, if the provider verified it: Google's email_verified, or GitHub's primary address when GitHub has verified it. Emails match ignoring case. A new Google identity whose email Google hasn't verified is refused (?error=EmailNotVerified), since NextAuth would otherwise link or claim the address; a GitHub one without a verified primary address signs up without an email.
  • A user has at most one GitHub account. A new GitHub identity whose email matches a user who already has a GitHub account is refused (?error=GitHubAccountMismatch). Every GitHub sign-in updates User.ghUsername.
  • A magic link is sent to any address (using it signs up an address no user has). The token never appears in a page URL, which analytics (PostHog, GA4) record along with referrers: the email points at /login/email/link?token=…&email=…, which moves the query into an httpOnly cookie (path /login/email) and redirects to the bare /login/email. That page's "Sign in" button is a form POST back to /login/email/link, which passes the token to NextAuth's callback. Link scanners (e.g. Outlook Safe Links) open URLs but don't submit forms, so they can't use the token up.
  • An OAuth sign-in that confirms the user's own address, and every magic-link sign-in, sets User.emailVerified.
  • The user's GitHub token stays on the server. It has the repo scope, so it is never put in the session or the JWT: /api/auth/session is readable by any script on the page. Nor is it sent to Inngest, which stores event data and step results: post/sync names the user (userId) and the sync function reads the token itself. Server code reads it from the Account table with gitHubAccessToken (server/github-token.ts); it works after a Google or email sign-in too, and every GitHub sign-in stores a fresh one.

Dashboard (authenticated)

  • Layout: app/dashboard/layout.tsx - shadcn's sidebar-08 shell (components/dashboard/shell/dashboard-shell.tsx): an inset sidebar with Overview, Personal (API keys when API_KEYS_ENABLED, Subscriptions, Account settings) and Publishing (Publications and Posts, for the Team and for anyone who owns a publication), breadcrumbs in the header, the user menu in the sidebar footer. Collapsing the sidebar is remembered in the sidebar_state cookie.
  • Breadcrumbs (components/dashboard/shell/breadcrumbs.tsx): pages without names to look up get theirs from the URL; pages that show a publication or post render <SetBreadcrumbs items>. The first crumb also picks the active sidebar link, so a post reached from a publication highlights Publications.
  • The dashboard calls everything in a publication a post (a dataset or a data story such as a blog post). There is no collaboration yet: every dashboard page and list shows only the caller's own publications and posts, Team members included.
  • Components: components/dashboard/ui/ holds shadcn's new-york components from the Tailwind v3 registry (components/ui/ has v4 ones, whose classes don't work under this repo's Tailwind 3); components/dashboard/page-kit.tsx builds pages from them (PageHeader, Section, SectionLayout and SettingsGroup for settings pages with side links, Notice, DataTable, SyncStatusLabel). @portaljs/components/styles.css ships its own Tailwind preflight and utilities, and in the production build it loads after globals.css, so its plain utilities beat our responsive ones. Dashboard buttons set backgrounds with !bg-*, and a class that changes at a breakpoint is written as the wide value plus a max-*:! override: max-lg:!hidden rather than hidden lg:block, flex max-sm:!flex-col rather than flex-col sm:flex-row.
  • Overview: app/dashboard/page.tsx - the Team gets create shortcuts, their recently updated posts with sync status (post.getRecent) and the Personal cards; everyone else gets the API keys, Subscriptions and Get started cards (components/dashboard/overview/).
  • API keys: app/dashboard/api-keys/page.tsx, when API_KEYS_ENABLED (components/dashboard/api-keys-manager.tsx): create a named key (the full dhk_… key is shown once), list, revoke. Keys are free; issuing one needs a verified email, and an account holds at most 10 active keys (apiKey.create locks the user row so parallel creates can't pass the cap). In phase 1 a key unlocks nothing: raw file requests that send one are attributed to its Account (see Raw file analytics). See CONTEXT.md and docs/adr/0001-api-keys-and-raw-file-access.md. Old links to /dashboard/settings#api-keys are sent on in the browser (app/dashboard/settings/api-keys-hash-redirect.tsx).
  • Account settings: app/dashboard/settings/page.tsx - profile (name, username, avatar).
  • Avatar upload (components/dashboard/avatar-uploader.tsx, lib/avatar.ts): the browser crops to 256×256 and PUTs to avatars/<user id>.<ext> with a presigned URL whose signature covers the content type and exact size (image types only, at most 1 MB). user.updateAvatar only accepts that bucket URL.
  • Subscriptions: app/dashboard/subscriptions/page.tsx.
  • Publications: app/dashboard/publications/ - the caller's own publications (publication.list); [id] lists its posts with sync status, sort and pagination; [id]/settings (General, Custom domain, Social image, Danger zone); new. [id]/layout.tsx returns 404 unless the caller owns the publication, as posts/[id]/layout.tsx does for posts.
  • Posts: app/dashboard/posts/ - page.tsx lists the caller's posts across their publications (post.list) with status, filters by name, status and publication, and force sync for one or many rows; [id] overview (sync status with the full error, Sync now, source, public URL, authors) and [id]/settings (General, Source, Comments, Authors, Danger zone), both only for the publication owner; new creates one and opens its overview.
  • Sync status in tables comes from post.getSyncStatuses (lib/sync-status.ts, only the caller's posts): one query over the posts' files (PENDING if any file is still syncing, else ERROR if any failed, else SUCCESS). It never asks GitHub, so only the post overview (post.getSyncStatus) shows Outdated.

Only the DataHub team creates publications and posts and uses the CLI: users with role = ADMIN (isTeamMember in lib/publishing.ts, read from the database, so a role change applies without signing in again). publication.create and post.create refuse everyone else (FORBIDDEN); the /dashboard/publications/new and /dashboard/posts/new pages redirect them to /dashboard, and their create buttons are hidden (server/publishing.tsx). Only the team can approve a CLI login (/cli/auth/authorize), and the CLI API (app/api/v1/_auth.ts) refuses CLI tokens of anyone else with 403, including tokens issued before, so removing someone's ADMIN role cuts off their CLI at once. Publications and posts other users created earlier stay live and editable by their owners in the dashboard. To let someone publish, set their User.role to ADMIN.

Public rendering (publication/post pages)

  • Layout: app/[publication]/layout.tsx - the front shell (components/front/shell.tsx, see Homepage / marketing) without the spreadsheet grid; on a custom domain the shell's links point at the DataHub root domain
  • Publication index: app/[publication]/page.tsx - hero (name, description), then components/front/publication-posts.tsx: card grid of posts (components/front/post-card.tsx), sort and paging as ?sort=/?page= links
  • Local data: node scripts/seed-publications.mjs [slug…] copies publications and their post listings from production; defaults to blog and core. With --content (run as node --env-file=.env …) it also copies each post's main page into the content store, so post pages render. --files <publication>/<project>… copies every file of already-seeded posts (data, datapackage, pages; under 50 MB) into the content store with their Blob rows, so dataset pages get previews, charts and the API file tree
  • Post renderer: app/[publication]/[post]/[[...slug]]/page.tsx - by post kind:
    • story (markdown without a datapackage, e.g. blog posts): front design - components/front/post-hero.tsx (publication, date, title, description, authors, reading time), table of contents (components/front/post-toc.tsx) beside the text (.front-prose in styles/front.css), the publication's newest other posts (components/front/related-posts.tsx), newsletter
      • frontmatter dataset: <publication>/<dataset> (e.g. dataset: core/co2-ppm), or a list (dataset: [core/co2-ppm, core/global-temp]), adds a "Data behind this post" card in the right column (below the text on small screens): one icon, then each dataset's title, path and "View dataset" button. components/front/post-dataset-card.tsx. Datasets that don't exist are left out; with none, no card shows.
      • frontmatter date: YYYY-MM-DD (or published/publishedAt) is the date in the hero and on post cards (lib/post-date.ts); future dates are ignored. Without it the hero shows createdAt and the cards modifiedAt. Lists still sort by modifiedAt.
    • dataset (a datapackage beside the page): components/layouts/datapackage.tsx, see Dataset page
    • Observable notebook: ContentHeader and the embedded notebook
  • Post link previews: generateMetadata in app/[publication]/[post]/layout.tsx emits og:type=article and, via lib/social-image.ts, og:image/twitter:image from frontmatter og_image (a card that differs from the page hero), else image, else the publication's image; relative paths resolve against the post's raw-file base (custom domain aware) with ?preview=true, so crawler fetches aren't counted as downloads (the story's hero image too). No image anywhere: no image tags.
  • Post canonical URL: generateMetadata in app/[publication]/[post]/[[...slug]]/page.tsx sets alternates.canonical per page via lib/canonical-url.ts: https://<custom domain>/<post>[/<page>] when the publication has a custom domain, else https://<root domain>/<publication>/<post>[/<page>]. It returns no openGraph, so the layout's link-preview metadata stays.
  • Subscribe page: app/[publication]/subscribe/page.tsx
  • User profile: app/user/[username]/page.tsx (served at /@username) - front design in its own FrontShell grid: avatar, name and handle, then the user's posts as front post cards (components/front/post-card.tsx) with ?sort=/?page= paging, or an empty state
  • MDX compilation: components/MDX.tsx
  • Dataset page: components/layouts/datapackage.tsx - reads the datapackage via lib/dataset-shape.ts (generic vs full + sample shape, premium state, primary action). The datapackage properties DataHub reads are documented in DATAPACKAGE.md. Front design, top to bottom:
    • hero (components/front/dataset/dataset-hero.tsx): owner / publication / dataset crumbs, Premium or Coming soon badge and data-solution badges, title, description, authors other than the owner, actions; on premium and coming-soon datasets a price or request card (components/front/dataset/offer-card.tsx, #buy) on the right
    • facts row (components/front/dataset/dataset-facts.tsx): downloads, last updated, files or rows, size, format, license; hero and facts carry data-testid="page-header"
    • coming soon only: the full resource's schema as the columns to come
    • data views (components/layouts/data-views-section.tsx), one card each
    • data files: per file, "Data Preview" / "Schema" tabs (components/resource-preview-tabs.tsx) beside components/resource-info-card.tsx
    • data solutions band (components/front/dataset/solution-band.tsx, #solution): one heading with "Request a sample" (request-data dialog, solution_band source, prefilled via requestTemplate) and a call booking, then a row per has_solutions entry (name and pitch from lib/solutions.ts) linking to /solutions/<slug>
    • README with its table of contents and, beside it, the price again or the dataset's collection
    • API access band (components/layouts/programmatic-access-section.tsx, #api): every file's r-link
    • priced premium: a buy bar fixed to the bottom once the price card scrolls away (components/front/dataset/buy-bar.tsx)
  • Dataset resource previews: components/resource-preview.tsx and components/preview/table-preview.tsx - spreadsheet-style table (column letters, row numbers), 10 rows a page; CSV previews prefer resource.sample over resource.path when present and label the UI as sample-based
  • Markdown/MDX processing: lib/markdown.ts
  • MDX component factory: components/mdx-components-factory.tsx
  • MDX call-to-action: components/mdx/request-data-cta.tsx - <RequestData title="…" description="…" meetingUrl="…">body</RequestData> in a post opens the request-data form; submissions are tracked with source blog_post and the post URL
  • Remark plugins (Obsidian wiki-links, embeds, callouts): lib/remark-plugins.tsx

Content sync (Inngest)

  • GitHub client: lib/github.ts
  • Inngest client + events: inngest/client.ts
  • Sync/delete functions: inngest/functions.ts
  • GitHub webhook intake: app/api/webhook/route.ts
  • Inngest handler: app/api/inngest/route.ts

Storage

  • S3/MinIO abstraction: lib/content-store.ts
  • Raw content served via storage redirect

Homepage / marketing

All landing pages live in app/home/ and are served at the root domain via middleware rewrites (e.g. datahub.io/solutions -> app/home/solutions/page.tsx). /pricing has no page: next.config.js redirects it permanently to /solutions.

  • Landing page: app/home/page.tsx (served at /)
  • Collections: app/home/collections/page.tsx (served at /collections) - front design: hero with the collection count, a card per collection (the list mirrors the awesome-data repository), then the request-data and newsletter sections
  • Commons: app/home/commons/page.tsx (served at /commons) - hero saying what the Commons is (entries for datasets other people maintain, as against Core and Collections), then the commons publication's datasets in the publication card grid, counted as "datasets". Entries come from github.com/datasets/commons-datasets. Posts still live at /commons/<name> through the normal publication routes. /collections/d/<slug> pages that moved are 308-redirected by commonsRedirects in middleware.ts.
  • Publications: app/home/publications/page.tsx (served at /publications) - front design: hero with the featured counts, a table of the featured publications (FEATURED_SLUGS; publication, publisher, dataset count), then the request-data and newsletter sections
  • Solutions: app/home/solutions/page.tsx (served at /solutions) - front design: hero with headline facts, a card per solution (names and pitches from lib/solutions.ts; anchors #country-reference, #postal-codes, #logistics), key data features (components/front/solution-features.tsx), and the Enterprise plan on a dark band (components/front/enterprise-pricing.tsx, #pricing) with the work-email form (components/front/enterprise-lead-form.tsx)
    • Sub-pages logistics/, global-country-region-reference-data/, worldwide-postal-code-database/: one story in the same order, from the shared sections in components/front/solutions/sections.tsx: hero with Solutions / <name> crumbs, headline stats, "Request a sample" and a call booking → use cases → what's in the data (components/front/solution-section.tsx: field table, dataset groups with a one-country sample, or the available / on-request dataset lists) → why DataHub → how it works → plans on a dark band (#plans) → FAQ → a closing #contact section. The postal page also lists the most visited countries as cells (components/front/show-all.tsx collapses them on phones). "Request a sample" opens the request-data dialog (solutions_page source) prefilled with the questions sales needs (requestTemplate)

Status pages, front design via components/front/status-hero.tsx (eyebrow, h1, lead and actions; PopularPages link grid under the 404 and 500):

  • 404: app/not-found.tsx; 500: app/[publication]/error.tsx (errors in a publication's pages, inside its FrontShell) and app/error.tsx (errors no deeper boundary catches, such as the publication layout failing; draws its own FrontShell grid). "Try again" refreshes the route and resets the boundary. Invalid download link: app/download/error/page.tsx; purchase result: app/premium/success/page.tsx + success-client.tsx (ready, preparing, emailed). All but app/[publication]/error.tsx wrap themselves in FrontShell grid.
  • Publication and post pages and layouts send failed api calls through notFoundOrThrow (lib/not-found-or-throw.ts). Only a tRPC NOT_FOUND or BAD_REQUEST gives a 404. Anything else (database or storage down) is rethrown, so the request fails with 500 and is logged as an error. post.getBlobContent turns a file missing from storage (NoSuchKey) into NOT_FOUND.

Shared shell and design system (components/front/shell.tsx, used by app/home/layout.tsx and app/[publication]/layout.tsx):

  • Shell: Nav (with the A–E spreadsheet column bar when grid is set), Footer in components/front/. Pages without the grid get .front-plain on the wrapper.
  • Fonts: Space Grotesk (font-display), IBM Plex Sans (font-plex), IBM Plex Mono (font-plex-mono) from styles/fonts.ts, scoped to the .front wrapper.
  • Colour tokens in tailwind.config.js: ink, line, band, paper; accents use Tailwind orange.
  • styles/front.css: the grid behind sections (.front-lines, row numbers via a CSS counter), dark bands (.front-band), scroll-in motion (.front-reveal, driven by components/front/reveal-observer.tsx).
  • components/front/button.tsx: square button with arrow chip (solid, outline, outline-dark).
  • components/front/dialog.tsx: front dialog frame on Radix (backdrop, square panel with eyebrow, title and close button; bottom sheet below 640px) plus form field styles, used by the request-data dialog (components/modal/request-data.tsx, opened through useModal().show(content, { bare: true }) so the dashboard modal frame is skipped) and the checkout dialog (components/premium/buy-premium-button.tsx).
  • components/front/link-card.tsx: card linking to a dataset or solution (icon, title, description, path label, arrow chip; feature paints it orange), used by the landing page's core datasets and the solutions page.
  • components/front/page-hero.tsx: hero of a listing page (eyebrow, or parent / label crumbs; h1, lead, optional actions, two-column facts), used by the solutions pages and sub-pages, publications and collections pages.
  • Hero globe: components/front/globe/ (react-globe.gl, client-only) reading public/assets/globe/.

Middleware routing (middleware.ts)

The middleware handles all URL routing for the multitenant app:

  • /, /collections, /commons, /solutions, /publications -> rewritten to app/home/*
  • /@username -> rewritten to app/user/*
  • /<publication>/<post>/_r/-/<file> -> rewritten to raw file API
  • /<publication>/<post>/r/<file> -> rewritten to legacy raw file API
  • /<publication>/<post>/datapackage.json -> rewritten to raw file API
  • /dashboard/* -> auth guard (redirect to /login if unauthenticated)
  • /login -> redirect to /dashboard if already authenticated; with API_KEYS_ENABLED, /login?ref= keeps ref in a cookie and sends a signed-in visitor to the API keys page
  • Custom domains -> rewritten to /_domain={hostname}/*

API surface

HTTP route handlers (app/api/)

RouteFilePurpose
/api/auth/[...nextauth]app/api/auth/[...nextauth]/route.tsNextAuth OAuth and magic-link endpoints
/api/trpc/[trpc]app/api/trpc/[trpc]/route.tstRPC endpoint
/api/webhookapp/api/webhook/route.tsGitHub push webhook
/api/inngestapp/api/inngest/route.tsInngest function handler
/api/generateapp/api/generate/route.tsAI content generation
/api/raw/...app/api/raw/[publication]/[post]/[branch]/[[...path]]/route.tsxRaw file access: 302 to R2, download stats, file_accessed tracking with the caller's Account, DataHub-Notice header
/api/raw-old/...app/api/raw-old/[publication]/[post]/[resourceWithExtension]/route.tsxLegacy /r/<resource>.<ext> links: 301 to /_r/-/<path> (resource by name, id or index), legacy_raw_requested tracking
/api/v1/publications/...app/api/v1/CLI publishing API, team only: a team user's CLI token or the shared AUTH_BEARER_TOKEN; other users' tokens get 403

Raw file analytics

Each non-preview raw file request (?preview=true is skipped) increments PostStat.downloads and sends two PostHog events sharing a request_id:

  • file_accessed → main project (NEXT_PUBLIC_POSTHOG_KEY, long retention). Carries the dataset, file, user agent, the caller's network (asn, org) and Account (account_id, api_key_id). Never the IP.
  • file_accessed_ip → separate IP project ("Production – caller IPs (90d)", POSTHOG_IP_PROJECT_KEY, set in Vercel Production only). Carries only client_ip, the dataset (publication_slug, dataset_name, dataset_id) and request_id. Events retention is 1 month; PostHog's cleanup runs monthly and deletes whole months, so IPs are gone 33–64 days after capture, inside the privacy policy's 90 days. Not sent when the key is unset.

A weekly caller report reads both projects: repeat callers, how many look like businesses, and requests per IP for quotas. It joins the two events on request_id. It lives in datopian/product-exploration (workflow .github/workflows/datahub-caller-report.yml, script datahub/scripts/caller_report.py, output and definitions in datahub/reports/callers/) and writes only aggregates, never IPs. Renaming any of these event properties breaks it.

lib/caller-network.ts takes the client IP from x-forwarded-for / x-real-ip and looks up asn/org in data/asn.mmdb. That file is DB-IP's free IP to ASN Lite database (GeoLite2-ASN layout, CC BY 4.0). scripts/fetch-asn-db.mjs downloads it during pnpm build, and outputFileTracingIncludes in next.config.js puts it in the route bundle. If the file is missing, asn/org are null; the request still succeeds.

The Account comes from server/raw-caller.ts: the owner of the API key the request sends (Authorization: Bearer dhk_…, else ?apiKey=dhk_…; the header wins), else the signed-in user's session, else none (both null). Keys are looked up by sha256 (lib/api-key.ts); a revoked or unknown key, or a CLI token, counts as no key. A used key gets lastUsedAt stamped (best effort). Nothing is refused or limited. The 302 to R2 never carries the key. ?apiKey= survives the legacy /r/ redirect and the datapackage.json rewrite.

With API_KEYS_ENABLED, a response to a caller with no key and no session carries a DataHub-Notice header pointing to free keys at /login?ref=raw-notice.

Legacy /r/ links (/api/raw-old/...) send legacy_raw_requested to the main project on every request, counted ahead of their sunset. It carries the publication slug or custom domain, the dataset, the requested segment, the outcome (redirected, dataset_not_found, resource_not_found, format_unavailable, invalid_request), the HTTP status, the new_path it maps to, the user agent and asn/org. No IP and no person profile. A redirected request then reaches the raw route and is counted again as file_accessed. Multi-segment /r/ paths don't match the route and get the 404 page, untracked.

lib/consent.ts holds the visitor's choice (localStorage.datahub_consent: granted, denied, or unset = pending). components/cookie-consent.tsx has the banner (mounted in app/providers.tsx for every page and custom domain), WithConsent, and the "Cookie settings" button in the public and publication footers.

Pending / rejectedAccepted
PostHog (lib/posthog-client.ts)Cookieless: no cookies (only PostHog's opt-out flag in local storage), no session recording, no identify; unique visitors via PostHog's server-side daily hashNormal persistence, session recording, signed-in users identified
Google Tag Manager (app/layout.tsx), publisher Google Analytics (app/[publication]/[post]/layout.tsx)Not loadedLoaded

PostHog runs with cookieless_mode: "on_reject"; applyPostHogConsent opts out on every load for anyone who hasn't accepted. Cookieless events are dropped unless cookieless server hash mode is enabled in the PostHog project settings. In cookieless mode posthog.get_distinct_id() returns the shared sentinel $posthog_cookieless, so code that sends the distinct ID to the server (Stripe metadata in components/premium/buy-premium-button.tsx) uses getConsentedDistinctId(), which returns undefined without consent. If localStorage is blocked, the choice holds for the current page only. Withdrawing consent clears Google's _ga* cookies and reloads the page. Sign-out uses resetAnalyticsIdentity, because posthog.reset() also clears PostHog's stored consent.

tRPC routers (via /api/trpc/[trpc])

Composed in server/api/root.ts:

RouterFileKey procedures
postserver/api/routers/post.tsCRUD, sync, settings, tree management; getById, update, delete, sync, getSyncStatus, list, getRecent and getSyncStatuses act only on the caller's own posts (others' posts read as not found, Team included)
publicationserver/api/routers/publication.tsCreate, update, delete publications; getPosts returns each post's root README front-matter date as publishedAt (or null)
likeserver/api/routers/like.tsLike/unlike posts, get like status
subscriptionsserver/api/routers/subscription.tsSubscribe/unsubscribe to publications
userserver/api/routers/user.tsProfile management, avatar upload; search (post authors) is team only; getPostsByUser returns publishedAt like publication.getPosts
apiKeyserver/api/routers/api-key.tsList, create, revoke the Account's API keys (API_KEYS_ENABLED; events api_key_created, api_key_revoked)
homeserver/api/routers/home.tsHomepage data, featured content

Sync architecture (Inngest)

Configuration:

  • inngest/client.ts - Event definitions and client setup
  • inngest/functions.ts - Sync and delete functions

Trigger points

  • Automatic: GitHub push webhooks to the tracked branch, validated by webhook secret.
  • Manual: user-initiated sync from dashboard with force option.
  • Initial sync: on post creation, full repository processing.

Sync flow

  1. Fetch post details and publication/user info from Postgres, and the GitHub token of the event's userId (the post owner, or the CLI user for from-github). The token is read on each invocation and never returned from a step.
  2. Update sync status to PENDING.
  3. Load post configuration, include/exclude patterns, validate root directory.
  4. Fetch current tree from storage and repo tree from GitHub API.
  5. Compare SHA hashes to detect changes (early exit if trees match).
  6. For changed files:
    • Filter by supported extensions (.md, .json, .yaml).
    • Apply include/exclude patterns.
    • Upload raw file to R2/MinIO.
    • Parse frontmatter, compute metadata (title, description, URL).
    • Store/update Blob metadata in Postgres.
  7. Handle deletions (remove files from storage, clean metadata).
  8. Upload new tree, update sync status to SUCCESS, revalidate Next.js cache tags.

Error handling

  • Concurrency limit: 5 per user (event.data.userId).
  • Cancellation: on new sync or delete events for the same post.
  • Non-retriable errors: invalid root dir, YAML parse errors, invalid datapackage format.
  • Retriable errors: GitHub API rate limits, network timeouts, storage upload failures.
  • Error messages stored in database, visible in dashboard.

Cloudflare Worker (external repo)

Repository: datahub-cloudflare-workers (cloned alongside this repo, default ../datahub-cloudflare-workers).

Purpose: process markdown uploads from R2/MinIO, parse frontmatter, update Blob metadata, and index content in Typesense.

  • Consumes queue messages from R2 events (prod/staging) or MinIO webhook (dev at /queue).
  • Skips non-markdown files, supports publish: false to delete content.
  • Storage key pattern: {postId}/{branch}/raw/{path}

Queues:

  • Dev: markdown-processing-queue-dev
  • Staging: datahub-markdown-queue-staging
  • Prod: datahub-markdown-queue

External services

ServicePurposeConfig location
PostgreSQL (Neon/Vercel)Users, publications, posts, blobs, metadataPOSTGRES_PRISMA_URL in .env
R2 (Cloudflare) / MinIORaw markdown files, tree blobsS3_* vars in .env
TypesenseSearch indexingWorker config
InngestBackground sync/delete jobsinngest/functions.ts
GitHub OAuthAuthenticationNEXT_PUBLIC_AUTH_GITHUB_ID, AUTH_GITHUB_SECRET
Google OAuthAuthentication (optional)NEXT_PUBLIC_AUTH_GOOGLE_ID, AUTH_GOOGLE_SECRET
PosthogAnalyticsNEXT_PUBLIC_POSTHOG_KEY
Posthog IP projectRaw caller IPs, deleted within 90 daysPOSTHOG_IP_PROJECT_KEY
DB-IP IP to ASN LiteCaller network (asn/org) lookupscripts/fetch-asn-db.mjs (build)
BrevoNewsletter list (newsletter form)BREVO_* vars
Vercel KV (Upstash)Rate limits (lib/rate-limit.ts): AI SQL (20/h), sign-in links (5/h), per IP; fail openKV_REST_API_URL, KV_REST_API_TOKEN (Production, Preview)
Cloudflare TurnstileCaptchaTURNSTILE_* vars

Testing

Unit tests (Jest)

  • Location: lib/__tests__/, server/api/routers/__tests__/, lib/*.test.ts
  • Run: pnpm test
  • Framework: Jest + Testing Library

E2E tests (Playwright)

  • Location: e2e/renderer/ (public page tests)
  • Config: playwright.config.ts
  • Global setup: e2e/global-setup.ts (seeds test data via Inngest)
  • Run: pnpm exec playwright test --project=renderer-chromium
  • See: e2e/README.md for full guide

CI

  • GitHub Actions workflows in .github/workflows/:
    • e2e.yml - E2E tests against Vercel preview deployments
    • lint.yml - ESLint checks
    • unit.yml - Jest unit tests
    • sync-ga-views.yml - Google Analytics view sync