# roux > The base a Go + React application is built on. roux is the base a Go + React application is built on. The server side is the Go module github.com/jwcarman/roux: an app's main is app.Main, its features are modules (a package with SQL migrations, a pgx service and handlers mounted with kit.Handle behind a permission), and roux brings sign-in (emailed links and codes, passkeys, OpenID Connect, API keys, JWTs), roles and permissions, the users directory, Problem Details errors, paging (page.New), money, dates and the activity log. The web side is the npm package @jwcarman/roux-web (React 19, Chakra UI v3, TanStack Router, Query, Form and Table, Zod 4). New apps start from the template: npm create @jwcarman/roux-app. The changelog says what each version has: https://github.com/jwcarman/roux/blob/main/CHANGELOG.md. An Agent Skill packages these guides for coding agents: see the Agent Skill page. # Start here # roux The base a Go + React application is built on. Go 1.27 · PostgreSQL 17 · React 19 · Chakra UI v3 · TanStack [Get started](https://jwcarman.github.io/roux/guides/getting-started/index.md) [View on GitHub](https://github.com/jwcarman/roux) **roux is written for agents.** It is designed for a coding agent to get right the first time: one way to do each thing, exact names that match across Go, TypeScript and these docs, mistakes that fail loudly instead of silently, and an [Agent Skill](https://jwcarman.github.io/roux/agent-skill/index.md) that carries all of it into the agent's context. Every example here is code CI builds. roux is what every business app needs before its first feature: people who sign in, roles and permissions, a team to invite, errors a person can read, paged lists, forms, money and dates. A new app starts from roux's template with all of it working; each feature the app adds is a Go package and a folder of pages, and uses roux by importing from it. ``` func Register(k *app.Kit, svc Service) { k.Handle("GET /api/labels", LabelsRead, func(w http.ResponseWriter, r *http.Request) error { out, err := svc.List(r.Context()) if err != nil { return err } return api.JSON(w, http.StatusOK, out) }) } ``` The route is behind the CSRF check, a sign-in and the `labels.read` permission before the handler runs; anything the handler refuses is answered as a Problem Detail the browser's forms show under the right field. ## What you get - **Sign-in, done** ______________________________________________________________________ Emailed links and codes, passkeys, Google, GitHub or any OpenID Connect provider, API keys and JWTs, all resolving to one person, with sessions, CSRF and a first owner. - **Permissions, not roles** ______________________________________________________________________ Routes check permissions; roles are data, granted by migrations. The browser's list of permissions is generated from the server's, and a test checks every grant. - **The team** ______________________________________________________________________ Invite people, give them a role, rename, deactivate, sign them out everywhere, with a history of every change. - **Lists and forms** ______________________________________________________________________ A paginator over a view on the server; tables, growing lists and pickers in the browser. Forms validated in the server's own words, with versions that refuse a stale save. - **Money and dates** ______________________________________________________________________ Amounts in minor units, never floats. The organization's zone and today, the same on the server and in the browser. - **One binary** ______________________________________________________________________ The front end built into the server; one distroless container image; health probes, OpenTelemetry and a graceful shutdown. ## How an app is put together - **`cmd/server/main.go`** is one call, `app.Main`, naming the app, its built front end and its modules. - **`cmd/server/modules.go`** lists the modules: roux's (sign-in, users, passkeys...) and the app's own. Turning a feature on is a line. - **`internal//`** is one feature's server side: its SQL migrations, a service over pgx, and handlers mounted behind permissions ([A feature's server side](https://jwcarman.github.io/roux/guides/features/index.md)). - **`frontend/src//`** is its pages, built on `@jwcarman/roux-web`. Start with [Getting started](https://jwcarman.github.io/roux/guides/getting-started/index.md). # Getting started roux is the base a Go + React application is built on. The server side is a Go module, `github.com/jwcarman/roux`: sign-in (emailed links and codes, passkeys, providers, API keys, JWTs), roles and permissions, the users directory, errors as Problem Details, paging, money, dates, the activity log, and the page shell. The web side is an npm package, `@jwcarman/roux-web`, with the matching API client, paging, tables, forms and feedback. A new app starts from roux's app template (below); the rest of this guide is what the template already does. Either way, features use roux by importing from it; no plumbing is written in the app. ## Start a new app 1. **Make the app.** With Node 20 or later: ``` npm create @jwcarman/roux-app team-planner ``` `team-planner` is the directory, the Go module and the npm name: lowercase letters, digits and single dashes. The app is called "Team Planner" until the owner renames it on the Appearance page; pass another name with `npm create @jwcarman/roux-app team-planner -- --name "Acme Planner"`. It is roux's app template at the latest release (sign-in, the first owner, the sidebar frame, Users, Settings and Appearance), with roux from the Go module proxy and npm, and a first commit. 2. **Run it.** With Docker running and Go 1.27, in the app's directory: ``` make dev ``` That starts PostgreSQL (`localhost:5432`, user, password and database `app`) and Mailpit, which catches every email the app sends and shows it at ; then runs the server under [air](https://github.com/air-verse/air) and Vite together, with development settings: a development `CODE_SECRET`, the compose database, and `owner@example.com` as the first owner. Open , the one address for everything: Vite serves the pages and passes `/api` to the server, and sign-in links, passkeys and cookies all name that address. Edit a page and it reloads; edit Go (or a migration or an email template) and air rebuilds and restarts the server, printing the compiler's error when the build fails. Each setting gives way to the environment: `OWNER_EMAIL=you@example.com make dev` makes you the owner instead. One Ctrl-C stops both; if either stops on its own, the other is stopped and `make dev` fails. 3. **Sign in as the owner.** On the sign-in page, ask for a link for the owner's address and open it from Mailpit. roux made that address the `OWNER` on the first start. 4. **Add a first page.** Ask your agent for it: roux's Claude Code plugin (the `roux` skill) says where each piece goes, and the app's `.claude/settings.json` names it, so Claude Code offers to install it when you trust the folder: accept. By hand, a feature is a Go package in `internal//` listed in `cmd/server/modules.go` ([A feature's server side](https://jwcarman.github.io/roux/guides/features/index.md)), and a page is a feature folder in `frontend/src//`, a route file in `frontend/src/routes/_signedIn/`, and an entry in `frontend/src/shell/nav.ts` ([The shell](https://jwcarman.github.io/roux/guides/shell/index.md)). `make check` runs the Go checks (gofmt, `go vet`, golangci-lint, the tests; `make lint` builds the Makefile's pinned golangci-lint into `bin/` the first time, so nothing needs installing); in `frontend/`, `npm run format` (Prettier), `npm run lint` (ESLint, type-aware), `npm run coverage` (Vitest, 100% of lines and branches), `npm run build` and `npm run mutate` run the browser's. ESLint and Prettier live in `frontend/lint-tools/`, with an install of their own, which `npm run lint`, `format` and `format:check` make when it is missing: typescript-eslint does not yet support TypeScript 7, the app's compiler. `make build` makes the release binary, one file with the front end inside, and `make image` the container image. `make up` runs that image as a deployment does, beside Postgres and Mailpit (`docker compose --profile app`), at ; `make down` stops it. Stop `make dev` first: its server uses port 8080 too. ## Requirements roux supports one stack and nothing else: - Go 1.27, `net/http`'s router, pgx 5. - PostgreSQL 17. roux runs its own migrations and the app's. - React 19, Chakra UI v3, TanStack Router, Query, Form and Table, Zod 4. - Go's `testing` with a real database, Vitest with MSW, and Playwright, for tests. Database tests start PostgreSQL in Docker, or use `TEST_DATABASE_URL`. ## The server An app's whole `main` is one call: ``` // Command server runs Team Planner. package main import ( "github.com/jwcarman/roux/app" web "team-planner/frontend" ) func main() { app.Main(app.Config{Name: "team-planner", DisplayName: "Team Planner", Frontend: web.Dist, Modules: modules}) } ``` `app.Main` runs the app until SIGINT or SIGTERM and exits 1, logging why, if it fails. In order it sets up logging and telemetry, the health probes (`/api/roux/healthz` and `/api/roux/readyz`), the database (`DATABASE_URL`), the modules, the front end, and an HTTP server on `ADDR` with every connection bounded in time. When it is told to stop, it fails readiness, waits `SHUTDOWN_DELAY` so a load balancer notices, stops taking requests, and lets the modules finish their work in flight (an email accepted a moment ago still goes out). `app.Run(ctx, cfg)` is the same without the signals and the exit. | `app.Config` field | What it is | | ------------------ | ----------------------------------------------------------------------------------------------------------------- | | `Name` | The service's name in traces and logs. | | `DisplayName` | The app's name on its pages and in its emails, unless `APP_NAME` says otherwise (and until the owner renames it). | | `Frontend` | The front end built into the binary: the `frontend` package's `Dist`. | | `Modules` | `func(k *app.Kit) ([]app.Module, error)`: what the app is made of. | ### Modules A module is one feature: the tables it owns, the sign-in method it brings, the routes it mounts and what it does at startup. `modules.go` lists them, so turning a feature on is a line: ``` func modules(k *app.Kit) ([]app.Module, error) { mods := []app.Module{&appRoles{}} emails, err := fs.Sub(emailFiles, "emails") // cmd/server/emails: your wording for roux's emails if err != nil { return nil, err } email, err := app.EmailLinkFromEnv(k.AppName, emails) if err != nil { return nil, err } members := app.UsersFromEnv(email) passkeys, err := app.PasskeysFromEnv(k.AppName, email) if err != nil { return nil, err } mods = append(mods, email, members, items.Module{}) if passkeys != nil { mods = append(mods, passkeys) } return mods, nil } ``` Each stock module reads its settings from the environment. Email sign-in and users are always on; the others are nil when their feature is off. One that needs another takes it as an argument (passkeys take the email module), so a missing dependency does not compile. roux's stock modules: | Constructor | The feature | | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `app.EmailLinkFromEnv(appName, emails)` | Sign-in by an emailed link or typed code; `emails` is the app's wording for any of roux's emails ([Email](https://jwcarman.github.io/roux/guides/email/index.md)). Needs `CODE_SECRET`. | | `app.UsersFromEnv(email)` | The users directory, roles and invitations, the owner's theme, the organization, and the first owner ([Users](https://jwcarman.github.io/roux/guides/users/index.md), [Roles and permissions](https://jwcarman.github.io/roux/guides/roles/index.md)). | | `app.PasskeysFromEnv(appName, email)` | Passkeys, for the address in `PUBLIC_URL`. On unless `PASSKEYS=false`. | | `app.APIKeysFromEnv(email)` | API keys, made by a signed-in person. On unless `API_KEYS=false`. | | `app.OIDCFromEnv(email, members)` | Sign-in with Google, GitHub or any OpenID Connect provider. Nil without `OIDC_PROVIDERS_FILE`. | | `app.JWTFromEnv(email)` | Bearer tokens from an authorization server, for API-only callers. Nil without `JWT_ISSUER`. | An app's own feature is a module too: a type with `Name()`, and any of these, each an interface in `app`: - `app.Migrator`: `Migrations() []pgdb.Migration`, its SQL; - `app.Mounter`: `Mount(ctx, k) error`, its routes; - `app.Starter`: `Start(ctx, k) error`, run after every module has mounted (checking a list's SQL); - `app.Drainer`: `Drain()`, work in flight (an email) to finish before the process exits. [A feature's server side](https://jwcarman.github.io/roux/guides/features/index.md) builds one. A module's own setting is read with `app.Getenv(key, fallback)`, `os.Getenv` with a default. `app.Main` opens the database with `pgdb.Connect`. `app.Assemble` runs every module's migrations together (ordered by each migration's `After` and `Before`), registers sign-in with every module's method, then mounts the modules and starts them, in the order listed. A failure names the module. ### Settings Everything else comes from the environment. A missing required setting stops startup, naming it, and so does a value roux cannot read: `true` and `false` are the only booleans, and a duration has a unit (`30s`). | Variable | What it is | | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `DATABASE_URL` | PostgreSQL. Required: a module with tables stops startup without it. | | `ADDR` | Where the server listens (default `:8080`). | | `PUBLIC_URL` | Where browsers reach the app (default `http://localhost:8080`): sign-in links point here, and `https://` marks every cookie Secure. Behind a load balancer that ends TLS, set it to the `https` address. | | `COOKIE_SECURE` | `true` or `false`, overriding what `PUBLIC_URL` says. A `PUBLIC_URL` of `http://` for a host other than this machine is refused unless this is `false`. | | `APP_NAME` | The app's name, instead of `DisplayName`. | | `CODE_SECRET` | At least 32 random characters (`openssl rand -base64 32`), the same on every instance: keys the typed sign-in codes. Required. A secret weaker than about 128 bits (its length times log2 of the character kinds it uses: lower case, upper case, numerals, others; one repeated character counts once) logs a warning at startup. `make dev`'s secret is not warned about, but is refused when `PUBLIC_URL` starts with `https://`. | | `SMTP_ADDR`, `MAIL_FROM` | The mail server, `host:port` (default `localhost:1025`, Mailpit), and the sender (default `no-reply@localhost`). `SMTP_USERNAME` and `SMTP_PASSWORD` are the server's login, both or neither. Mail to a server off this machine goes over STARTTLS unless `SMTP_ALLOW_PLAINTEXT=true`. | | `EMAIL_RESEND_INTERVAL`, `EMAIL_TOKEN_TTL` | How soon another sign-in email may be asked for, and how long a link or code lasts (defaults `60s` and `5m`). | | `OWNER_EMAIL`, `OWNER_NAME` | The first owner: while no active user holds `OWNER`, roux creates one at startup, who signs in with that address. Both or neither; once an active owner exists they change nothing, and an address that belongs to someone else stops startup. With neither and nobody able to manage the team, startup stops. | | `INVITABLE_ROLES` | The roles an invitation may give, comma separated, in the order an invite form offers them (default `USER`). Each must be a role a migration creates; `OWNER` is refused. See [Roles and permissions](https://jwcarman.github.io/roux/guides/roles/index.md). | | `ORG_TIME_ZONE`, `ORG_LOCALE` | The organization's IANA time zone (default `UTC`) and BCP 47 locale (default `en-US`): where its day starts and ends, and how dates, numbers and amounts are written. See [Dates and time](https://jwcarman.github.io/roux/guides/dates-and-time/index.md). | | `ORG_WEEK_START` | The first day of the organization's week (`Monday`); without it, where `ORG_LOCALE`'s region starts the week (Sunday for `en-US`). See [Dates and time](https://jwcarman.github.io/roux/guides/dates-and-time/#weeks). | | `ORG_CURRENCY` | The organization's one currency, an ISO 4217 code (`USD`), once the app has money. See [Money](https://jwcarman.github.io/roux/guides/money/index.md). | | `PASSKEYS`, `PASSKEY_RP_ID`, `PASSKEY_ORIGINS` | Passkeys follow `PUBLIC_URL`: its host is the relying party and its address is allowed. `PASSKEYS=false` turns them off; `PASSKEY_RP_ID` names a parent domain instead (`example.com` for `app.example.com`); `PASSKEY_ORIGINS` adds addresses, comma separated. | | `API_KEYS`, `API_KEY_PREFIX`, `API_KEY_HEADER`, `API_KEY_MAX_LIFETIME` | API keys: `false` to turn them off; what every key starts with (default `roux_`); the header (default `X-API-Key`); the longest a key may last (default a year). | | `OIDC_PROVIDERS_FILE` | A JSON list of OpenID Connect providers; `${NAME}` in it is an environment variable. Each provider's callback is `PUBLIC_URL/api/roux/auth/oidc/callback/{id}`. `OIDC_SUCCESS_URL`, `OIDC_FAILURE_URL`, `OIDC_LINK_URL` and `OIDC_SIGNUP_ROLE` tune where people land and the role a sign-up gets. | | `JWT_ISSUER`, `JWT_AUDIENCES`, `JWT_JWKS_URL` | Bearer tokens: the authorization server's issuer, the audiences a token must name one of, and the keys' address for a server without discovery. | | `FRONTEND_DIR` | Serve the front end from this directory (`frontend/dist`) instead of the one in the binary. The page is read once, at startup: restart the server after rebuilding the front end. | | `LOG_FORMAT` | `json` (the default) or `text`. | | `SHUTDOWN_DELAY` | How long to keep serving after readiness fails, with a unit: `5s`. | | `OTEL_EXPORTER_OTLP_ENDPOINT` and the other `OTEL_*` | Where traces, metrics and logs go (`compose.yaml`'s `otel` profile runs a collector and Grafana). | roux's tables and the app's are made by the migrations the modules declare (see [A feature's server side](https://jwcarman.github.io/roux/guides/features/#the-table)). There is nothing to run by hand: every start applies the migrations it has not applied, each in its own transaction, and a migration that has run is never edited. ### The binary The `frontend` package carries the built front end into the binary. `embed_web.go` embeds `frontend/dist` when built with the `embedweb` tag; `embed_none.go` is the same package without it, so `go build`, `go test` and `go vet` need no Node and no `dist` folder. `make build` builds the front end, then the binary with the tag; without one, the server serves `FRONTEND_DIR`, or else a stand-in page that says how to build the real one. The `Dockerfile` does the same in a container: the front end built on Node, the server built on Go, and the binary alone on distroless, running as a user who is not root. ## The web side ``` npm install @jwcarman/roux-web@0.4.0 npm install @chakra-ui/react @emotion/cache @emotion/react @fontsource-variable/inter @fontsource-variable/lora @fontsource-variable/nunito @tanstack/react-form @tanstack/react-query @tanstack/react-router @tanstack/react-table culori date-fns next-themes react react-icons zod ``` The Go and web versions must match: use the same version of `github.com/jwcarman/roux` and `@jwcarman/roux-web`. The second line is the peer dependencies; the app supplies them (`react` `^19.3.1`, `@chakra-ui/react` `^3.38.0`, `@emotion/react` and `@emotion/cache` `^11.14.0`, `@tanstack/react-query` `^5.107.1`, `@tanstack/react-form` `^1.33.5`, `@tanstack/react-router` `^1.170.46`, `@tanstack/react-table` `^8.21.3`, `date-fns` `^4.4.0`, `zod` `^4.6.7`, `culori` `^4.0.2`, `next-themes` `^0.4.6`, `react-icons` `^5.7.0`, and the three theme fonts `@fontsource-variable/inter`, `lora` and `nunito` `^5.3.0`). The browser test kit's peers (`vitest`, `msw`, `@testing-library/react`, `@testing-library/jest-dom`) are optional; see [Testing](https://jwcarman.github.io/roux/guides/testing/index.md). The package is ESM only. Import from a subpath; there is no root import: | Subpath | What it is for | Guide | | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `@jwcarman/roux-web/problem` | the `Problem` type and `problemOf` | [Errors](https://jwcarman.github.io/roux/guides/errors/index.md) | | `@jwcarman/roux-web/api` | the fetch client, `configureApi`, `createQueryClient`, `useServerAction` | [API client](https://jwcarman.github.io/roux/guides/api-client/index.md), [Queries and mutations](https://jwcarman.github.io/roux/guides/queries-and-mutations/index.md) | | `@jwcarman/roux-web/paging` | `PageDto`, `PageParams`, infinite lists and selects | [Tables and paging](https://jwcarman.github.io/roux/guides/tables-and-paging/index.md) | | `@jwcarman/roux-web/table` | `QueryTable` and its parts, search inputs | [Tables and paging](https://jwcarman.github.io/roux/guides/tables-and-paging/index.md) | | `@jwcarman/roux-web/feedback` | toasts (`notify`), confirmations, error and not-found pages | [Feedback](https://jwcarman.github.io/roux/guides/feedback/index.md) | | `@jwcarman/roux-web/form` | Zod rule helpers, `useSchemaForm`, fields, `FormDialog` | [Forms](https://jwcarman.github.io/roux/guides/forms/index.md) | | `@jwcarman/roux-web/dates` | ISO strings to and from date-fns Dates (`parseIsoDate`, `formatIsoDate`, `parseIsoTime`, `formatIsoTime`) | [Forms](https://jwcarman.github.io/roux/guides/forms/#dates-and-times) | | `@jwcarman/roux-web/organization` | the organization's zone, locale, currency and today | [Dates and time](https://jwcarman.github.io/roux/guides/dates-and-time/index.md) | | `@jwcarman/roux-web/money` | amounts: parsing, formatting, the money field | [Money](https://jwcarman.github.io/roux/guides/money/index.md) | | `@jwcarman/roux-web/activity` | a record's history | [The activity log](https://jwcarman.github.io/roux/guides/activity-log/index.md) | | `@jwcarman/roux-web/users` | the users API client, its queries and mutations | [Users](https://jwcarman.github.io/roux/guides/users/index.md) | | `@jwcarman/roux-web/theme` | `ThemeProvider`, colour mode, `useShellTheme`, `createThemeSystem`, `AppearanceSettings` | [The shell](https://jwcarman.github.io/roux/guides/shell/index.md) | | `@jwcarman/roux-web/session`, `auth`, `signin`, `navigation` | the session and route guards, sign-in pages, the sidebar frame | [The shell](https://jwcarman.github.io/roux/guides/shell/index.md) | | `@jwcarman/roux-web/testing` | the browser test kit | [Testing](https://jwcarman.github.io/roux/guides/testing/index.md) | ## Set up the app root `main.tsx` builds one query client with `createQueryClient()`, loads the organization's context and starts the day watch ([Dates and time](https://jwcarman.github.io/roux/guides/dates-and-time/index.md)) before rendering: without the context, `today()`, the formatters and money throw. ``` import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { createQueryClient } from "@jwcarman/roux-web/api"; import { loadOrganization, startDayWatch } from "@jwcarman/roux-web/organization"; import { App, createAppRouter } from "./App"; const queryClient = createQueryClient(); const router = createAppRouter(queryClient); await loadOrganization().catch((error: unknown) => { document.getElementById("root")!.textContent = `The app could not start: ${String(error)}`; throw error; }); startDayWatch(queryClient); createRoot(document.getElementById("root")!).render( , ); ``` `App.tsx` mounts, once each: `QueryClientProvider`, `ThemeProvider` (Chakra's provider with the app's theme, [The shell](https://jwcarman.github.io/roux/guides/shell/index.md)), `ColorModeProvider` (light and dark), `ConfirmProvider` (for `useConfirm`), `SessionProvider`, and `Toaster` (where `notify` toasts appear), then the router once the session has loaded. The route tests render the same `App`. - Use `createQueryClient()`, never `new QueryClient()`: mutations' `meta.refreshes` only work with roux's client, and `useSchemaForm` and `useServerAction` throw when a mutation names `meta.refreshes` on another client. `createQueryClient(): QueryClient` takes no options. - `Toaster` and `ConfirmProvider` render Chakra components, so they go inside `ThemeProvider`. `useConfirm` throws outside `ConfirmProvider`. - Pass the same `queryClient` to TanStack Router's context if route loaders prefetch. `SessionProvider` is roux's ([The shell](https://jwcarman.github.io/roux/guides/shell/#the-session-and-route-guards)): it loads the caller (`/api/roux/auth/me`) and their profile (`/api/roux/users/me`), empties the query cache when the identity changes, and reloads the caller when an API call reports the session lost. Components read it with `useSession()`, and route guards with `context.session.currentMe()`. An app that keeps a session of its own does the same two roux things with `useClearQueriesOnIdentityChange(identityId: string | null | undefined): void`, which empties the query cache when the identity goes away (`null`) or changes, so nobody sees rows cached for the previous user (`undefined`, still loading, changes nothing; call it inside `QueryClientProvider`), and `onSessionLost(listener)`, which runs `listener` whenever an `/api` call answers 401 and returns the function that stops it. ## Point the client at the API Nothing to do. The client's defaults are `baseUrl` `/api`, `csrfBootstrapPath` `/api/roux/auth/me` and `sessionPathPrefix` `/api/`, which match a roux server. Only if the API lives elsewhere on the same origin, call `configureApi` once in `main.tsx` before rendering: ``` import { configureApi } from "@jwcarman/roux-web/api"; configureApi({ baseUrl: "/v2", sessionPathPrefix: "/v2/" }); ``` Details in [API client](https://jwcarman.github.io/roux/guides/api-client/#change-where-the-api-lives). ## One origin roux requires the pages and the API to be served from one origin: the client calls relative paths (`/api/...`), the session is a cookie, and CSRF reads a cookie the page can see. Two deployments are supported: 1. **One binary (the default).** The server serves the built front end, and answers any page URL with the shell: a GET or HEAD that accepts `text/html`, has no file extension and is not under `/api/`, `/assets/` or `/.well-known/`. Adding a page is adding its route file; the server has no list of pages, and an unknown URL gets the shell, whose not-found route answers it. The shell is open to signed-out visitors (with `/assets/`, which roux caches for a year), so a reload or a deep link opens the app, which sends the visitor to sign in. A fetch for JSON, an API path (a missing one is still a `404` problem) and a request for a file never get the shell. `spa.Register` does this; `app.Run` calls it. 1. **Edge routing.** Static hosting or a CDN serves the pages, and a proxy on the same domain routes `/api` to the app. Separate origins (the pages on one host calling the API on another, with CORS and cross-site cookies) are not supported; `baseUrl` is a path, not a host. In development, Vite's dev server passes `/api` to the Go server: ``` // vite.config.ts const backend = "http://localhost:8080"; export default defineConfig({ server: { proxy: { "/api": backend, }, }, }); ``` Every sign-in endpoint is under `/api/roux/auth`, so this one entry covers the app's API and its sign-in. ## The shell roux serves `index.html` (package `spa`; no code in the app). Each response is the built page with four placeholders filled, `Cache-Control: no-store` (a stored copy's nonce would not match the next response's policy) and its own `Content-Security-Policy` header. The front-end build leaves the placeholders; the server does not start if one is missing: ``` __APP_NAME__ ``` and `html: { cspNonce: "__CSP_NONCE__" }` in `vite.config.ts`, which makes Vite write `nonce="__CSP_NONCE__"` on every script and style tag it emits. The name is HTML-escaped into the title; the theme and the organization's context ([Dates and time](https://jwcarman.github.io/roux/guides/dates-and-time/index.md)) are JSON with every `<` escaped, so nothing in it can end the element. One pass fills them, so an app named `__APP_THEME__` shows that name. **The policy:** `default-src 'self'`; `script-src` and `style-src` `'self'` plus the response's nonce; `img-src 'self' data:`; `font-src`, `connect-src`, `frame-src`, `media-src` and `form-action` `'self'`; `object-src 'none'`; `base-uri 'self'`; `frame-ancestors 'none'`. It never holds `'unsafe-inline'` or `'unsafe-eval'`. `spa.Config.CSP` adds sources to a directive, after the defaults; nothing loosens `default-src`, `object-src`, `base-uri` or `frame-ancestors`, and a source that would undo the policy (`*`, `'unsafe-inline'`, `'unsafe-eval'`, a bare scheme for scripts or styles) stops startup. `app.Run` registers the shell with the defaults alone, so an app that needs another source calls `app.Assemble` and `spa.Register` itself. **The theme** (`spa.Theme`: `appName`, `palette`, `brandColor`, `shape`, `headingFont`, `bodyFont`) is read for every page, so a theme the owner has just saved is in the next page. The users module keeps the owner's theme in roux's table `roux_theme`; until the owner chooses, it is `spa.StockTheme(appName)` (palette `gray`, brand colour `#3b82f6`, shape `medium`, fonts `standard`). ### The owner's theme The users module serves the theme: - `GET /api/roux/theme`, open to anyone, signed out too (the sign-in page needs its look): the whole theme and its `version`, 0 until the first save. - `PUT /api/roux/theme`, for whoever holds `theme.manage` (`theme.ThemeManage`, granted to `OWNER`): the theme with the `version` the owner read. A stale one is a `409`, a missing one a `400` on `version`. The values are the shell's own: palette `gray|red|orange|yellow|green|teal|blue|cyan|purple|pink|brand`, shape `square|slight|medium|round|extra-round`, fonts `standard|modern|friendly|classic`, a `#rrggbb` colour (kept lower-case) and a name of 1 to 60 characters (trimmed); a bad one is a `400` naming the field. The template's Appearance page edits it with roux-web's `AppearanceSettings`. `@jwcarman/roux-web` runs under this policy: `@jwcarman/roux-web/form` calls `z.config({ jitless: true })` when it loads, so Zod never probes `eval`. The package's `package.json` marks that file in `sideEffects` so bundlers keep it; do not override `sideEffects` for the package or tree-shake it away. ## Next - [A feature's server side](https://jwcarman.github.io/roux/guides/features/index.md): a feature's table, list, service, handlers and module. - [Errors](https://jwcarman.github.io/roux/guides/errors/index.md): refusing a request on the server and showing why in the browser. - [API client](https://jwcarman.github.io/roux/guides/api-client/index.md): one API module per resource. - [Queries and mutations](https://jwcarman.github.io/roux/guides/queries-and-mutations/index.md), [Forms](https://jwcarman.github.io/roux/guides/forms/index.md), [Tables and paging](https://jwcarman.github.io/roux/guides/tables-and-paging/index.md), [Feedback](https://jwcarman.github.io/roux/guides/feedback/index.md), [Testing](https://jwcarman.github.io/roux/guides/testing/index.md). # A feature's server side A feature is a Go package in `internal//`: its tables, made by its own SQL migrations; a service that reads and writes them with pgx; handlers that check the request and answer JSON; and a module that brings them into the app. There is no ORM and no code generator: the SQL is in the package, next to the Go that runs it. This guide builds the server side of one feature, from the table to the endpoint and its test. The browser side is [API client](https://jwcarman.github.io/roux/guides/api-client/index.md), [Queries and mutations](https://jwcarman.github.io/roux/guides/queries-and-mutations/index.md), [Forms](https://jwcarman.github.io/roux/guides/forms/index.md) and [Tables and paging](https://jwcarman.github.io/roux/guides/tables-and-paging/index.md). ## The files For a feature `labels` (the tags an item can carry) in the app `roux-app`: | File | What it is | | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | | `internal/labels/migrations/001_label.sql` | The table, and the grants of the feature's permissions | | `internal/labels/labels.go` | The permissions, the module, its migrations | | `internal/labels/input.go` | The body a write sends, and its rules | | `internal/labels/service.go` | What the API answers, and the operations: the SQL and the refusals | | `internal/labels/handlers.go` | The endpoints under `/api/labels`, each behind a permission | | `internal/labels/labels_test.go` | The endpoints over a real database, one test per refusal ([Testing](https://jwcarman.github.io/roux/guides/testing/index.md)) | | `cmd/server/modules.go` | One more module in the list, and its permissions in `permissions()` | ## The table ``` -- The team's labels. Names are unique ignoring case. create table label ( id uuid primary key default gen_random_uuid(), name text not null check (char_length(name) between 1 and 40), colour text not null, version bigint not null default 0, created_at timestamptz not null, created_by uuid not null references roux_identity (id), modified_at timestamptz not null, modified_by uuid not null references roux_identity (id) ); create unique index label_name_key on label (lower(name)); -- Every member may see the labels; only an owner may change them. insert into roux_role_permission (role_id, permission) select r.id, 'labels.read' from roux_role r where r.name in ('USER', 'OWNER') on conflict do nothing; insert into roux_role_permission (role_id, permission) select r.id, 'labels.manage' from roux_role r where r.name = 'OWNER' on conflict do nothing; ``` - **A migration is a `.sql` file in the feature's `migrations/` folder**, run in name order (`001_label.sql`, then `002_...`), each in its own transaction, once. roux records each file it ran with a checksum (in `schema_history`), and **an edited file that has run stops startup**, so never edit one that has run anywhere. A later change is a new file (`002_label_order.sql` with `alter table label add column ...`). - **`id uuid primary key default gen_random_uuid()`.** The database makes the id. - **`version bigint not null default 0`**, raised by every update, so an edit made from an old copy is refused ([Errors](https://jwcarman.github.io/roux/guides/errors/#refuse-a-stale-save)). - **Who and when:** `created_at`, `created_by`, `modified_at`, `modified_by`, set by the service from its clock and the caller. A reference to a person is `references roux_identity (id)` (a person who signs in) or `references roux_user (id)` (a member of the team; see [Users](https://jwcarman.github.io/roux/guides/users/index.md)). - **Text is `text` with a `check` on its length**, the same number as the Go constant (`MaxName`), so the database refuses what the API would. - **Unique ignoring case** is a unique index on `lower(...)`. The service checks first, so the person sees a message under the field; the index guards the race the check cannot see (two saves at once), which roux answers `409`. - **The feature's permissions are granted in its own migration**, after the roles exist. roux creates `OWNER`; the app's own roles (`USER`) are made by `cmd/server/migrations/`, which is why the module's migration runs `After` `app-roles` ([Roles and permissions](https://jwcarman.github.io/roux/guides/roles/index.md)). - Write the SQL for what PostgreSQL 17 does: `check` constraints, partial and expression indexes, views, `on delete cascade`. ## The module ``` // Package labels is the team's labels: the tags an item can carry. Everyone may see them; only // an owner may change them. package labels import ( "context" "embed" "time" "github.com/jwcarman/roux/app" "github.com/jwcarman/roux/pgdb" ) // The labels' permissions (migrations/001_label.sql grants them). const ( LabelsRead = "labels.read" LabelsManage = "labels.manage" ) // Permissions is every permission labels checks, for the app's list of them. var Permissions = []string{LabelsRead, LabelsManage} //go:embed migrations/*.sql var migrations embed.FS // Module is the labels feature: its table and its endpoints. type Module struct { // Clock is the time changes are stamped with; time.Now when nil. Clock func() time.Time } func (Module) Name() string { return "labels" } func (Module) Migrations() []pgdb.Migration { return []pgdb.Migration{{Name: "labels", FS: migrations, Dir: "migrations", After: []string{"roux-users", "app-roles"}}} } func (m Module) Mount(_ context.Context, k *app.Kit) error { now := m.Clock if now == nil { now = time.Now } Register(k, Service{Pool: k.Pool, Clock: now}) return nil } ``` - **The permissions are constants** in the package that checks them, and `Permissions` lists them for the app's list ([Roles and permissions](https://jwcarman.github.io/roux/guides/roles/index.md)). - **`//go:embed migrations/*.sql`** puts the SQL in the binary. `Migrations()` names them: `Name` is unique in the app (lowercase words joined by `-`), and `After` names the migrations that must run first. A name nobody declared is ignored. - **`Mount`** builds the service from the kit (`k.Pool`, `k.Organization` for the time zone) and registers the endpoints. A module with work to do after every module is mounted also has `Start(ctx, k) error` (making a first record, say). - **The clock is a field**, `time.Now` when nil, so a test sets the time. Then, in `cmd/server/modules.go`, the module joins the list and its permissions join the app's: ``` mods = append(mods, email, members, labels.Module{}) ``` ``` func permissions() []string { return slices.Concat(app.RouxPermissions(), labels.Permissions) } ``` The next `go test ./cmd/server` rewrites `frontend/src/permissions.gen.ts` with `LABELS_READ` and `LABELS_MANAGE` and fails once, so the change is committed; it also fails if `OWNER` lacks a permission or a migration grants one nobody declares. ## The input ``` package labels import ( "slices" "strings" "unicode/utf8" "github.com/jwcarman/roux/problem" ) // MaxName is the longest name, in characters (migrations/001_label.sql checks it too). const MaxName = 40 // Colours are the palettes a label may be shown in (Chakra UI's names). var Colours = []string{"gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"} // body is a write as it arrives; pointers tell "missing" from empty. type body struct { Name *string `json:"name"` Colour *string `json:"colour"` Version *int64 `json:"version"` } // Input is a valid write. type Input struct { Name, Colour string } // validate checks every field and answers every mistake at once; an edit must say which version // it was made from. func (b body) validate(edit bool) (Input, error) { var in Input var v []problem.Violation bad := func(field, message string) { v = append(v, problem.Violation{Field: field, Message: message}) } in.Name = strings.TrimSpace(deref(b.Name)) switch n := utf8.RuneCountInString(in.Name); { case n == 0: bad("name", problem.MustNotBeBlank) case n > MaxName: bad("name", problem.MustBeBetween(1, MaxName)) } in.Colour = deref(b.Colour) if !slices.Contains(Colours, in.Colour) { bad("colour", problem.MustBeOneOf(Colours...)) } if edit && b.Version == nil { bad("version", problem.MustNotBeEmpty) } if len(v) > 0 { return Input{}, problem.Validation(v...) } return in, nil } func deref(s *string) string { if s == nil { return "" } return *s } ``` - **The body is a struct of pointers**, so a missing member is told from an empty one. It is unexported: the handlers decode it, and only a valid `Input` reaches the service. - **`validate` checks every field and returns every mistake at once**, as `problem.Validation`, a `400` whose `errors` name each field. The form shows each under its field ([Forms](https://jwcarman.github.io/roux/guides/forms/#useschemaform)). - **The words are roux's** (`problem.MustNotBeBlank`, `problem.MustBeBetween(1, MaxName)`, `problem.MustBeOneOf(...)`), the same the browser's rules show, so the person reads one vocabulary. A message of the feature's own is a constant (`NameTaken`), so a test can name it. - **Trim text before checking it**, and count characters with `utf8.RuneCountInString`, never `len` (bytes). - An edit must carry the `version` it was made from; a create carries none. ## The service ``` package labels import ( "context" "errors" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/jwcarman/roux/authn" "github.com/jwcarman/roux/problem" ) // NameTaken is what a clash of names says, under the name field. const NameTaken = "Another label has this name" // Label is a label as the API answers it. type Label struct { ID uuid.UUID `json:"id" db:"id"` Name string `json:"name" db:"name"` Colour string `json:"colour" db:"colour"` Version int64 `json:"version" db:"version"` } // Service is the labels' operations. type Service struct { Pool *pgxpool.Pool Clock func() time.Time } const columns = `id, name, colour, version` // List is every label, by name. func (s Service) List(ctx context.Context) ([]Label, error) { rows, err := s.Pool.Query(ctx, `select `+columns+` from label order by lower(name), id`) if err != nil { return nil, err } return pgx.CollectRows(rows, pgx.RowToStructByName[Label]) } // Get is one label. func (s Service) Get(ctx context.Context, id uuid.UUID) (Label, error) { rows, err := s.Pool.Query(ctx, `select `+columns+` from label where id = $1`, id) if err != nil { return Label{}, err } r, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Label]) if errors.Is(err, pgx.ErrNoRows) { return Label{}, notFound() } return r, err } // Create adds a label. func (s Service) Create(ctx context.Context, caller *authn.Principal, in Input) (Label, error) { var out Label err := pgx.BeginFunc(ctx, s.Pool, func(tx pgx.Tx) error { if err := uniqueName(ctx, tx, in.Name, uuid.Nil); err != nil { return err } rows, err := tx.Query(ctx, ` insert into label (name, colour, created_at, created_by, modified_at, modified_by) values ($1, $2, $3, $4, $3, $4) returning `+columns, in.Name, in.Colour, s.Clock(), caller.IdentityID) if err != nil { return err } out, err = pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Label]) return err }) return out, err } // Update changes a label, from the version the caller last saw. func (s Service) Update(ctx context.Context, caller *authn.Principal, id uuid.UUID, version int64, in Input) (Label, error) { var out Label err := pgx.BeginFunc(ctx, s.Pool, func(tx pgx.Tx) error { var current int64 err := tx.QueryRow(ctx, `select version from label where id = $1 for update`, id).Scan(¤t) if errors.Is(err, pgx.ErrNoRows) { return notFound() } if err != nil { return err } // First, before anything changes: a stale version is a 409. if current != version { return problem.StaleVersion() } if err := uniqueName(ctx, tx, in.Name, id); err != nil { return err } rows, err := tx.Query(ctx, ` update label set name = $2, colour = $3, version = version + 1, modified_at = $4, modified_by = $5 where id = $1 returning `+columns, id, in.Name, in.Colour, s.Clock(), caller.IdentityID) if err != nil { return err } out, err = pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Label]) return err }) return out, err } // Delete removes a label. func (s Service) Delete(ctx context.Context, id uuid.UUID) error { tag, err := s.Pool.Exec(ctx, `delete from label where id = $1`, id) if err != nil { return err } if tag.RowsAffected() == 0 { return notFound() } return nil } func notFound() error { return problem.NotFound("This label no longer exists") } // uniqueName refuses a name another label has, ignoring case, under the name field. func uniqueName(ctx context.Context, tx pgx.Tx, name string, self uuid.UUID) error { var taken bool if err := tx.QueryRow(ctx, `select exists (select 1 from label where lower(name) = lower($1) and id <> $2)`, name, self).Scan(&taken); err != nil { return err } if taken { return problem.InvalidField("name", NameTaken) } return nil } ``` - **What the API answers is a struct with JSON tags** (`Label`), never a row type shared with another feature. It carries `version`, so the browser can send it back with an edit. - **SQL text is a constant; values are always arguments** (`$1`, `$2`). Never build SQL from what a request sent. - **A write is one transaction**: `pgx.BeginFunc` commits when the function returns nil and rolls back otherwise. `select ... for update` holds the row while the edit is checked. - **An edit checks the version first**, before anything changes, and refuses a stale one with `problem.StaleVersion()` (`409`). The update raises `version`. - **A missing row is `problem.NotFound("")`** (`404`); a clash on what the person typed is `problem.InvalidField(field, message)` (`400` on that field). Every refusal is a `*problem.Problem` returned as the error ([Errors](https://jwcarman.github.io/roux/guides/errors/index.md)); anything else is a `500` that says nothing about why and logs the cause. - **Time comes from the service's clock**, today from the organization's zone ([Dates and time](https://jwcarman.github.io/roux/guides/dates-and-time/index.md)). A change worth a history is recorded with `activity.Append` in the same transaction ([The activity log](https://jwcarman.github.io/roux/guides/activity-log/index.md)). - `pgx.RowToStructByName[Label]` fills each field from the column its `db` tag names, so the order of a query's columns does not matter; the `columns` constant lists every one, and a column missing from either side fails the first query, which the tests run. ## The handlers ``` package labels import ( "net/http" "github.com/google/uuid" "github.com/jwcarman/roux/api" "github.com/jwcarman/roux/app" "github.com/jwcarman/roux/authn" ) // BasePath is where the labels' endpoints live. const BasePath = "/api/labels" // Register serves the labels' endpoints. Each is a kit route: the CSRF token, a sign-in and the // permission are checked before the handler runs. // // GET /api/labels every label, by name labels.read // POST /api/labels add a label labels.manage // GET /api/labels/{id} one label labels.read // PUT /api/labels/{id} change it, from its version (409) labels.manage // DELETE /api/labels/{id} delete it labels.manage func Register(k *app.Kit, svc Service) { k.Handle("GET "+BasePath, LabelsRead, func(w http.ResponseWriter, r *http.Request) error { out, err := svc.List(r.Context()) if err != nil { return err } return api.JSON(w, http.StatusOK, out) }) k.Handle("POST "+BasePath, LabelsManage, func(w http.ResponseWriter, r *http.Request) error { in, _, err := decode(r, false) if err != nil { return err } out, err := svc.Create(r.Context(), authn.PrincipalFrom(r.Context()), in) if err != nil { return err } return api.JSON(w, http.StatusCreated, out) }) k.Handle("GET "+BasePath+"/{id}", LabelsRead, func(w http.ResponseWriter, r *http.Request) error { id, err := labelID(r) if err != nil { return err } out, err := svc.Get(r.Context(), id) if err != nil { return err } return api.JSON(w, http.StatusOK, out) }) k.Handle("PUT "+BasePath+"/{id}", LabelsManage, func(w http.ResponseWriter, r *http.Request) error { id, err := labelID(r) if err != nil { return err } in, version, err := decode(r, true) if err != nil { return err } out, err := svc.Update(r.Context(), authn.PrincipalFrom(r.Context()), id, version, in) if err != nil { return err } return api.JSON(w, http.StatusOK, out) }) k.Handle("DELETE "+BasePath+"/{id}", LabelsManage, func(w http.ResponseWriter, r *http.Request) error { id, err := labelID(r) if err != nil { return err } if err := svc.Delete(r.Context(), id); err != nil { return err } w.WriteHeader(http.StatusNoContent) return nil }) } // decode reads and checks a write: a body that is not JSON, or has a member the API does not // know, is a 400; so is every mistake validate finds. func decode(r *http.Request, edit bool) (Input, int64, error) { var b body if err := api.Decode(r, &b); err != nil { return Input{}, 0, err } in, err := b.validate(edit) if err != nil { return Input{}, 0, err } var version int64 if b.Version != nil { version = *b.Version } return in, version, nil } // labelID is the {id} in the path; one that is not a UUID names no label. func labelID(r *http.Request) (uuid.UUID, error) { id, err := uuid.Parse(r.PathValue("id")) if err != nil { return uuid.Nil, notFound() } return id, nil } ``` - **Every route is `k.Handle(pattern, permission, fn)`**: the CSRF token, a sign-in and the permission are checked before `fn` runs, so a signed-out caller gets `401` and one without the permission `403`. A route for anyone signed in is `k.HandleSignedIn`, and one for anybody (signed out too) `k.HandlePublic`; an empty permission panics at startup, and one no role holds (a misspelling) stops it, naming the route. Never mount an app route with `k.Mux.Handle`: it would be open, and startup warns that it is. - **The pattern is Go's** (`net/http`): a method, a space, a path, `{id}` read with `r.PathValue("id")`. - **A handler returns an error** and writes nothing when it does: roux answers a `*problem.Problem` as itself and anything else as a `500`. - **`api.Decode`** reads one JSON object, refusing a member the API does not know, trailing data or a body that is not JSON, with a `400`. **`api.JSON(w, status, v)`** answers. - A create answers `201` with what it made, an edit `200`, a delete `204`. An `{id}` that is not a UUID names nothing: `404`. - **The handlers say nothing about the database**, and the service nothing about HTTP; the caller (`authn.PrincipalFrom(r.Context())`) is passed in. - A long list answers a page instead ([Tables and paging](https://jwcarman.github.io/roux/guides/tables-and-paging/#the-server)). ## The test ``` package labels_test import ( "testing" "github.com/google/uuid" "github.com/jwcarman/roux/authn/authntest" "github.com/jwcarman/roux/rouxtest" "roux-app/internal/labels" ) // setup is the labels API over a fresh schema, with Olive (OWNER) and Ada (USER) signed in. func setup(t *testing.T) (owner, user *authntest.Browser) { t.Helper() a := rouxtest.New(t, "labels") a.Role("USER") // the app's own role, before labels grants to it a.Migrate(labels.Module{}.Migrations()...) labels.Register(a.Kit(), labels.Service{Pool: a.Pool, Clock: a.Clock.Now}) a.Serve() return a.SignedIn(a.Person("Olive Owner", "OWNER")), a.SignedIn(a.Person("Ada Lovelace", "USER")) } func TestAnOwnerAddsALabelThatEveryoneSees(t *testing.T) { owner, user := setup(t) added := owner.Post("/api/labels", map[string]any{"name": " Urgent ", "colour": "yellow"}). Want(t, 201, "add").JSON(t) if added["name"] != "Urgent" || added["version"] != float64(0) { t.Fatalf("added %v", added) } var list []labels.Label user.Get("/api/labels").Want(t, 200, "list").Decode(t, &list) if len(list) != 1 || list[0].Name != "Urgent" { t.Fatalf("list %v", list) } } func TestOnlyAnOwnerChangesLabels(t *testing.T) { _, user := setup(t) user.Post("/api/labels", map[string]any{"name": "Waiting", "colour": "yellow"}).Want(t, 403, "a USER") } func TestALabelNeedsANameAndAColourItKnows(t *testing.T) { owner, _ := setup(t) got := owner.Post("/api/labels", map[string]any{"name": " ", "colour": "mauve"}).Want(t, 400, "bad").JSON(t) errs, _ := got["errors"].([]any) if len(errs) != 2 { t.Fatalf("errors %v", got) } } func TestTwoLabelsMayNotShareANameIgnoringCase(t *testing.T) { owner, _ := setup(t) owner.Post("/api/labels", map[string]any{"name": "Waiting", "colour": "yellow"}).Want(t, 201, "first") got := owner.Post("/api/labels", map[string]any{"name": "WAITING", "colour": "green"}).Want(t, 400, "second").JSON(t) if errs := got["errors"].([]any); errs[0].(map[string]any)["message"] != labels.NameTaken { t.Fatalf("got %v", got) } } func TestAnEditFromAnOldVersionIsRefused(t *testing.T) { owner, _ := setup(t) id := owner.Post("/api/labels", map[string]any{"name": "Waiting", "colour": "yellow"}).Want(t, 201, "add").JSON(t)["id"] path := "/api/labels/" + id.(string) owner.Put(path, map[string]any{"name": "Blocked", "colour": "yellow", "version": 0}).Want(t, 200, "edit") owner.Put(path, map[string]any{"name": "On hold", "colour": "yellow", "version": 0}).Want(t, 409, "stale") owner.Put(path, map[string]any{"name": "On hold", "colour": "yellow"}).Want(t, 400, "no version") owner.Delete(path).Want(t, 204, "delete") owner.Get(path).Want(t, 404, "gone") owner.Get("/api/labels/"+uuid.NewString()).Want(t, 404, "never was") } ``` `rouxtest.New` is the feature over a fresh schema with roux's tables, `Person` a member of the team in a role, and `SignedIn` a browser signed in as them, with the CSRF token. [Testing](https://jwcarman.github.io/roux/guides/testing/index.md) says more. ## Check it - `make check` runs gofmt, `go vet`, golangci-lint and every test. The database tests start PostgreSQL in Docker, or use `TEST_DATABASE_URL`. - A migration that fails stops every test that runs it, naming the file and PostgreSQL's error. - `go test ./cmd/server` checks the permissions: the front end's list, and every grant. ## Don't - Don't build SQL from what a request sent; pass values as arguments. - Don't edit a migration that has run; add one. - Don't mount an app route with `Mux.Handle`; use `k.Handle`, `k.HandleSignedIn` or `k.HandlePublic`. - Don't answer a refusal by writing to the response; return a `*problem.Problem`. - Don't compare versions after changing anything; check first. - Don't catch a unique violation to turn the race into a field error: no test can make two saves race, and roux already answers it `409`. # The server and the browser # Errors Every error a roux API answers is an [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) Problem Detail with a message written for the person using the app. On the server, a handler returns a `*problem.Problem` (package `github.com/jwcarman/roux/problem`) as its error, and roux writes it; anything else it returns is a `500` that tells the client nothing and logs the cause. In the browser, `@jwcarman/roux-web/problem` reads the problem, `/api` rejects with it inside an `ApiError`, and the form and button hooks show it: field errors under their fields, anything else as a toast. ## The problem shape The wire format, from roux's fixtures (`contracts/problem-*.json`), which the server's and the browser's tests both read: ``` { "title": "Bad Request", "status": 400, "detail": "The request has invalid fields", "errors": [{ "field": "title", "message": "Must not be blank" }], "instance": "/api/contract/invalid-fields" } ``` - `title`: the status's reason phrase (`Not Found`, `Conflict`, ...). Never app text. - `status`: the HTTP status. - `detail`: the message for the person. Omitted when empty. - `instance`: the request path, filled in when the problem is written. - `errors`: on a 400 about fields only. Each entry is a `problem.Violation` (`field`, `message`); `field` is the name the client sent (`name`, `assigneeIds`). Sorted by field, then message. - `errorId`: on a 500 only. The same id is logged at ERROR with the cause, so a person's report can be matched to the log. - `traceId`: the request's trace, when telemetry is on. - `code`: a stable machine-readable code, on sign-in's own problems. - `type`: not sent (it is `about:blank`); the browser's `problemOf` fills it in. The content type is `application/problem+json`. ## Refuse a request Return the problem as the handler's (or the service's) error. A `*problem.Problem` is an `error`, and it passes through `fmt.Errorf("...: %w", p)` wrapping unchanged. | Constructor | Status | Use it for | | -------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `problem.NotFound(detail)` | 404 | A record that does not exist, or that the caller may not know exists. | | `problem.InvalidField(field, message)` | 400 | One field the client sent is wrong, and only the server can tell (a name another record has). | | `problem.Validation(violations...)` | 400 | Every field's mistakes at once: what `validate` returns ([A feature's server side](https://jwcarman.github.io/roux/guides/features/#the-input)). | | `problem.BadRequest(detail)` | 400 | A rule about the request as a whole, with no one field to blame. | | `problem.Conflict(detail)` | 409 | A clash with what the server holds, with no one field to blame. | | `problem.StaleVersion()` | 409 | An edit made from a version that is no longer current. | | `problem.Forbidden()` | 403 | The caller holds the route's permission but may not touch this record (not its author). | | `problem.Unauthorized()` | 401 | Never needed in a `k.Handle` route: the guard answers it. | | `problem.New(status, detail)` | any | Anything else. | ### Return 404 for a missing record ``` err := tx.QueryRow(ctx, `select version from label where id = $1 for update`, id).Scan(¤t) if errors.Is(err, pgx.ErrNoRows) { return problem.NotFound("This label no longer exists") } ``` Answer: `404`, `detail` the message (`contracts/problem-not-found.json`). An `{id}` in the path that is not a UUID names nothing: answer it `404` too. A `pgx.ErrNoRows` a handler lets through is answered `404` as well, with a generic detail, but say what is missing where you can. ### Refuse a request that breaks a rule ``` if current.Done && in.Day != current.Day { return problem.BadRequest("A done item can't be moved; reopen it first") } ``` Answer: `400`, `detail` the message, no `errors` (`contracts/problem-invariant.json`). Build a message with `fmt.Sprintf`; it is shown as it stands. ### Refuse one field the client sent The input's `validate` refuses what can be checked from the body alone ([A feature's server side](https://jwcarman.github.io/roux/guides/features/#the-input)). When a rule about one field needs the database (or the clock), return `problem.InvalidField` naming the field as the client sent it: ``` var taken bool if err := tx.QueryRow(ctx, `select exists (select 1 from label where lower(name) = lower($1) and id <> $2)`, name, self).Scan(&taken); err != nil { return err } if taken { return problem.InvalidField("name", NameTaken) } ``` Answer: `400`, `detail` `The request has invalid fields`, and `errors` with one entry for that field. A form built with `useSchemaForm` shows the message under the field. A uniqueness clash on something the person typed (an email, a name) is an invalid field, not a `409`: it lands where they can fix it. The words for the common rules are constants and functions in `problem`, the same the browser's rules show (`contracts/messages.json` is the list both sides test against): | Go | Message | | ---------------------------------------------- | ------------------------------------------------------ | | `problem.MustNotBeBlank` | `Must not be blank` | | `problem.MustNotBeEmpty` | `Must not be empty` | | `problem.InvalidValue` | `Invalid value` | | `problem.ValidEmail` | `Must be a valid email address` | | `problem.ValidURL` | `Must be a valid web address` | | `problem.BadFormat` | `Is not in the expected format` | | `problem.MustBeMoreThan0` | `Must be more than 0` | | `problem.MustNotBeNegative` | `Must not be negative` | | `problem.MustBeInThePast`, `MustBeInTheFuture` | `Must be in the past`, `Must be in the future` | | `problem.MustNotBeInFuture`, `MustNotBeInPast` | `Must not be in the future`, `Must not be in the past` | | `problem.MustBeBetween(1, 80)` | `Must be between 1 and 80 characters` | | `problem.MustBeAtLeast(5)`, `MustBeAtMost(5)` | `Must be at least 5`, `Must be at most 5` | | `problem.MustBeAfter("starts at")` | `Must be after starts at` | | `problem.MustBeOneOf("A", "B")` | `Must be one of A, B` | ### Report a clash with the server's state (409) ``` if booked { return problem.Conflict(fmt.Sprintf("%s already has an item at %s", person.Name, at)) } ``` Answer: `409`, `detail` the message (`contracts/problem-conflict.json`). ### Refuse a stale save A record carries a `version`, raised by every update, and an edit sends back the version it was made from. Check it first, before changing anything, with the row locked: ``` var current int64 err := tx.QueryRow(ctx, `select version from label where id = $1 for update`, id).Scan(¤t) // ... a missing row is a 404 ... if current != version { return problem.StaleVersion() } ``` Then `update ... set version = version + 1`. An edit with no `version` is a `400` on `version` (`Must not be empty`), from the input's `validate`. Answer: `409`, `detail` `This record changed since you loaded it`. `useSchemaForm` handles this 409 specially; see [Forms](https://jwcarman.github.io/roux/guides/forms/index.md). ### Refuse because of what another feature holds "A label items carry may not be removed" belongs to the feature that refers to labels, and `labels` must not import `items`. Invert it: the owning feature takes checks, and `modules.go` passes the referring feature's: ``` // in labels: a reason a label may not be removed, from a feature that refers to labels type RemovalCheck func(ctx context.Context, tx pgx.Tx, label Label) error type Module struct { Clock func() time.Time RemovalChecks []RemovalCheck } ``` ``` // in items func LabelInUse(ctx context.Context, tx pgx.Tx, label labels.Label) error { var held bool if err := tx.QueryRow(ctx, `select exists (select 1 from item_label where label_id = $1)`, label.ID).Scan(&held); err != nil { return err } if held { return problem.Conflict(fmt.Sprintf("Items carry %s: take it off them first", label.Name)) } return nil } ``` ``` // in cmd/server/modules.go labels.Module{RemovalChecks: []labels.RemovalCheck{items.LabelInUse}} ``` The service runs each check in the delete's transaction. Keep the foreign key as the last line of defence (a refusal there is the generic `409`), and the check as the one that says why. ### Treat "already done" as success Some requests mean "make it so", and a repeat is not an error: assigning someone to an item twice (a double tap, two devices), adding someone to a group they are in. Let the unique constraint decide, and ask PostgreSQL not to fail: ``` tag, err := tx.Exec(ctx, ` insert into item_assignee (item_id, user_id) values ($1, $2) on conflict (item_id, user_id) do nothing`, itemID, userID) if err != nil { return err } added := tag.RowsAffected() == 1 // false: it was already there, which is success too ``` Never insert and then look for the unique violation inside the same transaction: the failed statement aborts the transaction, and everything after it fails. ## What else is answered for you | Cause | Status | `detail` | | ------------------------------------------------------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | A body that is not one JSON object, or has trailing data (`api.Decode`) | 400 | `Request body is not valid JSON.`, or what is wrong with it | | A member of the wrong type (`"name": 3`) | 400 | `Request body is not valid JSON: name has the wrong type.` | | A member the endpoint does not take (`api.Decode`; `api.DecodeLenient` ignores it) | 400 | `Request body has a member this endpoint does not take: colour.` | | A body over 1 MB | 413 | `Request body is too large.` | | A bad `pageIndex`, `pageSize`, `sortBy` or `sortDirection` (`api.PageRequest`) | 400 | `The request has invalid fields`, with `errors` on the parameter (`Must be one of DAY, TITLE`) | | A signed-out caller on a `k.Handle` or `k.HandleSignedIn` route | 401 | `Sign in to continue` | | A caller without the route's permission | 403 | `You do not have permission` | | An unsafe request (POST, PUT, PATCH, DELETE) without the CSRF token | 403 | `Invalid CSRF token`, with `code` `invalid-csrf-token` (roux-web's client sends the token for you) | | A path under `/api/` that no route matches | 404 | `No resource exists at this path.` | | A route matched with the wrong method | 405 | `Method PATCH is not allowed for this resource.` | | `pgx.ErrNoRows` returned as it is | 404 | `The requested resource does not exist.` | | A unique or foreign-key violation returned as it is | 409 | `A resource with these values already exists.`, `The operation conflicts with a related resource.` (never the database's text) | | Anything under `/api/roux/auth/` | its status | sign-in's own problems, with `type` `urn:roux:error:` and `code` | | A panic | 500 | `Something went wrong`, with `errorId` | | The request's own cancellation, after the client went away (a page left mid-request) | 499 (`api.StatusClientClosedRequest`) | nothing anyone reads; logged at DEBUG, not ERROR, and no failed trace | | Anything else | 500 | `Something went wrong`, with `errorId` (`contracts/problem-server-error.json`) | An error type of the app's own can say how it is answered by having a method `Problem() *problem.Problem` (`api.ProblemSource`); `api.MapType(mux, fn)` and `mux.MapError(err, fn)` map an error type or a sentinel the app does not own. Most apps need neither: return a problem. A feature that must tell one constraint from another inspects the error after its transaction ended: `pgdb.IsViolation(err, pgdb.CodeUniqueViolation)` (or `pgdb.CodeForeignKeyViolation`). A transaction opened by hand with `pool.Begin` is closed with `defer pgdb.Rollback(ctx, tx)`, which rolls back unless it committed; `pgx.BeginFunc` needs neither. ## Don't - Don't write a refusal to the response yourself (`w.WriteHeader(400)`): the answer would not be a problem. Return one. - Don't put Go type names, SQL or a wrapped error's text in a message: messages are shown to people as they stand. - Don't answer a refusal with `500`: a mistake the person can fix is a `400`, `404` or `409`. - Don't catch a database error to reword it unless you can name the field; the generic `409` is answered for you. ## In the browser: reading a problem From `@jwcarman/roux-web/problem` (`Problem`, and `FieldProblem` for each entry of `errors`): ``` interface FieldProblem { field: string; message: string; } interface Problem { type: string; // "about:blank" when the server sent none title: string; status: number; detail?: string; instance?: string; errors?: FieldProblem[]; errorId?: string; // on a 500 only } function problemOf(response: Response): Promise; ``` `problemOf` never throws. A response that is not `application/problem+json`, or whose body cannot be read, gives `{ type: "about:blank", title: response.statusText, status: response.status }`. `errors` is kept only when it is a non-empty array of well-formed entries. You rarely call `problemOf` yourself: `getJson` and `sendJson` (from `/api`) reject with an `ApiError` that already carries it. ``` class ApiError extends Error { constructor(status: number, problem?: Problem); // problem defaults to a blank one with that status readonly status: number; readonly problem: Problem; // message: problem.detail, or "Request failed with status " } ``` Branch on `error instanceof ApiError` and `error.status`; show `error.problem.detail`. ## In the browser: what the user sees A form saved with `useSchemaForm` (from `/form`) and a button that runs `useServerAction` (from `/api`) show refusals for you. `failure` is the toast title you pass (default `Could not save`). | Answer | `useSchemaForm` | `useServerAction` | | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | 400 with `errors` | each field's first message under the field; messages for fields the form does not have are toasted together under `failure` | toast: `failure`, then `detail` (`The request has invalid fields`); the field messages are not shown | | 400 without `errors` (`problem.BadRequest`) | toast: `failure`, then `detail` | same | | 401 | nothing: the app's `onSessionLost` listener sends the user to sign in | nothing | | 403, 404 | toast: `failure`, then `detail` | same | | 409 | toast: `failure`, then `detail`; the form starts over from the refreshed record when it changed | toast: `failure`, then `detail` | | 500 | toast: `failure`, then `Something went wrong` and `Reference: ` | same | | Network failure (no answer) | toast: `failure` alone | same | Known gap: a button whose request is refused with field `errors` shows only the generic detail. Keep field rules on forms; a button's request should fail with `problem.BadRequest` or `problem.Conflict`, whose message is shown. To show a problem yourself (outside those hooks), use `notify.problem(problem, title)` from `/feedback`, which renders the same toast. To place a problem's field errors yourself, `fieldErrorsOf(problem)` (from `/form`) gives `{ [field]: firstMessage }`. Both are covered in [Feedback](https://jwcarman.github.io/roux/guides/feedback/index.md) and [Forms](https://jwcarman.github.io/roux/guides/forms/index.md). A query (`useQuery`, `useSuspenseQuery`) that fails rejects with the same `ApiError`. roux's query client does not retry a 4xx. What the page shows is the app's choice; the template's root route renders `ErrorPage` from `/feedback` (see [Queries and mutations](https://jwcarman.github.io/roux/guides/queries-and-mutations/index.md)). # Roles and permissions A roux app checks **permissions**, never roles: `k.Handle("GET /api/labels", labels.LabelsRead, ...)` on an endpoint, a `permission` on a navigation item. A **role** is a named set of permissions that people hold. Permissions are constants in Go; roles and what they grant are **data**, changed by migrations like any schema. ## What roux gives every app - **`OWNER`** (`authz.RoleOwner`). roux's migrations create it, and each of roux's modules grants `OWNER` its own permissions in its own migration: `theme.manage` (`theme.ThemeManage`), `users.read`, `users.invite`, `users.manage` and `users.owners` (`users.UsersRead` and the others, [Users](https://jwcarman.github.io/roux/guides/users/index.md)), and `roux.admin` (`authz.Admin`, below). `app.RouxPermissions()` lists them. A roux upgrade that adds a permission brings its grant with it. The app grants `OWNER` its own permissions. - **The first owner**, from `OWNER_EMAIL` and `OWNER_NAME` (both or neither). While no active identity holds `OWNER`, the users module creates one at startup. Once an active owner exists, the settings change nothing. If none is active (someone changed the database by hand), the next start makes one again; when another identity already holds the address, startup fails. - **Invitable roles**, from `INVITABLE_ROLES` (comma separated, default `USER`; `OWNER` is refused). An invitation or a role change that gives another role is refused, `400` on `role`. The list is served at `GET /api/roux/roles/invitable` for the invite form, in the order given. List only roles a migration creates. - **The last administrator stays.** See [Keep someone who can manage people](#keep-someone-who-can-manage-people). ## The app's permissions Constants in the package that checks them, and a list of them: ``` // The labels' permissions (migrations/001_label.sql grants them). const ( LabelsRead = "labels.read" LabelsManage = "labels.manage" ) // Permissions is every permission labels checks, for the app's list of them. var Permissions = []string{LabelsRead, LabelsManage} ``` A permission is lowercase words joined by dots: the feature, then what it allows (`labels.read`, `items.delete.any`). Reading and changing are usually two (`labels.read`, `labels.manage`); "only the owner" is a permission granted to `OWNER` alone. `cmd/server/modules.go` lists every permission the app checks, roux's first: ``` func permissions() []string { return slices.Concat(app.RouxPermissions(), labels.Permissions) } ``` ### Parts of a response only some callers see `k.Handle` guards a whole endpoint. When the endpoint is open to more people than one of its parts (a list's column, a delete button's `canDelete`), check the caller inside: ``` caller := authn.PrincipalFrom(r.Context()) if !caller.Has(ItemsDeleteAny) && caller.IdentityID != author { return problem.Forbidden() } ``` `Principal.Has(permission)` answers from the permissions the caller held when the request began; `Principal.IdentityID` is who they are. See [Tables and paging](https://jwcarman.github.io/roux/guides/tables-and-paging/#a-column-only-some-people-see). ## The app's roles The app's own roles are made by its own migration, `cmd/server/migrations/`, by name, inserting only what is missing: ``` -- This application's own roles and what each grants. OWNER is roux's: it holds every -- permission (each module's migration grants it its own). USER is anyone invited. insert into roux_role (id, name) values (gen_random_uuid(), 'USER') on conflict (name) do nothing; insert into roux_role_permission (role_id, permission) select r.id, 'users.read' from roux_role r where r.name = 'USER' on conflict do nothing; ``` The template's `appRoles` module (`modules.go`) runs it, named `app-roles`, after `roux-users`. Each feature then grants its own permissions in its own migration, after `app-roles`: ``` insert into roux_role_permission (role_id, permission) select r.id, p.permission from roux_role r cross join (values ('labels.read')) as p(permission) where r.name in ('USER', 'OWNER') on conflict do nothing; insert into roux_role_permission (role_id, permission) select r.id, 'labels.manage' from roux_role r where r.name = 'OWNER' on conflict do nothing; ``` Never change a migration that has run; add a new one. - **Adding a permission** is a constant, an entry in the feature's `Permissions`, and a migration granting it to `OWNER` (and to any other role that should hold it). - **Adding a role** is a migration in `cmd/server/migrations/` (and, if people may be invited to it, an entry in `INVITABLE_ROLES`). - **Renaming a role** is a migration: `update roux_role set name = 'LEAD' where name = 'ORGANIZER';`. Holders keep it: assignments refer to the role's id. - **Taking a permission away** is a migration deleting the grant from `roux_role_permission`. No startup code creates or syncs roles. A sync breaks a rolling deploy: an old instance that restarts meets a role the new version added, or undoes its grants. ## The permissions tests `cmd/server/permissions_test.go` holds two tests, over `permissions()`: ``` // The front end's list of permissions is the server's: a permission added here is rewritten into // frontend/src/permissions.gen.ts, and this test fails once so the change is committed. func TestTheFrontEndListsEveryPermission(t *testing.T) { rouxtest.PermissionsFile(t, "../../frontend/src/permissions.gen.ts", permissions()...) } // After every migration the app runs, OWNER holds every permission and no role grants one that // is not declared: a forgotten grant or a typo in a migration fails here, naming it. func TestEveryGrantIsADeclaredPermissionAndOwnerHoldsThemAll(t *testing.T) { t.Setenv("CODE_SECRET", strings.Repeat("s", 40)) t.Setenv("PUBLIC_URL", "http://localhost:8080") a := rouxtest.New(t, "app_grants") mods, err := modules(a.Kit()) if err != nil { t.Fatal(err) } var migrations []pgdb.Migration for _, m := range mods { if mg, ok := m.(app.Migrator); ok { migrations = append(migrations, mg.Migrations()...) } } a.Migrate(migrations...) rouxtest.CheckGrants(t, a.Pool, permissions()...) } ``` - `rouxtest.PermissionsFile` writes `permissions.gen.ts` (a constant per permission, named from it: `labels.read` is `LABELS_READ`; and `PERMISSIONS`, the array `defineNav` takes) and fails when the committed file was stale. After adding a permission, run `go test ./cmd/server`: the first run rewrites the file and fails, the second passes; commit the file. Never edit it by hand. - `rouxtest.CheckGrants` fails, naming each one, when `OWNER` lacks a permission, or any role grants one nobody declares (a typo in a migration). It needs the database. - A route mounted with `k.Handle` that needs a permission no role holds stops startup, naming the route and the permission: a misspelling there would otherwise answer `403` to everyone. ## Keep someone who can manage people `roux.admin` (`authz.Admin`) makes its holder an administrator, and roux refuses a change that would leave no active identity holding it. In a roux app only `OWNER` holds it, so the rule keeps an active owner. roux's own endpoints (deactivating someone, changing a role) apply it; a change it refuses is a `409` with code `last-admin` and the detail "The team needs someone active who can manage people" (`authz.LastAdminProblem()`). The app's own code must apply it too, whenever it deactivates someone or takes a role away. Inside the transaction, after the change, call `authz.EnsureAdmin(ctx, tx)`; it returns `authz.ErrLastAdmin` when nobody active is left holding `roux.admin`, and the transaction must then roll back: ``` err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { if err := authz.Remove(ctx, tx, identityID, role.ID); err != nil { return err } if err := authz.EnsureAdmin(ctx, tx); errors.Is(err, authz.ErrLastAdmin) { return authz.LastAdminProblem() } else if err != nil { return err } return nil }) ``` Two such changes at once could both pass; take a lock that serializes them first (roux's own use a transaction-scoped advisory lock). Prefer roux's endpoints for these changes where you can. The rule is about managing people, not the name `OWNER`: an app that also grants `roux.admin` to another role may remove the last owner while someone holding that role is active. Grant it to `OWNER` alone unless that is what you want. ## The pieces - `authz.RoleOwner`, `authz.Admin`; `app.RouxPermissions()`. - `authz.FindRole(ctx, db, name)`, `authz.RolesOf(ctx, db, identityID)`, `authz.Assign`, `authz.Remove`, `authz.EnsureAdmin`, `authz.ErrLastAdmin`, `authz.LastAdminProblem()`. - `authz.Invitable` (`NewInvitable(names)`, `Contains`, `Names`), served by `authz.RegisterInvitable` at `authz.InvitablePath`. - `authn.Principal`: `Has(permission)`, `IdentityID`, `Permissions`. - `rouxtest.PermissionsFile` and `rouxtest.CheckGrants`, for the app's permissions tests. - The tables: `roux_role` (`id`, `name`), `roux_role_permission` (`role_id`, `permission`), `roux_identity_role` (`identity_id`, `role_id`). ## Don't - Don't check a role's name in code (`if role == "OWNER"`): check a permission. - Don't create roles or grant permissions from startup code (a module's `Start`); write a migration. - Don't refer to a role by its id in a migration: ids differ between databases. Use its name. - Don't edit `permissions.gen.ts`, or keep a second list of permissions in the front end. - Don't deactivate someone or remove a role without `authz.EnsureAdmin` in the same transaction. - Don't list `OWNER` in `INVITABLE_ROLES`, or grant `roux.admin` to another role without meaning to. # Users A **user** is a member of the team: anyone who can sign in. roux's sign-in owns what makes them able to: the identity, its status, its email addresses and passkeys, its roles. The users module (`app.UsersFromEnv`, package `users`) adds the one thing every app shows, a **display name**, in its own table, and the endpoints that list, invite and manage users. Its table, `roux_user`, and its view, `roux_user_directory`, come from its own migration (`users.Migration`, named `roux-users`), which runs before the app's. ## The rule: anything that signs in is a user Anything in the app that can sign in is a user; what never signs in is not. Roles say what a user may do; the app's own table, when it has one, says what they are. Pick one of three shapes: | The app's thing | Shape | Example | | ------------------------------------------ | ------------------------------------------------------------------------------- | --------------------------------------------------------- | | Is nothing but a person with permissions | **A role only.** No table: the user and their role are all there is. | An organizer who can change everyone's items | | Always signs in, and has fields of its own | **A table that shares the user's id.** | A person's profile: the team they are on | | Sometimes signs in | **A table with an optional reference to a user**, set when it is given a login. | A contact (a supplier, a venue), some of whom get a login | A table that shares the user's id makes it its key, and goes when the user does: ``` create table profile ( id uuid primary key references roux_user (id) on delete cascade, team text not null default '', version bigint not null default 0 ); ``` roux has no hook that runs when a user joins, so the app makes the row when it is first needed (`insert into profile (id) values ($1) on conflict (id) do nothing`), or from its own invite endpoint after `users.Service.Invite`. A table for something that only sometimes signs in has its own id and a nullable `user_id uuid references roux_user (id) on delete set null`, set when the app invites that row. `roux_user` holds the id (the identity's id), `display_name` (trimmed, 1 to `users.MaxNameLength`, 80, characters), a version and when they first signed in. It takes no domain columns: put them on the app's table. ## Referring to people A feature that assigns work to people, or lists who came, keeps their ids, and checks them in the transaction that stores them: ``` if err := users.MustBeActive(ctx, tx, "assigneeIds", in.Assignees); err != nil { return err // 400 on assigneeIds: "Must be active members of the team" } ``` `users.MustBeActive(ctx, db, field, ids)` refuses an id that is not an active member (unknown, or deactivated) as a `400` on `field` (`users.MustBeActiveMembers`); the same id twice is one member. To show them, `users.Members(ctx, db, ids)` answers each as a `users.Member` (`id`, `name`, `active`), by name, leaving out an id that is no member, so a feature that keeps people who have since left can still name them and mark them inactive. A feature's table refers to them with `references roux_user (id)`. The people a form may choose from now (an assignee picker's options) are `users.ActiveMembers(ctx, db)`: every active member, by name. A feature serves them from an endpoint of its own, under its own read permission, so everyone who can fill in the form can see the choices: ``` k.Handle("GET "+BasePath+"/assignees", TasksRead, func(w http.ResponseWriter, r *http.Request) error { members, err := users.ActiveMembers(r.Context(), svc.Pool) if err != nil { return err } return api.JSON(w, http.StatusOK, members) }) ``` ## The endpoints All under `/api/roux/users` (`users.BasePath`), each behind one of the users' permissions (`users.UsersRead`, `users.UsersInvite`, `users.UsersManage`, `users.UsersOwners`), which its migration grants to `OWNER`. Grant them to the app's own roles in the app's migration (the template grants `users.read` to `USER`). | Endpoint | Permission | Does | | ----------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /me` | signed in | The caller: `{ id, displayName, email, version }` (`users.Me`) | | `PUT /me` | signed in | Renames the caller: `{ displayName, version }` | | `GET /` | `users.read` | A page of `users.Row` (`id, displayName, email, role, status`); `search`, `role`, `status` (`ACTIVE` by default, or `DEACTIVATED`), sorted by `NAME` (the default), `EMAIL`, `ROLE` or `JOINED` | | `GET /{id}` | `users.read` | `users.Detail`: the row plus `joinedAt`, `invited` (never signed in) and `version` | | `GET /{id}/activities` | `users.read` | The user's history (roux's `user.*` kinds only), newest first ([The activity log](https://jwcarman.github.io/roux/guides/activity-log/index.md)) | | `POST /invitations` | `users.invite` | Invites `{ name, email, role }`; `202 { linkSent }` | | `POST /{id}/invitation` | `users.invite` | Sends the invitation again; `202 { linkSent }`, `false` within the resend interval | | `PUT /{id}/name` | `users.manage` | Renames them: `{ displayName, version }` | | `PUT /{id}/role` | `users.manage` | Gives them one role in place of theirs: `{ role }` | | `POST /{id}/deactivate` | `users.manage` | Deactivates them | | `POST /{id}/reactivate` | `users.manage` | Reactivates them | | `POST /{id}/sign-out` | `users.manage` | Ends every session they have; `204` | | `POST /{id}/owner` | `users.owners`, and a recent sign-in | Makes them an owner, in place of their role | `email` and `role` may be `null` (someone who signs in only with a provider has no address). roux-web's `@jwcarman/roux-web/users` is the client for all of them. What they refuse ([Errors](https://jwcarman.github.io/roux/guides/errors/index.md)): - An unknown id is `404` "No such user" (`users.NotFound()`). A stale `version` is `409`; a missing one a `400` on `version`. - A blank or overlong name is a field error on `displayName`. An address that already belongs to someone is a field error on `email`, "That address already belongs to a user". A role that is not invitable (`INVITABLE_ROLES`; never `OWNER`) is a field error on `role`, "That role cannot be given", as is an unknown `role` filter on the list ("No such role"), and a role holding a permission the caller does not hold ("You cannot give a role with permissions you do not hold"). - Deactivating yourself is `400` "You cannot deactivate yourself". Deactivating someone deactivated is `409` "Already deactivated"; reactivating someone active, `409` "Already active". Resending to someone who has signed in is `409` "Already signed in". - A change that would leave no one active who can manage people is `409` with code `last-admin` ([Roles](https://jwcarman.github.io/roux/guides/roles/#keep-someone-who-can-manage-people)). `users.Service` is the service behind them, for an app's own endpoint or job: `Invite`, `Rename`, `ChangeRole`, `Deactivate`, `Reactivate`, `MakeOwner`, `SignOutEverywhere`, `List`, `Detail`, `Me` and `Names`. `users.ListConfig` is its list's sorts (`NAME`, the default, `EMAIL`, `ROLE`, `JOINED`) and page sizes, for `api.PageRequest`. ## One role per user An invitation gives one role, and `PUT /{id}/role` replaces whatever the user holds with the one asked for. Changing to the role they hold already does nothing and records nothing. Only invitable roles can be given that way. `OWNER` is given by `POST /{id}/owner`, to someone who is already a user: invite them first, then make them an owner. It needs `users.owners` (granted to `OWNER` alone; leave it there, since whoever holds it can hand out everything) and a recent sign-in (within 10 minutes): a caller who signed in longer ago gets `401` and signs in again. It is recorded as `user.role_changed`. ## Signing out and deactivating `POST /{id}/sign-out` ends every session the user has, on every device: their next request is `401`. Deactivating ends them too. A reactivated user signs in again. ## The directory `roux_user_directory` is one row per user: `id`, `version` and `display_name` from `roux_user`, and from sign-in the `status` (`ACTIVE`, or `DEACTIVATED` for any other), `joined_at`, the `role` (the first by name, if someone holds more than one), `invited` and **the `email`: the oldest of their addresses**, since none is marked primary. A user changes their addresses on their own account page; the directory follows. `users.Filter{Search, Role, Status}` is the list's filter: each word of `Search` must be in the name or the email, ignoring case (`%` and `_` taken literally); `Role` and `Status` must match, and an empty status means `ACTIVE`. ## An app's own list An app that shows users with columns of its own (a person's team) writes its own list over a view that joins its table to the directory, and searches, filters and sorts by the user's fields too: ``` create view profile_list as select d.id, d.display_name, d.email, d.status, p.team from profile p join roux_user_directory d on d.id = p.id; ``` ``` var list = page.New(page.ListConfig[Sort, Row]{ From: "profile_list", Sorts: map[Sort][]page.Term{ ByName: {page.By("lower(display_name)")}, ByEmail: {page.By("lower(email)")}, ByTeam: {page.By("lower(team)")}, }, DefaultSort: ByName, Search: []page.Field{page.Contains("display_name"), page.Contains("email")}, }) type Row struct { ID uuid.UUID `json:"id" db:"id"` DisplayName string `json:"displayName" db:"display_name"` Email *string `json:"email" db:"email"` Team string `json:"team" db:"team"` } ``` with `page.Where("status = ?", users.StatusActive)` as a filter (`users.StatusDeactivated` for the others). [Tables and paging](https://jwcarman.github.io/roux/guides/tables-and-paging/#the-server) covers the paginator and the endpoint. ## Its activities Every change is recorded against the user, in its transaction: `user.invited` (`users.UserInvited`), `user.signed_up` (`users.UserSignedUp`, a provider sign-up), `user.renamed` (`users.UserRenamed`, from and to; only when the name changed), `user.deactivated` (`users.UserDeactivated`), `user.reactivated` (`users.UserReactivated`) and `user.role_changed` (`users.UserRoleChanged`, from and to). The actor is the signed-in user, named from `roux_user`. A user's history (`GET /{id}/activities`) is these `user.*` kinds only. Anyone with `users.read` sees it, so an app's activity about a person (an allowance entry related to a kid) is never in it: it belongs in the app's own feed (`activity.Feed` with `activity.About(personID)`), under the app's own permission. Never name an app's kinds `user.*`. ## In the browser: `@jwcarman/roux-web/users` The template's Users pages are built on this client; an app's own page about people uses it too. - `usersApi`: `list`, `get`, `invite`, `changeStatus`, `renameMe`, over `/api/roux/users`. - Queries: `usersPage(filters)` (a `UserFilters`: `search`, `role`, `status`; rows are `User`), `userQuery(id)` (a `UserDetail`), `userActivitiesPage(id)`, `invitableRolesQuery`. Their keys are `userKeys`, under `["roux", "users"]`. - Mutations: `inviteUser` (an `Invitation`, answering an `InvitationResult` with `linkSent`), `changeUserStatus(id)` (a `UserStatusAction`: `deactivate` or `reactivate`), `renameMe(version)` (a `Rename`). - Schemas: `invitationSchema` and `renameSchema`, in the server's words; `MAX_NAME` is 80, the server's `users.MaxNameLength`. ## Don't - Don't add domain columns to `roux_user`, or a second display name to the app's table: put the app's columns on its own table, and read the name from the user. - Don't keep a copy of the user's email: read it from the directory, which follows sign-in. - Don't store an id of someone without `users.MustBeActive` in the same transaction. - Don't deactivate someone or change their role with SQL of your own: use `users.Service`, or keep the last administrator ([Roles](https://jwcarman.github.io/roux/guides/roles/#keep-someone-who-can-manage-people)). # Tables and paging A roux list is paged by the server. The endpoint takes the page parameters (`pageIndex`, `pageSize`, `sortBy`, `sortDirection`) plus its own filters, and answers a `PageDto`: one page of rows and where it sits in the whole. In the browser, `@jwcarman/roux-web/table` draws a paged, sortable table over such an endpoint (`QueryTable`), with search inputs and filter chips beside it, and `@jwcarman/roux-web/paging` holds the page types, a list that grows a page at a time (`InfiniteList`), a picker over a long list (`InfiniteSelect`), and the helpers that keep a table's state in the URL. Queries and keys follow [Queries and mutations](https://jwcarman.github.io/roux/guides/queries-and-mutations/index.md). A list that grows as the app is used (tasks, entries, payments, events, anything with a date) is paged this way, even while it is short: done and past rows pile up. A list that something small and fixed bounds (the roles, the colours, a team's labels) is one request, shown with `SimpleQueryTable` ([A short list](#a-short-list)). ## The wire A paged endpoint reads these query parameters, all optional (`contracts/page-params.json`): | Parameter | Meaning | When absent | | --------------- | --------------------------------------------------------------------------------------- | ----------------------------------------- | | `pageIndex` | The page, counting from 0. | 0 | | `pageSize` | Rows per page; kept between 1 and the list's maximum (100 unless configured). | the list's default (20 unless configured) | | `sortBy` | One of the list's sorts (`DAY`, `TITLE`): the constants of its sort type on the server. | the list's default sort | | `sortDirection` | `ASC` or `DESC` (any case). | `ASC` | and answers (`contracts/page.json`): ``` { "data": [ { "id": "1", "title": "Order the venue" }, { "id": "2", "title": "Send the invitations" } ], "pagination": { "pageIndex": 0, "pageSize": 2, "totalElementCount": 3, "totalPageCount": 2, "hasNext": true, "hasPrevious": false } } ``` The same shapes in TypeScript, from `/paging` (`PageParams`, `PageDto`, `PaginationDto`, `SortDirection`): ``` type SortDirection = "ASC" | "DESC"; interface PageParams { pageIndex?: number; pageSize?: number; sortBy?: string; sortDirection?: SortDirection; search?: string; // the search term most list endpoints also take } interface PageDto { data: T[]; pagination: PaginationDto; } interface PaginationDto { pageIndex: number; pageSize: number; totalElementCount: number; totalPageCount: number; hasNext: boolean; hasPrevious: boolean; } ``` Refusals are Problem Details ([Errors](https://jwcarman.github.io/roux/guides/errors/index.md)), all `400` with `errors` on the parameter: - A `sortBy` that is not one of the list's sorts: ``` { "title": "Bad Request", "status": 400, "detail": "The request has invalid fields", "errors": [{ "field": "sortBy", "message": "Must be one of ASSIGNEE, DAY, TITLE" }], "instance": "/api/items" } ``` - A `sortDirection` other than `ASC` or `DESC`: an error on `sortDirection`. - A `pageIndex` or `pageSize` that is not a number: an error on that field, `Invalid value`. The browser never sends these if the table's column ids are the list's sort names and the URL is read with `tableSearchOf` (below). ## The server A list is declared once, as a package variable, with `page.New`; the handler reads the page request with `api.PageRequest` and asks the list for a page. The paginator writes the count, the search, the `ORDER BY` (with `id` last, so rows never move between pages), `LIMIT` and `OFFSET`; the app writes the SQL particular to it: the view, and each filter. ### The view Give each list a view shaped for it: one row per record, with every column the list shows, sorts by or searches, and an `id`. Joined and computed values (a person's name, the first of several assignees, a count) are columns of the view, so sorting and searching by them is no different from any other column. A column the row answers in another form than the database keeps it is the view's work too: a date as `2026-11-24` is `to_char(day, 'YYYY-MM-DD')`, a time of day as `10:30` is `to_char(at_time, 'HH24:MI')`, beside the `date` and `time` columns the filters and sorts use: ``` -- The items list reads this: the item, and its assignees' names, the first of them to sort by. create view item_list as select i.id, i.title, i.notes, i.day, i.at_time, i.done, i.version, coalesce(a.ids, '{}') as assignee_ids, coalesce(a.names, '{}') as assignee_names, a.names[1] as first_assignee_name, to_char(i.day, 'YYYY-MM-DD') as day_text, to_char(i.at_time, 'HH24:MI') as at_text from item i left join lateral ( select array_agg(u.id order by lower(u.display_name), u.id) as ids, array_agg(u.display_name order by lower(u.display_name), u.id) as names from item_assignee ia join roux_user u on u.id = ia.user_id where ia.item_id = i.id) a on true; ``` A view is a migration like any table. `create or replace view` may add columns at the end but cannot change or drop one; a changed view is `drop view` and `create view` in a new migration. ### The list ``` // Sort is how the list may be sorted: the sortBy values a client sends. type Sort string const ( ByDay Sort = "DAY" ByTitle Sort = "TITLE" ByAssignee Sort = "ASSIGNEE" ) // list is the items list: item_list, by day unless asked otherwise. var list = page.New(page.ListConfig[Sort, Row]{ From: "item_list", Sorts: map[Sort][]page.Term{ ByDay: {page.By("day"), page.By("at_time").NullsFirst()}, ByTitle: {page.By("lower(title)")}, ByAssignee: {page.By("lower(first_assignee_name)")}, }, DefaultSort: ByDay, DefaultPageSize: 25, Search: []page.Field{page.Contains("title"), page.Contains("notes")}, }) // Row is an item as the list shows it: each db tag names a column of the view. type Row struct { ID uuid.UUID `json:"id" db:"id"` Title string `json:"title" db:"title"` Day string `json:"day" db:"day_text"` // 2026-11-24 At *string `json:"at" db:"at_text"` // 10:30, or null for all day Done bool `json:"done" db:"done"` AssigneeNames []string `json:"assigneeNames" db:"assignee_names"` Version int64 `json:"version" db:"version"` } ``` - **The row is the select list.** Each field's `db` tag names its column, and pgx fills the row by name, so there is no scan code to keep in step. `db:"-"` leaves a field out; an embedded struct contributes its own tagged fields. A field without a tag, or a tag that is not a plain column name, makes `page.New` panic, naming the field and the tag to write. - **The sort type is a string type** whose constants are the `sortBy` values; each maps to the terms it orders by. The request's direction applies to every term; `NullsFirst()` puts rows with no value first (they come last otherwise, ascending): here an all-day item leads its day. - **`DefaultPageSize: 25`** matches the browser's `DEFAULT_PAGE_SIZE` (without it, 20); the maximum is `page.DefaultMaxSize` (100) unless `MaxPageSize` says otherwise. - `page.New` returns a `*page.Paginator`; its `Page` takes a `page.Querier` (the pool, or a transaction). The direction is `page.Asc` or `page.Desc` (a `page.Direction`); a request's offset stops at `page.MaxOffset`, and a search term at `page.MaxSearchLength` characters. The answer is a `page.Page[T]`: `data`, and `pagination` (a `page.Pagination`). An unknown sort is a `page.UnknownSortError`, which `api.PageRequest` answers as the `400` on `sortBy`. - **Search fields** say how a word matches: `page.Contains(col)` anywhere in the column, `page.Prefix(col)` at its start (it can use an index on `lower(col) text_pattern_ops`), and `page.Exact(col)` the whole value, ignoring case. A search matches when every word of the term is in some field; a blank term matches everything, and one over 200 characters is a `400`. - **`page.New` panics on a mistake in the declaration** (a default sort that is not a sort, an untagged row field), so it stops the program when the package loads. - **Its test checks it.** The list's Go test runs `list.Check(ctx, pool)`, which runs the list's queries for every sort, both ways and with a search, matching nothing, so a misspelled view, column, sort or search field fails the build. A test in another package reaches the list through an `export_test.go` (`package items`, `var List = list`), Go's way of showing a test what the package keeps unexported: ``` func TestTheListMatchesTheDatabase(t *testing.T) { f := setup(t) if err := items.List.Check(context.Background(), f.Pool); err != nil { t.Fatal(err) } } ``` - **SQL is written as string literals.** `From`, `page.By`, the search fields and `page.Where` take only literals: a string variable or an `fmt.Sprintf` result does not compile (`cannot use ... as page.sqlText value`), so a value can never be pasted into SQL. Values go in as `page.Where`'s arguments; a choice between two fragments is two literals. ### The filters ``` // List is a page of items. func (s Service) List(ctx context.Context, req page.Request, f Filter) (page.Page[Row], error) { filters := []page.Filter{ page.WhereIf(f.Done != nil, "done = ?", f.Done), page.WhereIf(f.From != nil, "day >= ?", f.From), } if f.Assignee != nil { filters = append(filters, page.Where("assignee_ids && ?", []uuid.UUID{*f.Assignee})) } return list.Page(ctx, s.Pool, req, f.Search, filters...) } ``` - **`page.Where(fragment, args...)`** is one condition, with a `?` for each argument; the fragment is a constant and the values are always arguments. A slice is one argument: write `label_id = any(?)`, or `assignee_ids && ?` for an array column (above: any of the item's assignees is the one asked for). - **`page.WhereIf(cond, ...)`** is the condition when `cond` holds and nothing otherwise, so a list of optional filters reads as a list. Its arguments are evaluated either way: pass a pointer as it is (pgx sends the value), and dereference one only behind an `if`, as the assignee is here. - A `?` count that does not match the arguments panics the first time the line runs. ### The handler ``` k.Handle("GET "+BasePath, ItemsRead, func(w http.ResponseWriter, r *http.Request) error { req, err := api.PageRequest(r, list.Config()) if err != nil { return err } f, err := filterOf(r) if err != nil { return err } out, err := svc.List(r.Context(), req, f) if err != nil { return err } return api.JSON(w, http.StatusOK, out) }) ``` `api.PageRequest(r, list.Config())` reads `pageIndex`, `pageSize`, `sortBy` and `sortDirection`, answering a bad one with the `400` above. `filterOf` reads the list's own parameters, and refuses a value it does not know as a `400` on that parameter, never ignoring it: ``` func filterOf(r *http.Request) (Filter, error) { q := r.URL.Query() f := Filter{Search: q.Get("search")} switch q.Get("status") { case "": case "open": f.Done = new(false) case "done": f.Done = new(true) default: return Filter{}, problem.InvalidField("status", problem.MustBeOneOf("open", "done")) } return f, nil } ``` `new(false)` is a `*bool` pointing at `false` (since Go 1.26, `new` takes a value): `Done` is nil when the request asks for neither. A list whose order is fixed (a history, newest first) reads its request with `api.PageRequestUnsorted(r)`, which ignores any `sortBy`. A list already in memory pages with `page.Slice(sorted, req)`, and a page fetched some other way is wrapped with `page.Of(rows, req, total)`. ## The list's query A table, a growing list or a select takes the list's query: `pageQuery(queryKey, fetch)`, the list's key and how to fetch one page. Put it in the resource module, `src/items/items.ts`, beside `itemsApi` ([API client](https://jwcarman.github.io/roux/guides/api-client/#write-an-api-module-for-a-resource)), as a function of the list's filters, with the list's row type, statuses and sorts (the module already imports `queryKeys`): ``` /** The list's status filter: the server's `open` and `done`. */ export const ITEM_STATUSES = ["open", "done"] as const; export type ItemStatus = (typeof ITEM_STATUSES)[number]; /** The list's sorts: the column ids, and the server's `Sort` constants. */ export const ITEM_SORTS = ["DAY", "TITLE", "ASSIGNEE"] as const; export type ItemSort = (typeof ITEM_SORTS)[number]; /** A row of the items list, as `/api/items` answers it. */ export interface ItemRow { id: string; title: string; day: string; at: string | null; done: boolean; assigneeNames: string[]; version: number; } /** The items list under `filters`, as a QueryTable takes it: its key and how to fetch a page. */ export function itemsPage(filters: ItemFilters) { return pageQuery(queryKeys.items.list(filters), (params, signal) => itemsApi.list({ ...params, ...filters }, signal)); } ``` The filters go in the key and in the fetch, so a different search or status is a different list (and starts on its first page). `fetch` receives the page, page size and sort, and the abort signal: pass it on, so a page no longer needed is cancelled. The spread puts the filters after the table's parameters. The component adds the page it asks for to the key (`[...queryKey, params]`), which is why the key must come from `queryKeys`: a key outside its prefixes is not refreshed by a mutation's `meta.refreshes`. ``` interface PageQuery { queryKey: QueryKey; fetch: (params: PageParams, signal: AbortSignal) => Promise>; } function pageQuery(queryKey: QueryKey, fetch: PageQuery["fetch"]): PageQuery; ``` Each component appends its own part to the key, so no two shapes of cached data collide: the table adds the page request, `InfiniteSelect` its search and page size, and `InfiniteList` the word `"infinite"` (an infinite query caches `{ pages, pageParams }`, not a plain list). All stay under the module's key, so `meta.refreshes` reaches them. The page never calls `itemsApi` or builds a key: it passes `query={itemsPage(filters)}`. ## A paged table `QueryTable` is the whole thing: the rows, sortable headers, the pager, the row count and the page size, placeholder rows while the first page loads, `emptyText` when there are no rows, and `errorText` above the table when a page fails. It sits on the page without a box: small muted headings that stay in view down a long list (from `md` up), an arrow only on the sorted column, and the row under the pointer highlighted. The pager shows only when there is more than one page, and the page size only when a smaller size would show fewer rows; on one page the count is just `7 rows`. The items page (`src/items/ItemsPage.tsx`) keeps the page, sort, search and status filter in the URL, so a reload, Back and a shared link keep them: ``` import { Heading, Link, Stack } from "@chakra-ui/react"; import { getRouteApi, Link as RouterLink } from "@tanstack/react-router"; import { createColumnHelper, type ColumnDef } from "@tanstack/react-table"; import type { TableSearch } from "@jwcarman/roux-web/paging"; import { DEFAULT_PAGE_SIZE, DebouncedSearchInput, FilterChips, QueryTable } from "@jwcarman/roux-web/table"; import { ITEM_SORTS, itemsPage, type ItemRow, type ItemSort, type ItemStatus } from "./items"; /** The list's URL: page, sort and search, plus the status filter (all optional). */ export type ItemsSearch = TableSearch & { status?: ItemStatus }; /** The list's defaults, left out of the URL. */ export const ITEMS_SEARCH_DEFAULTS = { pageIndex: 0, pageSize: DEFAULT_PAGE_SIZE, sortBy: "DAY", sortDirection: "ASC", } as const satisfies TableSearch; const STATUS_CHIPS = [ { value: "open", label: "Open" }, { value: "done", label: "Done" }, ] as const; const column = createColumnHelper(); /** Each sortable column's id is its sort's name; a column the server cannot sort says so. */ const COLUMNS: ColumnDef[] = [ column.accessor((item) => (item.at ? `${item.day} ${item.at}` : item.day), { id: "DAY" satisfies ItemSort, header: "When", }), column.accessor("title", { id: "TITLE" satisfies ItemSort, header: "Title", cell: (info) => ( {info.getValue()} ), }), column.accessor((item) => item.assigneeNames.join(", "), { id: "ASSIGNEE" satisfies ItemSort, header: "Assigned to", }), column.accessor("done", { id: "STATUS", header: "Status", enableSorting: false, cell: (info) => (info.getValue() ? "Done" : "Open"), }), ]; const route = getRouteApi("/_signedIn/items/"); /** The team's items: paged, sortable, searchable, filtered by status, all kept in the URL. */ export function ItemsPage() { const search = route.useSearch(); const navigate = route.useNavigate(); return ( Items navigate({ search: (previous) => ({ ...previous, search: term, pageIndex: undefined }), replace: true }) } /> navigate({ search: (previous) => ({ ...previous, status, pageIndex: undefined }) })} /> navigate({ search: (previous) => ({ ...previous, ...next, sortBy: ITEM_SORTS.find((sort) => sort === next.sortBy), }), }) } getRowId={(item) => item.id} emptyText="No items found." errorText="Could not load the items." /> ); } ``` The route (`src/routes/_signedIn/items/index.tsx`) reads the URL with `tableSearchOf` and `enumSearchOf`, and leaves the defaults out of it: ``` import { createFileRoute, stripSearchParams } from "@tanstack/react-router"; import { enumSearchOf, tableSearchOf } from "@jwcarman/roux-web/paging"; import { ITEM_SORTS, ITEM_STATUSES } from "../../../items/items"; import { ItemsPage, ITEMS_SEARCH_DEFAULTS, type ItemsSearch } from "../../../items/ItemsPage"; export const Route = createFileRoute("/_signedIn/items/")({ validateSearch: (raw: Record): ItemsSearch => ({ ...tableSearchOf(raw, ITEM_SORTS), status: enumSearchOf(raw.status, ITEM_STATUSES), }), search: { middlewares: [stripSearchParams(ITEMS_SEARCH_DEFAULTS)] }, component: ItemsPage, }); ``` How it fits together: - **Column ids are sort names.** A column's `id` is what the table sends as `sortBy`, so it must be one of the list's sorts on the server (`satisfies ItemSort` makes the compiler check it). A column the server cannot sort sets `enableSorting: false`; an accessor column without it is sortable, and clicking it would ask for a sort the server refuses. - **One sort at a time.** A sortable header is a button with `aria-sort`; the first click sorts ascending, the next descending. Changing the sort returns to the first page. - **A filter change starts on page 1.** Uncontrolled, the table does it when the query's key changes. Controlled by `params` (as here), the page's `navigate` does it: set `pageIndex: undefined` in the same update that changes the search or a filter. - **`params` and `onParamsChange`.** With `params` the table shows the page and sort it is given (defaults for what is absent) and reports each change as `TableParams` (`{ pageIndex, pageSize, sortBy?, sortDirection? }`) instead of keeping its own; `params.search` is ignored. `onParamsChange` gives `sortBy` as a `string`: narrow it back to the sort type with `ITEM_SORTS.find(...)` before it goes in the URL. - **Typed URLs are checked.** `tableSearchOf(raw, sorts)` keeps a whole `pageIndex` (0 or more), a `pageSize` of at least 1 (capped at `MAX_PAGE_SIZE`, 100), a `sortBy` that is one of `sorts`, an `ASC`/`DESC` direction (any case), and a non-blank `search`; anything else is dropped. `enumSearchOf(raw, values)` keeps a filter value only if `values` offers it; for a filter whose values are ids loaded at run time (an assignee, a label), `idSearchOf(raw)` keeps a value only if it is shaped like a UUID, so the route never needs its own `typeof` check. A date that is URL state (a page for one day, a report's start) is `dateSearchOf(raw)`: a real `YYYY-MM-DD` (`2026-02-30` is not one) or absent; the page falls back to the organization's `today()` ([Dates and time](https://jwcarman.github.io/roux/guides/dates-and-time/index.md)). A typed URL past the last page moves to the last page. `validateSearch` returns every key, `undefined` for a bad value: the router lays its result over the raw URL parameters, so a key it leaves out passes the raw value through. - **The previous page stays on screen** while the next one loads (TanStack's `keepPreviousData`). - Without `params`, the table keeps its own page and sort, starting from `initialSort` and `initialPageSize` (`DEFAULT_PAGE_SIZE`, 25, unless given). `QueryTableProps`: | Prop | Type | Meaning | | -------------------------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `query` | `PageQuery` | The list's query from its module (`itemsPage(filters)`): its key, filters included, and how to fetch one page. | | `columns` | `ColumnDef[]` | TanStack Table columns; sortable ids are sort names. | | `initialSort` | `ColumnSort` (`{ id, desc }`) | The sort when the URL or state has none. Give the server's default, so the header shows it. | | `initialPageSize` | `number` | Rows per page when none is given; at most 100. | | `getRowId` | `(row: T) => string` | A stable row id, such as the entity's id. | | `params`, `onParamsChange` | `TableSearch`, `(params: TableParams) => void` | Keep the page and sort outside the table (the URL). | | `pageSizes` | `number[]` | The page sizes offered (`PAGE_SIZES`, `[10, 25, 50, 100]`, by default; above 100 left out). | | `emptyText` | `string` | Shown in place of rows when there are none (`No rows.`). | | `errorText` | `string` | Shown above the table when a page cannot be loaded (`Could not load the rows.`). | | anything else | Chakra `Table.Root` props | `aria-label` (always give one), `size`, `variant`, ... | `TableSearch` is the URL's shape: `{ pageIndex?, pageSize?, sortBy?: S, sortDirection?, search? }`. ## Search and filters ``` function DebouncedSearchInput(props: DebouncedSearchInputProps): JSX.Element; // DebouncedSearchInputProps: label, placeholder?, width?, size?, plus // term?: string the search in effect (from the URL) // onSearchChange: (term: string | undefined) => void // minLength?: number default 0 // debounceMs?: number default 300 function FilterChips(props: FilterChipsProps): JSX.Element; // FilterChipsProps: label, options: readonly FilterOption[] ({ value, label }), // value: T | undefined, onChange: (value: T | undefined) => void, // allLabel?: string | defaultValue?: T (one or the other, never both) ``` - `DebouncedSearchInput` (`DebouncedSearchInputProps`) reports the trimmed term once typing pauses (or at once when the field loses focus, so a link clicked mid-debounce navigates after it, not before), only when it changes, and `undefined` for a blank one. It follows `term` when the URL changes elsewhere (Back, a link) without reporting it back. Below `minLength` characters it searches for nothing and says `Type at least characters to search`. Escape and its clear button empty it and report the search gone at once. Pass `replace: true` to the navigation so Back skips the keystrokes. - `FilterChips` (`FilterChipsProps`, options of `FilterOption`) is one filter as a row of toggle buttons (`aria-pressed`), one chosen at a time; `allLabel` adds a first chip that clears it (`undefined`). `label` names the group for screen readers. When the list has its own default (a list that shows open items unless asked), pass `defaultValue` instead of `allLabel`: that chip shows chosen while `value` is `undefined`, and choosing it reports `undefined`, so the default stays out of the URL and the page needs no `value ?? DEFAULT` or `x === DEFAULT ? undefined : x` of its own. The two props exclude each other; with a default there is no "no filter" to offer. - `SearchInput` (`SearchInputProps`: `value`, `onChange`, `label`, `placeholder?`, `width?`, `size?`) is the same field without the debounce, for a filter in the browser; `useDebounce(value, delayMs)` gives the value once it has stopped changing: ``` import { List, Stack } from "@chakra-ui/react"; import { useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { SearchInput, useDebounce } from "@jwcarman/roux-web/table"; import { labelsQuery } from "./labels"; /** The labels whose name holds what was typed: a filter in the browser, no request per key. */ export function LabelFilter() { const [text, setText] = useState(""); const term = useDebounce(text, 200).trim().toLowerCase(); const labels = useQuery(labelsQuery); const shown = (labels.data ?? []).filter((label) => label.name.toLowerCase().includes(term)); return ( {shown.map((label) => ( {label.name} ))} ); } ``` `searchTermOf(text, minLength)` is the rule `DebouncedSearchInput` applies: the trimmed text, or `undefined` when it is blank or shorter than `minLength`. ## A table with its own layout `QueryTable` is `useQueryTable` plus `TableView`. To arrange the parts differently, call the hook and place them yourself: ``` import { Flex, Stack } from "@chakra-ui/react"; import { createColumnHelper, type ColumnDef } from "@tanstack/react-table"; import { ErrorMessage } from "@jwcarman/roux-web/feedback"; import { TablePageSizeSelect, TablePagination, TableStatus, TanstackTable, useQueryTable, } from "@jwcarman/roux-web/table"; import { itemsPage, type ItemRow } from "./items"; const column = createColumnHelper(); const COLUMNS: ColumnDef[] = [ column.accessor("day", { id: "DAY", header: "Day" }), column.accessor("title", { id: "TITLE", header: "Title" }), ]; /** The open items, with the row count and page size above the table and the pager below. */ export function OpenItemsTable() { const { table, isLoading, isError } = useQueryTable({ query: itemsPage({ status: "open" }), columns: COLUMNS, initialSort: { id: "DAY", desc: false }, initialPageSize: 10, getRowId: (item) => item.id, }); return ( {isError && Could not load the items.} ); } ``` - `useQueryTable(options: UseQueryTableOptions): UseQueryTableResult`. The options are `QueryTable`'s first seven props (`query`, `columns`, `initialSort`, `initialPageSize`, `getRowId`, `params`, `onParamsChange`). The result is `{ table, page, isLoading, isError, refetch }`: the TanStack `table`, the `PageDto` on screen (the last one loaded while the next loads), `isLoading` while the first page loads, `isError` when a page failed. - `TanstackTable` (`TanstackTableProps`: `table`, `isLoading?`, `isError?`, `emptyText?`, and Chakra `Table.Root` props) draws the rows and the sortable headers; while it loads with no rows, three placeholder rows and a `status` named "Loading". - `TableView` (`TableViewProps`: `TanstackTable`'s props plus `pageSizes?`) is `TanstackTable` with the pager (more than one page), the status and the page size (more rows than the smallest size) below it, shown once there are rows. - `TablePagination` (`{ table }`): first, previous, a page number field (`Page of `), next, last. A number typed past the end goes to the last page. - `TableStatus` (`{ table }`, plus Chakra `Text` props): `Showing 26 to 50 of 60 rows` (`7 rows` on one page), announced politely as it changes. `rowRange(pagination, rowsOnPage)` gives its `{ first, last, total }`. - `TablePageSizeSelect` (`TablePageSizeSelectProps`: `table`, `pageSizes?`): rows per page, from `PAGE_SIZES` unless given; sizes above `MAX_PAGE_SIZE` are left out, and the current size is always offered. - `pageParamsOf(pagination, sorting)` turns a table's state into the `PageParams` it requests: the first sorted column becomes `sortBy`. ## Choose rows `createSelectColumn(options: SelectColumnOptions): ColumnDef` makes a checkbox column. The selection is the page's state, kept by key, so it survives paging: ``` import { Button, Stack } from "@chakra-ui/react"; import { createColumnHelper, type ColumnDef } from "@tanstack/react-table"; import { useState } from "react"; import { createSelectColumn, QueryTable } from "@jwcarman/roux-web/table"; import { itemsPage, type ItemRow } from "./items"; const column = createColumnHelper(); const COLUMNS: ColumnDef[] = [ column.accessor("day", { id: "DAY", header: "Day" }), column.accessor("title", { id: "TITLE", header: "Title" }), ]; /** Open items to choose and mark done together, across pages. */ export function ChooseItems({ onChosen }: { onChosen: (items: ItemRow[]) => void }) { const [selected, setSelected] = useState>(new Map()); const columns = [ createSelectColumn({ selected, onSelectedChange: setSelected, keyOf: (item) => item.id, labelOf: (item) => item.title, }), ...COLUMNS, ]; return ( item.id} /> ); } ``` `SelectColumnOptions`: `selected` (a `ReadonlyMap` from key to row), `onSelectedChange` (a new `Map`), `keyOf` (a stable key; rows are new objects on every fetch), `labelOf` (each checkbox is labelled `Select