saasaloy-app
Runbook for the app capability — the customer SPA at apps/app on port 3002, where every signed-in user lands. Use when adding a product screen (a list or a form) to apps/app, putting a screen in the sidebar, protecting a screen by session or by role, calling the api from the app with the typed hc client and TanStack Query, wiring the sign-in and sign-up routes, changing the app's canvas in app.css, debugging the :3002 → :4000 cookie and CORS flow (including COOKIE_DOMAIN and the workers.dev case), deploying the static bundle to Workers, or removing the module.
- License 许可
- MIT
- 所属仓库
- mimukit/saasaloy
- 最近更新
- 2026-11-13
- Stars
- ★ 4
- Forks
- 0
01 前言 Front Matter
- name
- saasaloy-app
- description
- Runbook for the app capability — the customer SPA at apps/app on port 3002, where every signed-in user lands. Use when adding a product screen (a list or a form) to apps/app, putting a screen in the sidebar, protecting a screen by session or by role, calling the api from the app with the typed hc client and TanStack Query, wiring the sign-in and sign-up routes, changing the app's canvas in app.css, debugging the :3002 → :4000 cookie and CORS flow (including COOKIE_DOMAIN and the workers.dev case), deploying the static bundle to Workers, or removing the module.
03 SKILL.md 正文
app — the customer SPA
apps/app is the product a signed-in user sees: a TanStack Router + Vite SPA on port 3002, built on the shell frame with the web brand tokens, light first. apps/web keeps the public pages; apps/admin is the backoffice for the admin group. Any signed-in account may open app. See ADR 0047 for why the product lives here and not in web or admin.
saasaloy add app installs api, auth and shell first, and needs no admin. It writes:
| Path | What it is |
|---|---|
apps/app/ |
the SPA: vite.config.ts (port 3002, strictPort), wrangler.jsonc (assets only), src/env.ts |
apps/app/src/routes/__root.tsx |
the one guard: no session sends the visitor to /sign-in?redirect=… |
apps/app/src/routes/sign-in.tsx, sign-up.tsx |
the auth module's SignInCard and SignUpCard, with the calls to the client instance |
apps/app/src/routes/index.tsx |
the home screen: a welcome card and an empty state that points at saasaloy-feature |
apps/app/src/components/nav.ts |
the sidebar's nav data |
apps/app/src/components/nav-counts.ts |
the sidebar's live counts, NAV_COUNTS, empty until a module adds a row |
apps/app/src/lib/auth.ts, api.ts, redirect.ts |
the auth client and session cache, the typed api client, the safe-destination check |
packages/ui/src/styles/app.css |
the app's one stylesheet: brand.css, shell.css, two canvas values |
It also appends an app row to packages/env/src/services.ts, a deploy target and a smoke check to packages/tooling/src/targets.ts, and a PUBLIC_API_URL entry for app to packages/env/.env.example. The auth module's blocks under packages/ui/src/blocks/auth/ arrive in the same run: auth ships them with when: { installed: ["shell"] }, so the shell this module brings writes them.
Wire-up
After saasaloy add app:
- Run
pnpm install. - Run
saasaloy env, thenpnpm env:setup.apps/app/.envgetsPUBLIC_API_URL(http://localhost:4000in dev). - Run
pnpm db:seedif the database is empty, thenpnpm dev. Openhttp://localhost:3002and sign in asmember@example.testwith the passwordsaasaloy-dev-password, or create an account on/sign-up. - A project made before the
apprelease has nohttp://localhost:3002inDEV_ORIGINS, inapps/api/src/index.tsand inpackages/auth/src/auth.ts. Runsaasaloy update api authfirst, or every call from :3002 fails CORS (see Failure modes). - In production, add the app's origin to
CORS_ORIGINS, the one list the api CORS spine andauth'strustedOriginsboth read:CORS_ORIGINS=https://x.com,https://app.x.com,https://admin.x.com. A set value replaces the localhost list, so name every frontend. Put the app and the api on sibling subdomains of one domain you own, and setCOOKIE_DOMAIN=.x.comwhen the derived one does not match. SetPUBLIC_API_URLfor theappservice to the api's origin.
Add a screen
Drop src/routes/<screen>.tsx with a createFileRoute whose id matches the file path. The file is a child of src/routes/__root.tsx, so it gets the shell and the session guard with no work of its own. @tanstack/router-plugin rewrites src/routeTree.gen.ts on the next pnpm dev or pnpm build, and pnpm typecheck runs tsr generate first, so a new route typechecks before Vite has run. Both read the generator options in tsr.config.json. Never edit src/routeTree.gen.ts by hand.
Then put it in the sidebar: add a row to NAV_AREAS in src/components/nav.ts. The to is checked against the route tree, so a typo fails pnpm typecheck. A row takes an optional shortcut, G then a letter written as "G P"; pick the letter by hand and keep it unique, because the tool repo's commands.test.ts fails on two rows with one shortcut. Every row becomes a "Go to <label>" command in src/components/commands.ts, which AppShell declares next to sign out and the three theme choices. A screen declares its own with useCommands(commands, { scope: "route", label }). They do nothing until the command module is installed, which appends itself to src/components/shell-extensions.ts.
items: [
{ to: "/", label: "Home", icon: HouseIcon, shortcut: "G H" },
{ to: "/projects", label: "Projects", icon: FolderIcon, shortcut: "G P" },
],
Add a live count to a nav row
A static count in NAV_AREAS is a number fixed at build time. A number that changes, such as how many notifications are unread, is a live count. NAV_COUNTS in src/components/nav-counts.ts lists them, one { to, path } per row. to is the row's to in NAV_AREAS. path is an api path that answers { count: number } behind the user's session.
A module adds its entry with a const-array patch keyed on to:
{
"file": "apps/app/src/components/nav-counts.ts",
"kind": "const-array",
"constName": "NAV_COUNTS",
"key": "to",
"entry": { "to": "/notifications", "path": "/notifications/unread-count" }
}
AppShell runs one TanStack query per entry under the key ["nav-count", to] and passes the numbers to ShellLayout as counts. Each query fetches PUBLIC_API_URL plus path with the session cookie. It refetches every 60 s while the tab is visible, on every window focus (refetchOnWindowFocus: "always", so a count fetched inside the 30 s staleTime still refetches), and on a pageshow with persisted set, which is a back-forward cache restore. A live count replaces the row's static count, and a live 0 hides the badge.
A failed fetch (a network error, a non-OK answer or a body without a numeric count) throws, so TanStack Query keeps the last count it read. The badge never drops to 0 or disappears because of a failure. Before the first success the row keeps its static count. A screen whose action changes a count invalidates the key after the mutation, so the badge follows with no reload:
await queryClient.invalidateQueries({ queryKey: ["nav-count", "/notifications"] });
Every screen renders inside the shell's page frame, which owns the width, the background and the gutter. Never set a page's own max-w-*, padding or background. Compose from the shell set only: @repo/ui/components/shell/*, @repo/ui/blocks/shell/*, @repo/ui/containers/shell/*. The base oxlint.config.mjs makes a base primitive under apps/app/** a lint error. saasaloy-shell lists the blocks.
The list recipe
A list reads the api through TanStack Query, and the loader fills the cache before the first paint. The route below assumes an api route GET /projects that answers { projects, total }; the saasaloy-feature skill builds one.
// src/routes/projects.index.tsx → /projects
import { queryOptions, useQuery } from "@tanstack/react-query";
import { Link, createFileRoute } from "@tanstack/react-router";
import { FolderIcon } from "lucide-react";
import { DataTable } from "@repo/ui/blocks/shell/data-table";
import type { DataTableColumn } from "@repo/ui/blocks/shell/data-table";
import { EmptyState } from "@repo/ui/blocks/shell/empty-state";
import { PageHeader } from "@repo/ui/blocks/shell/page-header";
import { Button } from "@repo/ui/components/shell/button";
import { StatusPill } from "@repo/ui/components/shell/status-pill";
import { PageLayout } from "@repo/ui/containers/shell/page-layout";
import { api } from "@app/lib/api";
const projectsQuery = queryOptions({
queryKey: ["projects"],
queryFn: async () => {
const res = await api.projects.$get();
if (!res.ok) {
throw new Error(`The api answered ${res.status}.`);
}
return res.json();
},
});
type Project = Awaited<ReturnType<NonNullable<typeof projectsQuery.queryFn>>>["projects"][number];
const COLUMNS: readonly DataTableColumn<Project>[] = [
{ id: "name", header: "Name", value: (project) => project.name },
{
id: "status",
header: "Status",
value: (project) => project.status,
cell: (project) => <StatusPill label={project.status} tone={project.status === "active" ? "ok" : "neutral"} />,
},
{
id: "updated",
header: "Updated",
value: (project) => project.updatedAt,
cell: (project) => new Date(project.updatedAt).toLocaleDateString(),
},
];
export const Route = createFileRoute("/projects/")({
loader: ({ context }) => context.queryClient.ensureQueryData(projectsQuery),
component: Projects,
});
function Projects() {
const { data } = useQuery(projectsQuery);
return (
<PageLayout>
<PageHeader
title="Projects"
count={data?.total}
actions={<Button render={<Link to="/projects/new" />}>New project</Button>}
/>
<DataTable
caption="Projects"
columns={COLUMNS}
rows={data?.projects ?? []}
rowId={(project) => project.id}
emptyState={<EmptyState icon={FolderIcon} title="No projects yet" description="Create the first one." />}
/>
</PageLayout>
);
}
value is what a column sorts on and shows when it has no cell. Read data through ?. even after the loader ran: useQuery types it as T | undefined, and the repo compiles with strict. Check DataTableColumn, PageHeader and StatusPill against their files under packages/ui/src/ when a prop does not type-check; the shell owns them.
The form recipe
A form posts through a TanStack Query mutation, then refreshes the list and navigates back. The server validates again; the form's checks are for the person typing.
// src/routes/projects.new.tsx → /projects/new
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import type { SubmitEvent } from "react";
import { PageHeader } from "@repo/ui/blocks/shell/page-header";
import { Button } from "@repo/ui/components/shell/button";
import { Field, FieldError, FieldLabel } from "@repo/ui/components/shell/field";
import { Form } from "@repo/ui/components/shell/form";
import { Input } from "@repo/ui/components/shell/input";
import { Textarea } from "@repo/ui/components/shell/textarea";
import { toastManager } from "@repo/ui/components/shell/toast";
import { PageBody } from "@repo/ui/containers/shell/page-body";
import { api } from "@app/lib/api";
export const Route = createFileRoute("/projects/new")({ component: NewProject });
function NewProject() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const create = useMutation({
mutationFn: async (input: { name: string; description: string }) => {
const res = await api.projects.$post({ json: input });
if (!res.ok) {
throw new Error(`The api answered ${res.status}.`);
}
return res.json();
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["projects"] });
toastManager.add({ type: "success", title: "Project created" });
await navigate({ to: "/projects" });
},
onError: (error) => {
toastManager.add({ type: "error", title: "The project was not created", description: error.message });
},
});
function submit(event: SubmitEvent<HTMLFormElement>) {
event.preventDefault();
const data = new FormData(event.currentTarget);
const name = data.get("name");
const description = data.get("description");
create.mutate({
name: typeof name === "string" ? name : "",
description: typeof description === "string" ? description : "",
});
}
return (
<>
<PageHeader title="New project" />
<PageBody>
<Form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
<Field>
<FieldLabel>Name</FieldLabel>
<Input name="name" required />
<FieldError />
</Field>
<Field>
<FieldLabel>Description</FieldLabel>
<Textarea name="description" />
</Field>
<Button type="submit" loading={create.isPending} className="self-start">
Create project
</Button>
</Form>
</PageBody>
</>
);
}
A form's max-w-* is the field column's width inside the page, not the page's width, so it does not fight the frame.
Protect a screen
The session. Every route under __root.tsx already needs one. The guard reads loadSession() once per page load; a visitor with none goes to /sign-in?redirect=<the page>, and the sign-in screen sends them back after a sign-in. src/lib/redirect.ts keeps that redirect on this origin and on a route this app has, or falls back to /.
A role. Ask the api, not the session object. The client session this app holds is not typed with role: adminClient() rides on the admin client only (see saasaloy-auth). So a role-gated screen calls a route the api guards with requireRole, in its beforeLoad, and sends the visitor home on a 403:
export const Route = createFileRoute("/subscription")({
beforeLoad: async () => {
const res = await api.subscription.$get();
if (res.status === 403) {
throw redirect({ to: "/" });
}
},
component: Subscription,
});
An organization role from the teams module is a different question with its own helper, can() from @repo/auth/permission-rules; saasaloy-teams covers it.
The api is the real gate. Hiding a screen protects nothing. Every api route the screen calls checks the session or the role itself, with requireSession(c) or requireRole(c, …) from @repo/auth/server (see saasaloy-auth). A request from app carries the client session, because src/lib/api.ts sends no x-auth-audience header.
Call the api
src/lib/api.ts exports api, an hc<AppType> client: api.<route>.$get() returns the route's own response type, with no hand-written fetch. It sends the session cookie (credentials: "include") to PUBLIC_API_URL. Wrap each call in queryOptions for a read and useMutation for a write, as the recipes above do.
An api route a screen calls is the api module's business: add it under apps/api/src/routes/ and gate it there. saasaloy-api has the route recipe, and saasaloy-feature builds a table, a route and a screen together.
Theme and stylesheet
src/main.tsx imports @repo/ui/styles/app.css, the app's one Tailwind entrypoint. It imports brand.css (the web brand tokens, which import globals.css), then shell.css (the shell primitives' @source line, status tokens and motion), then sets two canvas values per theme: --sidebar and --sidebar-accent. Those are the round 2 values the approved mockup settled on, so the white panel stands off the canvas. A shadcn preset applied to brand.css repaints app and the landing page together; admin keeps its own theme in admin.css.
The app starts light on a first visit and keeps the visitor's choice after that, system included. The theme menu sits in the shell's account menu.
Ports and CORS
| Service | Port |
|---|---|
apps/web |
3000 |
apps/admin |
3001 |
apps/app (this app) |
3002, with strictPort |
email-react preview |
3003 |
apps/api |
4000 |
http://localhost:3002 is in the api's DEV_ORIGINS and in auth's trustedOrigins fallback. strictPort makes a busy port fail at once rather than move to 3003, where nothing allows it. Cookies ignore the port, so the app at :3002 and the api at :4000 share the localhost jar, and the client cookie (client.session_token) never replaces the admin app's admin.session_token.
Deploy
apps/app/wrangler.jsonc serves dist/ as Workers static assets with not_found_handling: "single-page-application", so a hard reload on /projects gets index.html and the router takes over. pnpm deploy:production deploys it after the api and admin (order: 25) through the deploy script, env-deploy app, and smoke-checks / when the Worker has a custom domain route. Set the production PUBLIC_API_URL for app and add the app's origin to CORS_ORIGINS first (step 5 of Wire-up). saasaloy-deploy has the full run.
Removing the module
saasaloy remove app deletes apps/app, app.css and the rows in services.ts and targets.ts, and leaves shell and auth installed. Take the app's origin out of CORS_ORIGINS, and run pnpm install so the lockfile drops the workspace. saasaloy remove shell then removes the auth blocks too, unless admin still needs shell.
Failure modes
- The browser console says the request was blocked by CORS, or sign-in answers
403withINVALID_ORIGIN. The origin is not in the list. In dev, the project predates theapprelease: runsaasaloy update api auth, sohttp://localhost:3002joinsDEV_ORIGINS. In production, add the app's origin toCORS_ORIGINSand redeploy the api; a setCORS_ORIGINSreplaces the localhost list, so it has to name every frontend. - Sign-in succeeds, then the guard sends the visitor straight back to
/sign-in. The browser did not keep the session cookie, or does not send it to the api. The app and the api must be same-site: sibling subdomains of one domain you own, such asapp.x.comandapi.x.com. SetCOOKIE_DOMAIN=.x.comwhen the domain derived fromBETTER_AUTH_URLis not the shared parent. - The same loop on
*.workers.dev.workers.devis on the public suffix list, soapp.<account>.workers.devandapi.<account>.workers.devare two different sites, and noCOOKIE_DOMAINcan join them. Browsers treat the session cookie as third-party and drop it. Put both Workers on custom domains of one zone. - The build fails naming
PUBLIC_API_URL.apps/app/.envlacks it. Runsaasaloy envandpnpm env:setup; for a deploy, set it for theappservice. pnpm devfails with "Port 3002 is already in use". Another process holds it, often an olderemail-reactpreview from before it moved to 3003. Stop that process; do not change the port, or CORS breaks.- The pages render with no styles.
src/main.tsxno longer imports@repo/ui/styles/app.css, orapp.csslost itsshell.cssimport. Restore both. - The sign-in card renders unstyled. The blocks are missing:
packages/ui/src/blocks/auth/is empty becauseshellwas installed beforeauth's blocks existed. Runsaasaloy update auth.
Next
Run saasaloy-feature to build the first product feature end to end: the table, the api route, the screen here, and its test.
04 同仓库更多 Skills
saasaloy-subscription
Runbook for the subscription capability — provider-agnostic subscriptions in packages/subscription, with a plan file, a projection table, a billable-subject file, plan entitlements and per-provider modules. Use when adding a plan, adding a plan feature or a numeric limit, gating an API route with requireFeature or requireWithinLimit, reading the 402 it returns, working out why a subject resolves to the free plan, wiring a checkout or portal route, reading a SubscriptionError, choosing or switching SUBSCRIPTION_PROVIDER, registering a webhook in the vendor's dashboard, writing a third subscription provider, or upgrading a project that still has `billing` installed.
saasaloy-notification
Runbook for the notification module, in-app notifications for apps/app. It owns the notifications and notification_opt_outs tables, notify() in apps/api/src/lib/notify.ts, the /notifications api routes, the bell in the app header, the sidebar badge, the /notifications page with Inbox and Preferences tabs, the notification config section, and the daily prune. Use when sending a notification from an api route, adding or changing a category, changing retention, debugging a badge or bell count that does not move, or removing the module.
saasaloy-cms
Runbook for the cms module, the in-house CMS behind apps/admin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps/web and its 60-second cache. Use when adding a collection or a field, rendering a stored body, reusing the editor, renderer or media field from another module, moving the blog to another path, re-rendering live posts after a renderer upgrade or a STORAGE_PUBLIC_URL change, or working out why a published post is not live yet.
saasaloy-beta
The beta module's own procedure.
helper
暂无简介
saasaloy-update
Runbook for an AI agent that updates this project to a newer Saasaloy CLI and newer module versions with saasaloy update. Use when the owner says "update saasaloy", "upgrade the CLI", "pull the latest modules", "update the base template", "work the merge plan", "clear the update notes", when saasaloy update or saasaloy outdated --check exits 3 or 2, when a merge plan or .saasaloy/merge-plan.md is handed to you, or when an adopted project takes its first update. Covers the CLI upgrade, the preview, --out, the file merges, the update notes and "Notes that may apply", --resolved and --done, a file deleted locally and --restore, a three-way or two-way base, an update that skips releases, --from, the verify commands, and the exit codes.