Skip to Content
gentlemans-stack
Reference

GentlemansStack

An opinionated starting point for a SaaS product: web, mobile and APIs in one Nx + pnpm monorepo, built so a human and an AI assistant can change it safely and cheaply.

It is a boilerplate, not a framework and not a product. No product code ships here. The Todo chain (models/todo-model → contracts/todo-contracts → domains/todo-domain → services/todo-service → apps/todo-ui) is a worked example to generate from and diff against.

What you get

AreaIncluded
BackendContract-first Hono + oRPC services over MongoDB, a generated OpenAPI spec and /docs, Redis cache, per-procedure rate limits, security headers
IdentityOne IAM service on Better Auth: cookie and bearer sessions, two-factor, passkeys, GitHub and Discord linking, account deletion
Multi-tenancyWorkspaces, members, invitations, intent-based roles, and an audit log with an Activity view
WebTanStack Start app, shadcn/ui design system, schema-driven forms from one Zod schema, en and de messages
MobileFlutter apps themed from the same design tokens as the web
ObservabilityOpenTelemetry from browser to Mongo, through a Collector into local Grafana (traces, logs, metrics)
GeneratorsNx generators for models, contracts, domains, services, web apps and mobile apps, so new code is generated, not copied
AI-nativeAGENTS.md rulebook, repo skills for every recurring task, a docs map, and small packages with one job each

Every choice, and why it beat the alternatives, is in docs/stack.md, and the ideas behind them are in docs/principles.md. The same Markdown builds the documentation site in apps/docs (pnpm docs:build, then pnpm docs:dev to preview).

What it is not

  • Not a published package yet: you clone it. Publishing the libs and a CLI are on the backlog.
  • Not tied to a cloud: the core has no provider. Google Cloud Run is an optional add-on under platforms/gcp.
  • Not finished for production: the gaps (email delivery, background jobs, billing and more) are listed in the backlog.

Requirements

  • Node.js 26 (the Docker images use node:26-alpine; no engines field is pinned and @types/node targets v26)
  • pnpm (the Docker images install 12.23.0 with npm, because Node 26 no longer ships corepack; install it with Homebrew, mise or npm)
  • Docker, for the local MongoDB (a replica set, because Better Auth uses transactions), Redis and Grafana
  • Flutter SDK (only for apps/todo-mobile and other mobile apps; flutter and dart on PATH)

Getting started

pnpm install
cp .env.example .env     # then set IAM_SERVICE_AUTH_SECRET to a random string of at least 32 characters
pnpm infra:up            # MongoDB, Redis, OpenTelemetry Collector, Grafana (LOCAL_INFRA)

Run the services and the web app, each in its own terminal:

pnpm nx serve iam-service    # sign-in, workspaces, invitations: http://localhost:33001/docs
pnpm nx serve todo-service   # the example API: http://localhost:33002/docs
pnpm nx dev todo-ui          # the web app: http://localhost:4200

Open http://localhost:4200, sign up, and create a workspace and a todo. .env.example documents every variable; the IAM variables are listed in services/iam-service/README.md. E2E_PASSWORD (at least 8 characters, never committed) is only for the todo-ui:e2e Playwright run, which runs locally (there is no CI pipeline yet); see apps/todo-ui/README.md.

Every service answers on the same routes:

RouteDescription
/Health check: service name, version, Mongo status
/docsInteractive API reference (Scalar)
/openapi.jsonGenerated OpenAPI 3.1 spec
/api/*REST-style endpoints
/rpc/*oRPC endpoints for typed TypeScript clients

Callers are authenticated through iam-service sessions; the todo-service README shows how another provider plugs in (services/todo-service/README.md).

Observability

pnpm infra:up also starts the Collector (OTLP on localhost:4318) and Grafana on http://localhost:9300 (admin / admin). Services send traces, metrics and logs to the Collector with no setup; open Grafana, Explore, and pick Tempo (traces), Loki (logs) or Prometheus (metrics). A click in todo-ui shows up as one trace from the browser through the service into Mongo. Optional env vars: OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_SDK_DISABLED=true (off) and, for todo-ui, VITE_OTEL_COLLECTOR_URL. See libs/observability and LOCAL_INFRA.

Starting a product

  1. Clone this repo (or use it as a template) and follow Getting started above.
  2. Keep the @gentlemans-stack/* scope. Shared code reaches a product through node scripts/sync-from-stack.mjs --check and the same command without --check; renaming the scope would cut that link.
  3. Rebrand the web and Flutter themes in ui-libs/design-tokens/src/tokens.json, then pnpm nx run design-tokens:generate.
  4. Generate your own packages with pnpm nx g @gentlemans-stack/nx-plugin:<generator> --dry-run (model, contract, domain, deployable-service, deployable-web-app, mobile-app). Diff against the Todo chain instead of copying it.
  5. Replace the contact in SECURITY.md.

A gentlemans-stack CLI that wraps these steps is on the backlog.

How the code is layered

Dependencies point down only. Each layer has one job, so a change touches few files and an AI assistant needs little context.

apps/ and services/   composition roots: wire config, connectors, contracts and domains together
contracts/ domains/   public service APIs (oRPC) and Mongoose repositories
libs/ connectors/     foundation (auth, cache, server setup, observability) and isolated infrastructure adapters
models/               portable Zod schemas shared by browser, server and mobile

Add an endpoint by going up the layers once; the recipe is in docs/adding-an-endpoint.md.

Working with AI tools

Point Claude Code, Codex, Cursor or Copilot at AGENTS.md: it holds the commands, rules and recipes (CLAUDE.md imports it and adds the Claude Code specifics). Recurring tasks have skills in .claude/skills (endpoint, form, repository tests, Flutter page and more), and docs/README.md says which doc answers which question.

Agent tooling (installed once per machine)

Only tooling every repo needs is global. The repo's tracked .claude/settings.json holds only project hooks (format on edit, Nx daemon sandbox rules), and its tracked .mcp.json adds fallow, chrome-devtools and shadcn through npx -y <pkg>@latest (Claude asks once per machine before starting them).

  • MCP servers in ~/.claude.json: context7
  • Plugin context-mode@context-mode, plus the trail hooks in ~/.claude/settings.json
  • CONTEXT7_API_KEY exported from ~/.zshenv (the desktop app never reads ~/.zshrc); never write the key into a repo file
  • Generic skills, rules and agents from agentry-labs: scripts/install.sh --global --bundle global, and --bundle flutter, --bundle mongodb or --bundle web where they apply (add --source <path to a local checkout> to avoid cloning)
  • Skills tied to this stack's layers and generators (api-endpoints, service-handler-tests, ...) live in this repo's .claude/skills and are copied into projects built from it

The apply-global script in agentry-labs previews the changes to your global settings and MCP servers before writing them. A repo-level .mcp.json is only for servers that belong to that project, and holds no secrets: use ${VAR} expansion or let the server read the project's .env.

Commands

pnpm install                                                  # install deps (pnpm + catalog: versions)
pnpm infra:up                                                 # start local MongoDB, Redis, the OpenTelemetry Collector and Grafana (LOCAL_INFRA)
pnpm infra:down                                               # stop them
pnpm nx serve <project>                                       # run a service/app
pnpm typecheck                                                # typecheck every project in parallel
pnpm nx test <project>                                        # run a project's Vitest suite
pnpm exec playwright install chromium                         # once per machine, for the e2e target
pnpm nx run todo-ui:e2e                                       # Playwright e2e, local only (needs Mongo, iam-service, todo-ui, E2E_PASSWORD)
pnpm nx build <project>                                       # build a service/app
pnpm nx docker:build <service>                                # build the container image
pnpm nx docker:run <service>                                  # run it locally (reads root .env)
pnpm nx g @gentlemans-stack/nx-plugin:connector <name>        # new isolated connector package
pnpm nx g @gentlemans-stack/nx-plugin:model <name>            # new portable Zod model package
pnpm nx g @gentlemans-stack/nx-plugin:contract <name>         # new oRPC service contract package
pnpm nx g @gentlemans-stack/nx-plugin:domain <name>            # new Mongoose domain package
pnpm nx g @gentlemans-stack/nx-plugin:deployable-service <name> --contracts=<c> --domains=<d>
pnpm nx g @gentlemans-stack/nx-plugin:deployable-service <name> --auth=iam  # callers resolved through iam-service sessions (default dev)
pnpm nx g @gentlemans-stack/nx-plugin:deployable-service <name> --platform=gcp --deploy=cloud-run  # + auth-firebase dep, cloud-run.config.sh, `nx deploy`
pnpm nx g @gentlemans-stack/nx-plugin:deployable-web-app <name> --design-system
pnpm nx g @gentlemans-stack/nx-plugin:mobile-app <name>      # new Flutter app themed from ui-libs/design-tokens
pnpm nx g @gentlemans-stack/nx-plugin:mobile-app-rename <name> --newName=<n> --orgId=<org>  # rename app / bundle id everywhere
pnpm nx run design-tokens:generate                            # regenerate web CSS + Flutter theme from tokens.json
pnpm nx run <mobile-app>:analyze|test|run                      # Flutter tasks run through Nx too
pnpm sync:deploy-deps <project> [--check]                     # sync bundle-retained deps for a service
pnpm check:iam-boundary                                       # fail if code outside iam-service reads Better Auth's collections
node scripts/sync-from-stack.mjs [--check|--dry-run]          # in a project: copy kit paths from the stack (stack-sync.json)
node scripts/docs-lint.mjs                                    # check doc headings, relative links and pnpm/node commands (template: docs/DOC_TEMPLATE.md)
pnpm check                                                    # Biome (ultracite) lint/format check
pnpm fix                                                      # apply lint/format fixes
pnpm clean                                                    # reset Nx cache + build/output dirs
pnpm verify                                                   # typecheck + check + IAM boundary + build + deploy-dep check

Formatting runs automatically on commit via a lefthook pre-commit hook.

Project layout

LOCAL_INFRA/        Docker Compose for local MongoDB, Mongo Express, Redis, RedisInsight, an OpenTelemetry Collector and Grafana (pnpm infra:up)
models/             Browser-safe runtime schemas and inferred types: todo, workspace, audit, app-error
contracts/          Public oRPC service APIs consumed by services and clients: todo, workspace
libs/               Foundation packages: configuration, cache, contract-kit, app-errors, request-logger, test-support,
                     server-setup (transport), auth, email, rate-limit, observability
connectors/         Isolated infrastructure adapters plus the shared connector-factory contract (MongoDB, Redis, SMTP)
domains/            Mongoose schemas and repositories, reusable by any service: todo, workspace, audit
platforms/gcp/auth-firebase  Firebase AuthProvider (firebase-admin or JWKS); core never imports platforms/
platforms/gcp/cloud-run  Bash deploy/cleanup scripts for Cloud Run and Artifact Registry (not an Nx project)
ui-libs/design-tokens  tokens.json: single source for the web theme and every Flutter app's theme
ui-libs/design-system  shadcn/ui components + Tailwind v4 theme (tokens.css is generated), source-only like libs/*; `pnpm nx run design-system:storybook` shows them; the `data-table` subpath adds TanStack Table (`DataTable`) and the `form` subpath adds the schema-driven form builder
services/todo-service  Composition root: config + connectors + server-setup + auth + todo-contracts + todo-domain
services/iam-service  Identity: Better Auth (cookie sessions, admin + bearer) mounted at /api/auth, plus workspaces, members, invitations and the audit feed (workspace-contracts); todo-ui signs in against it
apps/todo-ui         TanStack Start app consuming the contracts via @orpc/tanstack-query
apps/todo-mobile     Flutter app themed from design-tokens (shell + Design tokens screen)
apps/email-templates React Email authoring/preview workspace (welcome/notification examples)
tools/nx-plugin      Generators: connector, model, contract, domain, deployable-service, deployable-web-app, mobile-app
tools/image-gen-tools Store screenshots, icons and website images rendered from HTML (Playwright + sharp)
docs/               Architecture, guides, principles, stack, learnings, backlog, design tokens and Flutter targets (map: docs/README.md)
scripts/             Node (.mjs) scripts: Docker build/run, dependency sync, IAM boundary check, version bump, kit sync into projects, docs lint,
                     scripts/flutter/ device and release builds

Deployment

Services build to a single bundled CommonJS file plus a pruned lockfile and are packaged as plain Docker images, with docker:build/docker:run only, no registry push and no assumed cloud host (see docs/stack.md). Before a service's first Docker build, run pnpm sync:deploy-deps <project> --check to confirm its package.json declares every package its bundle retains; this also runs automatically as part of that service's sync-deploy-deps Nx target and pnpm verify.

To run on Google Cloud Run, platforms/gcp/cloud-run has the registry push, deploy and cleanup scripts (all with --dry-run); they reuse the docker:build target and nothing in the core depends on them.

More

docs/README.md maps every document. Report vulnerabilities as described in SECURITY.md.

On this page