Project Architecture
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
High-level data flow
- User authenticates via GitHub OAuth and creates a publication.
- User adds posts to the publication, each linked to a GitHub repository/branch.
- A sync is triggered (manual or GitHub webhook) via
app/api/webhook/route.ts. - Inngest sync function pulls files from GitHub, writes raw files to R2/MinIO, and creates/updates
Blobrows in Postgres. - Each markdown upload to storage triggers the Cloudflare Worker via queue.
- The worker parses markdown, updates
Blobmetadata, and indexes in Typesense. - 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:
| Model | Purpose |
|---|---|
User | Authenticated user (GitHub, Google or magic-link sign-in) |
Publication | A named publication owned by a user (like a Substack) |
Post | A content item (dataset or Observable notebook) linked to a GitHub repo, belongs to a Publication |
Blob | A file record (metadata + sync status) belonging to a Post |
Like | User-to-Post like relationship |
PostStat | Daily views/downloads stats per Post |
PostAuthor | Many-to-many Post-to-User author relationship |
PublicationSubscription | User subscription to a Publication |
Account, Session, VerificationToken | NextAuth authentication models |
ApiKey | An Account's API key: sha256 hash, display prefix, label, last used, revoked (lib/api-key.ts) |
UserCliToken, CliDeviceCode | CLI tokens and the dh login handshake (team only) |
Key relationships:
User1->NPublication(owner)Publication1->NPostPost1->NBlobPostN<->NUser(viaPostAuthor)Post1->NLikePost1->NPostStatPublication1->NPublicationSubscriptionUser1->NApiKey
Post types (enum PostType):
DATAPACKAGE- standard markdown/data datasetOBSERVABLE- Observable Framework notebook
Major components
Authentication
- NextAuth config:
server/auth.ts - Email linking rules:
server/auth-identity.ts.User.emailiscitext, 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 incomponents/auth/sign-in-options.tsx). WhenAPI_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 keepsrefin thedatahub-sign-up-refcookie for a day (lib/sign-up-ref.ts), andaccount_createdandapi_key_createdcarry 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 inlib/sign-in-link.ts), confirmation pageapp/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 updatesUser.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
reposcope, so it is never put in the session or the JWT:/api/auth/sessionis readable by any script on the page. Nor is it sent to Inngest, which stores event data and step results:post/syncnames the user (userId) and the sync function reads the token itself. Server code reads it from theAccounttable withgitHubAccessToken(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 whenAPI_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 thesidebar_statecookie. - 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.tsxbuilds pages from them (PageHeader, Section, SectionLayout and SettingsGroup for settings pages with side links, Notice, DataTable, SyncStatusLabel).@portaljs/components/styles.cssships its own Tailwind preflight and utilities, and in the production build it loads afterglobals.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 amax-*:!override:max-lg:!hiddenrather thanhidden lg:block,flex max-sm:!flex-colrather thanflex-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, whenAPI_KEYS_ENABLED(components/dashboard/api-keys-manager.tsx): create a named key (the fulldhk_…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.createlocks 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). SeeCONTEXT.mdanddocs/adr/0001-api-keys-and-raw-file-access.md. Old links to/dashboard/settings#api-keysare 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 toavatars/<user id>.<ext>with a presigned URL whose signature covers the content type and exact size (image types only, at most 1 MB).user.updateAvataronly 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.tsxreturns 404 unless the caller owns the publication, asposts/[id]/layout.tsxdoes for posts. - Posts:
app/dashboard/posts/-page.tsxlists 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;newcreates 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), thencomponents/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 toblogandcore. With--content(run asnode --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-proseinstyles/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(orpublished/publishedAt) is the date in the hero and on post cards (lib/post-date.ts); future dates are ignored. Without it the hero showscreatedAtand the cardsmodifiedAt. Lists still sort bymodifiedAt.
- frontmatter
- dataset (a datapackage beside the page):
components/layouts/datapackage.tsx, see Dataset page - Observable notebook:
ContentHeaderand the embedded notebook
- story (markdown without a datapackage, e.g. blog posts): front design -
- Post link previews:
generateMetadatainapp/[publication]/[post]/layout.tsxemitsog:type=articleand, vialib/social-image.ts,og:image/twitter:imagefrom frontmatterog_image(a card that differs from the page hero), elseimage, 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:
generateMetadatainapp/[publication]/[post]/[[...slug]]/page.tsxsetsalternates.canonicalper page vialib/canonical-url.ts:https://<custom domain>/<post>[/<page>]when the publication has a custom domain, elsehttps://<root domain>/<publication>/<post>[/<page>]. It returns noopenGraph, 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 ownFrontShell 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 vialib/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 carrydata-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) besidecomponents/resource-info-card.tsx - data solutions band (
components/front/dataset/solution-band.tsx,#solution): one heading with "Request a sample" (request-data dialog,solution_bandsource, prefilled viarequestTemplate) and a call booking, then a row perhas_solutionsentry (name and pitch fromlib/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)
- hero (
- Dataset resource previews:
components/resource-preview.tsxandcomponents/preview/table-preview.tsx- spreadsheet-style table (column letters, row numbers), 10 rows a page; CSV previews preferresource.sampleoverresource.pathwhen 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 sourceblog_postand 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 thecommonspublication'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 bycommonsRedirectsinmiddleware.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 fromlib/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 incomponents/front/solutions/sections.tsx: hero withSolutions / <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#contactsection. The postal page also lists the most visited countries as cells (components/front/show-all.tsxcollapses them on phones). "Request a sample" opens the request-data dialog (solutions_pagesource) prefilled with the questions sales needs (requestTemplate)
- Sub-pages
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 itsFrontShell) andapp/error.tsx(errors no deeper boundary catches, such as the publication layout failing; draws its ownFrontShell 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 butapp/[publication]/error.tsxwrap themselves inFrontShell grid. - Publication and post pages and layouts send failed
apicalls throughnotFoundOrThrow(lib/not-found-or-throw.ts). Only a tRPCNOT_FOUNDorBAD_REQUESTgives a 404. Anything else (database or storage down) is rethrown, so the request fails with 500 and is logged as an error.post.getBlobContentturns a file missing from storage (NoSuchKey) intoNOT_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 whengridis set),Footerincomponents/front/. Pages without the grid get.front-plainon the wrapper. - Fonts: Space Grotesk (
font-display), IBM Plex Sans (font-plex), IBM Plex Mono (font-plex-mono) fromstyles/fonts.ts, scoped to the.frontwrapper. - Colour tokens in
tailwind.config.js:ink,line,band,paper; accents use Tailwindorange. 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 bycomponents/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 throughuseModal().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;featurepaints 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, orparent / labelcrumbs; 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) readingpublic/assets/globe/.
Middleware routing (middleware.ts)
The middleware handles all URL routing for the multitenant app:
/,/collections,/commons,/solutions,/publications-> rewritten toapp/home/*/@username-> rewritten toapp/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/loginif unauthenticated)/login-> redirect to/dashboardif already authenticated; withAPI_KEYS_ENABLED,/login?ref=keepsrefin 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/)
| Route | File | Purpose |
|---|---|---|
/api/auth/[...nextauth] | app/api/auth/[...nextauth]/route.ts | NextAuth OAuth and magic-link endpoints |
/api/trpc/[trpc] | app/api/trpc/[trpc]/route.ts | tRPC endpoint |
/api/webhook | app/api/webhook/route.ts | GitHub push webhook |
/api/inngest | app/api/inngest/route.ts | Inngest function handler |
/api/generate | app/api/generate/route.ts | AI content generation |
/api/raw/... | app/api/raw/[publication]/[post]/[branch]/[[...path]]/route.tsx | Raw 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.tsx | Legacy /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 onlyclient_ip, the dataset (publication_slug,dataset_name,dataset_id) andrequest_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.
Cookie consent (client analytics)
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 / rejected | Accepted | |
|---|---|---|
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 hash | Normal persistence, session recording, signed-in users identified |
Google Tag Manager (app/layout.tsx), publisher Google Analytics (app/[publication]/[post]/layout.tsx) | Not loaded | Loaded |
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:
| Router | File | Key procedures |
|---|---|---|
post | server/api/routers/post.ts | CRUD, 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) |
publication | server/api/routers/publication.ts | Create, update, delete publications; getPosts returns each post's root README front-matter date as publishedAt (or null) |
like | server/api/routers/like.ts | Like/unlike posts, get like status |
subscriptions | server/api/routers/subscription.ts | Subscribe/unsubscribe to publications |
user | server/api/routers/user.ts | Profile management, avatar upload; search (post authors) is team only; getPostsByUser returns publishedAt like publication.getPosts |
apiKey | server/api/routers/api-key.ts | List, create, revoke the Account's API keys (API_KEYS_ENABLED; events api_key_created, api_key_revoked) |
home | server/api/routers/home.ts | Homepage data, featured content |
Sync architecture (Inngest)
Configuration:
inngest/client.ts- Event definitions and client setupinngest/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
- 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 forfrom-github). The token is read on each invocation and never returned from a step. - Update sync status to
PENDING. - Load post configuration, include/exclude patterns, validate root directory.
- Fetch current tree from storage and repo tree from GitHub API.
- Compare SHA hashes to detect changes (early exit if trees match).
- 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
Blobmetadata in Postgres.
- Handle deletions (remove files from storage, clean metadata).
- 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: falseto 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
| Service | Purpose | Config location |
|---|---|---|
| PostgreSQL (Neon/Vercel) | Users, publications, posts, blobs, metadata | POSTGRES_PRISMA_URL in .env |
| R2 (Cloudflare) / MinIO | Raw markdown files, tree blobs | S3_* vars in .env |
| Typesense | Search indexing | Worker config |
| Inngest | Background sync/delete jobs | inngest/functions.ts |
| GitHub OAuth | Authentication | NEXT_PUBLIC_AUTH_GITHUB_ID, AUTH_GITHUB_SECRET |
| Google OAuth | Authentication (optional) | NEXT_PUBLIC_AUTH_GOOGLE_ID, AUTH_GOOGLE_SECRET |
| Posthog | Analytics | NEXT_PUBLIC_POSTHOG_KEY |
| Posthog IP project | Raw caller IPs, deleted within 90 days | POSTHOG_IP_PROJECT_KEY |
| DB-IP IP to ASN Lite | Caller network (asn/org) lookup | scripts/fetch-asn-db.mjs (build) |
| Brevo | Newsletter 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 open | KV_REST_API_URL, KV_REST_API_TOKEN (Production, Preview) |
| Cloudflare Turnstile | Captcha | TURNSTILE_* 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.mdfor full guide
CI
- GitHub Actions workflows in
.github/workflows/:e2e.yml- E2E tests against Vercel preview deploymentslint.yml- ESLint checksunit.yml- Jest unit testssync-ga-views.yml- Google Analytics view sync