A starting point for new projects on this stack. Copy this file into a new repo's docs/ folder (as docs/SPEC.md, or use it to seed AGENTS.md), fill in §0 The product, and remove the optional modules you don't need. Everything after §0 is the house default; change it only on purpose, and write down why.
Placeholders: {{APP_NAME}} (display name), {{app_slug}} (lowercase, used for cookies, key prefixes and the Render service), {{domain}} (e.g. example.com).
Replace this section with the business problem. Everything else in this document is infrastructure.
- Problem: who has it, and what they do about it today.
- Users and roles: who signs in, and what each role can do.
- Core objects: the nouns (they become Prisma models,
/v1resources and ID prefixes). - Core flows: the 3–5 things a user must be able to do in v1.
- Public surfaces: anything served to people who don't sign in (landing pages, embeds, a public API, an MCP server).
- Background work: anything slow, scheduled, or retried (AI calls, imports, exports, emails, syncs).
- Decisions locked with the user: choices that are settled and shouldn't be relitigated.
- Out of scope for v1.
- One app, one service. A single Nuxt app (dashboard, marketing site, API, public pages) deployed as one Render web service with a persistent disk. Split only when a real constraint forces it.
- The dashboard uses the public API. The UI calls the same
/v1handlers that integrations do, same-origin. No separate internal API, no BFF. - Boring, durable data. SQLite in WAL mode on a persistent disk, Prisma for schema and migrations, files on disk behind a small storage interface. Swapping to Postgres + S3 later must stay a contained change.
- One schema, many uses. zod schemas in
shared/validate requests, drive forms, generate OpenAPI components and define AI structured output. - Explicit imports, no relative paths. Every import names its source through an alias (
#root/,#server/,#shared/,~/). No auto-imports, no../. - Framework-agnostic server core.
server/utils/**andserver/database/**never import the Nitro runtime, so the same code runs in HTTP handlers, job worker threads, scripts, tests and the Prisma CLI. - Loosely coupled functions. Every function takes one object argument and declares only the properties it uses (see §5).
- Semantic names everywhere. Names say what something is or means, never how it looks or where it sits (see §5).
- Everything resumable. A disk-backed Render service has brief downtime on deploy. Jobs and long tasks keep their state in the database and are safe to retry.
- Swappable vendors. Email, AI, storage and similar dependencies sit behind a small interface with a dev fallback (e.g. email prints to the console when no key is set).
- Comments explain why, not what. Pin a decision next to the code it affects ("Migrations run at start: the disk isn't mounted during build").
- Use the current LTS release of anything that has an LTS line (Node first of all), and the latest stable major of everything else.
- No pre-releases (
rc,beta,nexttags) in dependencies. - When two packages must agree (TypeScript and
vue-tsc, the Prisma CLI, client and adapter), use the newest version they all support, pin those packages to exactly the same version, and put a comment next to the pin saying why. - Check versions when the project starts and on each dependency upgrade, not from this document.
| Concern | Choice | Notes |
|---|---|---|
| Runtime | Node (current LTS), npm | "type": "module"; engines.node pinned to the LTS major |
| Framework | Nuxt (Nitro, node-server preset) |
SSR on; file-based pages and server routes |
| Language | TypeScript, strict |
Newest version vue-tsc supports |
| UI kit | @nuxt/ui |
Includes the dashboard components (MIT) |
| CSS | Tailwind CSS (via Nuxt UI) | Theme tokens in app/assets/css/main.css |
| Icons | Lucide via @iconify-json/lucide |
i-lucide-* |
| Fonts | @nuxt/fonts (bundled with Nuxt UI), self-hosted |
Configure in nuxt.config.ts → fonts.families |
| Charts | nuxt-charts |
Follows Nuxt UI colors and dark mode |
| Composables | @vueuse/core |
|
| Database | SQLite (WAL, 5s busy timeout, foreign_keys = ON) |
better-sqlite3 driver |
| ORM | Prisma + @prisma/adapter-better-sqlite3, exact-pinned together |
prisma.config.ts, ESM client generated into server/generated/prisma |
| Search | SQLite FTS5 via raw SQL | Virtual table created outside Prisma migrate |
| Validation | zod |
z.toJSONSchema for OpenAPI and AI schemas |
| Auth | passport + passport-local + passport-http-bearer |
Called from h3 handlers with session: false; our own DB sessions |
| Password hashing | @node-rs/argon2 |
|
| Background jobs | sidequest + @sidequest/sqlite-backend |
Separate jobs.db file |
| Scheduled work | Nitro tasks (experimental.tasks, scheduledTasks) |
|
| API docs | Nitro experimental.openAPI + Scalar |
|
resend behind an adapter |
Console fallback in dev | |
| AI | Provider interface; OpenAI Responses API first | Structured output via JSON Schema |
| Outbound HTTP | undici + an SSRF-safe fetch helper |
Never fetch user-supplied URLs without it |
| MCP (optional) | @modelcontextprotocol/sdk |
Served from the API host |
| Images | sharp |
|
| PDFs (optional) | @cantoo/pdf-lib (edit), unpdf (text) |
pdf-lib itself is unmaintained |
| Files (optional) | archiver (zip), csv-stringify, read-excel-file, qrcode |
|
| Tests | Vitest | Node environment |
| Scripts | tsx |
One-off CLIs in scripts/ |
| Bundling jobs | esbuild |
Standalone worker bundle (see §7) |
| Formatting | Prettier | See §5 |
| Hosting | Render: one web service + persistent disk | render.yaml blueprint |
One app answers on several hostnames. A Nitro middleware (server/middleware/00.host.ts) tags each request with a host role and refuses paths that host doesn't serve. Typical layout (drop what you don't need):
| Host | Serves | Auth |
|---|---|---|
{{domain}} (+ www. → 301) |
Marketing site, SEO files (sitemap.xml, robots.txt, llms.txt) |
Public, edge-cached |
app.{{domain}} |
Dashboard (SSR) + same-origin /v1/** |
Session cookie |
api.{{domain}} |
/v1/**, /docs (Scalar), /openapi.json, /mcp |
API key (Bearer) |
<public>.{{domain}} |
Tokenized public pages, embeds, etc. | Public |
- Unknown hosts (plain
localhost,*.onrender.comhealth checks) are treated as the app host. - Dashboard paths typed on the marketing domain redirect to the app host.
- Any URL that gets printed or shared permanently (QR codes, emailed links) lives on its own host whose base URL never changes.
*.localhost resolves to 127.0.0.1 in browsers and curl, so every host works locally with no /etc/hosts edits: http://app.localhost:3000, http://api.localhost:3000, http://site.localhost:3000.
npm install
cp .env.example .env
npx prisma migrate dev
npm run admin:create -- you@example.com "Your Name"
npm run dev.claude/launch.json defines a dev configuration (npm run dev, port 3000) and a second one on another port with the host URLs overridden, for running two copies side by side.
- One web service on the current Node LTS, paid plan (needed for the disk and edge caching), persistent disk mounted at
/var/data. - A disk pins the service to one instance and disables zero-downtime deploys. That's acceptable; it's why jobs must be resumable.
- Build:
npm ci && npm run build. Start:prisma migrate deploy && node .output/server/index.mjs. Migrations run at start because the disk isn't mounted during build or pre-deploy. - Health check:
GET /healthzrunsSELECT 1and returns{ ok: true }withno-store. - Edge caching set to "All files"; caching is then driven entirely by
Cache-Controlheaders the app sends (see §8). Responses withSet-Cookieare never cached, so public routes must never touch the session. - Secrets use
sync: falseinrender.yaml(set in the dashboard); generated secrets usegenerateValue: true. - Post-deploy checklist lives as comments at the top of
render.yaml: custom domains, edge caching, creating the first super-admin from the service shell.
# Render Blueprint — {{APP_NAME}}
#
# One web service runs everything (HTTP + Sidequest workers + Nitro cron) with
# a persistent disk for SQLite and files. A disk pins the service to a single
# instance and disables zero-downtime deploys; jobs are resumable so a deploy
# restart is safe.
#
# After the first deploy, in the Render dashboard:
# 1. Add custom domains: {{domain}}, www.{{domain}}, app., api.{{domain}}
# 2. Enable edge caching (Settings → Edge Caching → "All files").
# 3. Create the first super-admin from the service shell:
# npm run admin:create -- you@example.com "Your Name"
services:
- type: web
name: {{app_slug}}
runtime: node
plan: standard
region: oregon
buildCommand: npm ci && npm run build
# Migrations run at start: the disk isn't mounted during build/pre-deploy.
startCommand: npm run start:render
healthCheckPath: /healthz
disk:
name: data
mountPath: /var/data
sizeGB: 10
envVars:
# Current Node LTS major; keep in step with engines.node.
- key: NODE_VERSION
value: "24"
- key: NODE_ENV
value: production
- key: DATA_DIR
value: /var/data
- key: APP_URL
value: https://app.{{domain}}
- key: API_URL
value: https://api.{{domain}}
- key: SITE_URL
value: https://{{domain}}
- key: NITRO_RUN_BACKGROUND_WORKERS
value: "true"
- key: EMAIL_FROM
value: {{APP_NAME}} <noreply@mail.{{domain}}>
- key: RESEND_API_KEY
sync: false
- key: SIDEQUEST_DASHBOARD_USER
value: admin
- key: SIDEQUEST_DASHBOARD_PASSWORD
generateValue: trueEverything persistent lives under DATA_DIR (.data locally, /var/data on Render):
DATA_DIR/
db/app.db # application database
db/jobs.db # Sidequest queue (separate so polling doesn't contend with app writes)
files/ # uploads and generated files, keyed "{tenant_id}/{kind}/{id}/…"
exports/
backups/ # nightly VACUUM INTO snapshots, 7 kept
A NITRO_RUN_BACKGROUND_WORKERS flag decides whether a process runs Sidequest workers and Nitro cron. It is true on the single service. Moving workers to their own service later means SQLite → Postgres and disk files → S3-compatible storage; Prisma and the storage interface keep that change contained.
README.md The only doc at the root (plus agent files: CLAUDE.md / AGENTS.md)
docs/ Every other doc: SPEC.md, api-guide.md, runbooks, decision notes
app/ Nuxt frontend
app.config.ts Nuxt UI theme + component default variants
assets/css/main.css Tailwind + Nuxt UI imports, theme tokens
components/ PascalCase .vue; marketing pieces under components/site/
composables/ useApi, useAuth, use<Thing>
layouts/ default (dashboard), auth, public, site, …
middleware/ auth.global.ts
pages/ file-based routes
utils/ client-side helpers
server/
database/ Basic CRUD against the database, one file per resource
(things.ts: findThing, listThings, createThing, updateThing, …).
The only place Prisma queries are written.
utils/ Generic, reusable functions: db client, config, ids, errors, auth,
email, ai, jobs, storage, serializers, and the h3 helpers (api.ts,
auth.ts). Group by area in subfolders.
database/ and utils/ are used by Nitro AND by job worker threads, so
they must not import the Nitro runtime (nitropack/runtime,
useRuntimeConfig, useStorage); config comes from process.env.
middleware/ Numbered for order: 00.host, 01.security-headers, …, 10.auth
plugins/ Numbered: 00.database, 10.sidequest, 20.openapi
routes/v1/ REST API, file-based: index.get.ts, [id].patch.ts, [id]/publish.post.ts
routes/ Non-API routes: healthz, robots.txt, sitemap.xml, public assets
tasks/ Nitro scheduled tasks
generated/ Prisma client (git-ignored)
shared/
schemas/ zod schemas, one file per resource, barrel in index.ts
constants/ enums and fixed lists shared by app and server
jobs/ Sidequest job classes: <name>.job.ts
sidequest.jobs.ts Barrel exporting every job class
prisma/ schema.prisma + migrations/
scripts/ tsx CLIs (create-super-admin, evals, one-off maintenance)
tests/unit/ Pure logic
tests/integration/ Against a throwaway SQLite database
tests/fixtures/
render.yaml
Node subpath imports in package.json are the single source of truth. Node, tsx, esbuild, Vite/Vitest and Nitro all resolve them, so the same import works in routes, jobs, scripts and tests:
"imports": {
"#root/*": "./*",
"#server/*": "./server/*",
"#shared/*": "./shared/*"
}Rules:
- Never use relative imports (
./,../). Server, jobs, scripts and tests use#server/,#shared/and#root/; app code uses Nuxt's~/(theapp/folder) and#shared/. - Always include the
.tsextension on internal imports (allowImportingTsExtensionsis on). External packages don't take one. #root/is for files outsideserver/andshared/:#root/jobs/send-email.job.ts,#root/sidequest.jobs.ts.- If a tool ever fails to pick up the
package.jsonimports, mirror the same three entries innuxt.config.ts→aliasandvitest.config.ts→resolve.aliasrather than falling back to relative paths.
// Good
import { db } from '#server/utils/db.ts'
import { CreateThingRequest } from '#shared/schemas/index.ts'
import { SendEmailJob } from '#root/jobs/send-email.job.ts'
import { defineEventHandler } from 'h3'
// Bad: relative path
import { db } from '../../utils/db.ts'
// Bad: missing extension
import { db } from '#server/utils/db'Nuxt and Nitro auto-imports are turned off. Every function, composable and helper is imported where it's used, so a file's dependencies are visible at the top and the same code reads identically in a job, a script or a test.
// nuxt.config.ts
export default defineNuxtConfig({
// App: no auto-imported composables, utils or Vue APIs.
imports: { autoImport: false },
nitro: {
// Server: no auto-imported h3 helpers or server/utils exports.
imports: false,
},
})Where things come from once auto-imports are off:
| What | Import from |
|---|---|
defineEventHandler, readBody, getQuery, setResponseStatus, getCookie, … |
h3 |
defineNitroPlugin, defineTask, defineRouteMeta, useRuntimeConfig |
nitropack/runtime |
ref, computed, reactive, watch, … |
vue |
definePageMeta, navigateTo, useRoute, useAsyncData, useState, useSeoMeta, … |
#imports |
| Project composables and utils | ~/composables/….ts, ~/utils/….ts |
Vue components (yours and Nuxt UI's U*) are still registered automatically; they are components, not functions.
Prettier, 4-space indentation, no tabs. Add Prettier as a dev dependency with a .prettierrc:
{
"tabWidth": 4,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 120,
"arrowParens": "avoid",
"endOfLine": "lf"
}- TypeScript everywhere,
strict.<script setup lang="ts">in every component. - Sort imports: external packages first, then aliases (
#root/,#server/,#shared/,~/). - Small, named functions over clever one-liners. Early returns.
- Named exports only, except where Nuxt/Nitro require a default (
defineEventHandler,defineNitroPlugin,defineTask, pages, layouts). - Inline comments only for the non-obvious why.
- Log with a bracketed area prefix:
console.info('[jobs] …'),console.error('[api] … failed', error). - No barrel files except
shared/schemas/index.tsandsidequest.jobs.ts.
One object argument. Every function we write takes a single object, destructured in the signature. Adding, removing or reordering a parameter later never breaks a caller, and call sites read like named arguments.
// Good
sendInvite({ email, role, invitedBy })
// Bad: positional arguments
sendInvite(email, role, invitedBy)Functions that take nothing (db()) take no object. Callbacks whose shape is fixed by someone else (h3's defineEventHandler(event => …), Vue's computed(() => …), array.map(item => …), a vendor SDK) keep the shape they're given.
Declare only what the function uses. Parameters are the specific values the function needs, never a whole request body, API payload or database row passed through "just in case". A function coupled to a big type has to change whenever that type does, and it hides which fields actually matter. This matters most around complex third-party APIs (Stripe, Shopify, Spotify), where payload shapes are large and change between versions: pull out the fields at the boundary and pass those.
// Good: the function says exactly what it needs
createUser({ name, email })
// Bad: coupled to the whole request type
createUser(body as CreateUserRequest)
// Good: take the three fields from the Stripe object at the boundary
recordPayment({ amountCents: invoice.amount_paid, currency: invoice.currency, paidAt })
// Bad: the whole Stripe invoice leaks into our code
recordPayment(invoice)The one exception is a function whose whole job is mapping a record, such as a serializer (serializeThing({ thing })).
Complete JSDoc on every function, exported or not: a one-line summary, extra context if it's needed, an @param for every property of the argument object, @returns, and @throws when it throws on purpose.
/**
* Create a user with a hashed password and send their email confirmation.
*
* @param input.name - Display name.
* @param input.email - Login email; must not already be registered.
* @param input.password - Plain-text password, hashed before storage.
* @returns The created user row.
* @throws ApiError 409 `conflict` when the email is taken.
*/
export async function createUser({ name, email, password }: { name: string; email: string; password: string }) {
// …
}Where a function lives:
| Kind | Where | Example |
|---|---|---|
| Helper function: used by one route only | Same file as the route, below the handler | buildPublishSummary in [id]/publish.post.ts |
| Database function: basic CRUD for a resource | server/database/<resource>.ts |
findThing, createThing, archiveThing |
| Utility: generic and reused across routes, jobs or scripts | server/utils/ |
newId, parseBody, enqueueEmail, serializeThing |
A helper that a second route starts to need moves to server/utils/ (or server/database/ if it's a query) at that point, not before.
Name things for what they are or what they mean in the product, never for how they look, where they sit, or how they're implemented. If the design or the implementation changes, the name should still be right.
| Kind | Good | Bad |
|---|---|---|
| Variables | publishedAt, pendingInvites, isTrialExpired |
d2, list, flag, tmp |
| Booleans | is_, has_, can_ prefixes: can_write, has_more |
write, more, status2 |
| Functions | Verb + object: publishThing, findActiveSession |
handle, doStuff, process2 |
| Vue components | Role in the UI: ThingStatusBadge, InviteMemberModal |
GreenPill, LeftBox, Modal2 |
| CSS classes | Meaning: .thing-card__title, .is-overdue |
.blue-text, .mt-big, .left-col |
| CSS tokens | Role: --color-danger, --surface-muted |
--red, --gray-2 |
| Endpoints | Resource nouns + action verbs: POST /v1/things/{id}/publish |
POST /v1/doThing, /v1/thing2 |
| Parameters | Name the thing: brand_id, published_after, include_archived |
id2, b, filter, flag |
| Events, audit actions | thing.published, member.removed |
update1, changed |
| Env vars | PUBLIC_LINK_BASE_URL, SESSION_TTL_DAYS |
URL2, TTL |
Tailwind utility classes in templates are fine; any custom CSS class or token gets a semantic name.
- Files and folders in
server/,shared/,jobs/,scripts/,tests/: kebab-case (api-keys.ts,send-email.job.ts). - Vue components: PascalCase (
CopyLink.vue). Composables:useThing.ts. - Server routes: Nitro method suffixes (
index.post.ts,[id].delete.ts). - TypeScript variables and functions: camelCase. Types, classes, zod schemas: PascalCase (
Thing,CreateThingRequest,UpdateThingRequest), with a same-named type viaz.infer. - API and database fields are snake_case (
created_at,company_id), so Prisma rows, API JSON and form state look the same. Prisma models are PascalCase and@@mapto snake_case tables.
server/utils/config.ts reads process.env directly (no useRuntimeConfig) so it works in every context. It loads .env itself for scripts and tests, never overriding existing variables. Values are exposed as getters with local-dev defaults:
export const config = {
get appUrl() {
return env('APP_URL', 'http://app.localhost:3000')
},
get resendApiKey() {
return env('RESEND_API_KEY')
},
// …
}runtimeConfig.public in nuxt.config.ts only holds what the browser needs (host URLs for cross-links).
db()inserver/utils/db.tsreturns a lazily created, process-wide Prisma client (better-sqlite3 adapter, 5s timeout). A Nitro plugin runsPRAGMA journal_mode = WALandPRAGMA foreign_keys = ONat boot.- Queries live in
server/database/<resource>.ts, never inline in routes or jobs. Each file holds the basic CRUD for one resource, with the tenant scope as a parameter:
import { db } from '#server/utils/db.ts'
import { newId } from '#server/utils/ids.ts'
/**
* Create a thing owned by a company.
*
* @param input.companyId - Owning company (tenant).
* @param input.name - Display name.
* @param input.notes - Optional free-text notes.
* @returns The created thing row.
*/
export function createThing({ companyId, name, notes }: { companyId: string; name: string; notes?: string | null }) {
return db().thing.create({
data: { id: newId({ kind: 'thing' }), company_id: companyId, name, notes: notes ?? null },
})
}
/**
* Find one non-archived thing within a company.
*
* @param input.companyId - Company the caller is acting in; rows from other companies are never returned.
* @param input.thingId - The thing's id.
* @returns The thing row, or null when it doesn't exist in this company.
*/
export function findThing({ companyId, thingId }: { companyId: string; thingId: string }) {
return db().thing.findFirst({ where: { id: thingId, company_id: companyId, archived_at: null } })
}- Schema header comment states the conventions: snake_case fields, IDs generated in app code.
- IDs: prefixed, time-sortable strings (ULID layout, Crockford base32), e.g.
usr_01k6x3…, fromnewId({ kind }). A singleID_PREFIXESmap inserver/utils/ids.tslists every kind. Sorting by id sorts by creation time, which makes cursor pagination cheap. - Timestamps:
created_at @default(now()),updated_at @updatedAt. Soft delete withdeleted_at/archived_atwhere users can delete things; a cleanup task purges later. - Flexible settings go in a
settings Json?column, validated by zod in app code. - Every tenant-owned query includes the tenant id in its
where(findFirst({ where: { id, company_id: ctx.company_id } })), never justid. - Migrations:
npm run db:migrateafter editingschema.prisma. Never edit an applied migration. - FTS5 (if needed): the virtual table is created idempotently at boot and declared as external tables in
prisma.config.tsso migrate ignores it; keep the index in sync inside the same transaction as writes.
Every /v1 route follows the same shape: imports, route meta, the handler, then any helper functions used only by this route.
import type { H3Event } from 'h3'
import { setResponseStatus } from 'h3'
import { defineRouteMeta } from 'nitropack/runtime'
import { createThing } from '#server/database/things.ts'
import { defineApiHandler, parseBody, requestIp } from '#server/utils/api.ts'
import { recordAudit } from '#server/utils/audit.ts'
import type { AuthActor } from '#server/utils/auth.ts'
import { requireRole } from '#server/utils/auth.ts'
import { serializeThing } from '#server/utils/serializers/things.ts'
import { CreateThingRequest } from '#shared/schemas/index.ts'
defineRouteMeta({
openAPI: {
tags: ['Things'],
summary: 'Create a thing',
requestBody: {
required: true,
content: { 'application/json': { schema: { $ref: '#/components/schemas/CreateThingRequest' } } },
},
responses: {
201: {
description: 'Thing created',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Thing' } } },
},
},
},
})
export default defineApiHandler(async event => {
const { ctx } = requireRole({ event, minimum: 'editor' })
const body = await parseBody({ event, schema: CreateThingRequest })
const thing = await createThing({ companyId: ctx.company_id, name: body.name, notes: body.notes })
await auditThingCreated({ event, companyId: ctx.company_id, actor: ctx.actor, thingId: thing.id, name: body.name })
setResponseStatus(event, 201)
return serializeThing({ thing })
})
/**
* Record the creation of a thing in the audit log.
*
* Helper function: only this route uses it, so it lives here, below the handler.
*
* @param input.event - The request, for the caller's IP.
* @param input.companyId - Company the thing belongs to.
* @param input.actor - The user or API key that created it.
* @param input.thingId - Id of the created thing.
* @param input.name - Name it was created with.
* @returns Resolves once the entry is written.
*/
async function auditThingCreated({
event,
companyId,
actor,
thingId,
name,
}: {
event: H3Event
companyId: string
actor: AuthActor
thingId: string
name: string
}) {
await recordAudit({
companyId,
actor,
action: 'thing.created',
entityType: 'thing',
entityId: thingId,
changes: { name },
ip: requestIp({ event }),
})
}defineApiHandler(inserver/utils/api.ts) setscache-control: private, no-storeand maps errors:ApiError→ its status,ZodError→ 422 withdetails: [{ path, message }], h3 4xx → passthrough, anything else → logged 500.- Return plain objects. h3 JSON-encodes whatever a handler returns (and sets
content-type: application/json), so never callJSON.stringifyorsendyourself. - Error shape is always
{ error: { code, message, details? } }. Helpers inserver/utils/errors.ts:badRequest,unauthorized,forbidden,notFound,conflict,tooManyRequests. Errorcodes are semantic snake_case strings (invalid_api_key,validation_error). parseBody/parseQueryvalidate with shared zod schemas.- Serializers per resource (
serializeThing({ thing }), inserver/utils/serializers/) define the public shape. This is separate from JSON encoding: a serializer chooses which fields go out, so internal columns (password_hash,key_hash, storage paths,deleted_at) never leak and a new column isn't public until it's added on purpose. It also turns stored values into API values (storage paths → public URLs, JSON columns parsed and defaulted through zod) and adds computed fields (counts, flags). Never return a raw Prisma row. - Lists return
{ data, next_cursor, has_more }(listOf(Item)inshared/schemas/common.ts), cursor = last id. - A catch-all
server/routes/v1/[...path].tsreturns the JSON 404 instead of an HTML page. - Every mutation writes an audit log entry (actor, action
thing.verb, entity, changes, IP). - Client IP: right-most
X-Forwarded-Forentry (the one Render's proxy added).
- Nitro
experimental.openAPIwithproduction: 'runtime', the full document at/_openapi.jsonand Scalar at/_scalar(app host only).docs/api-guide.mdis read intoopenAPI.meta.description. - Route meta only accepts static literals, so routes reference
#/components/schemas/<Name>. A Nitro plugin fillscomponents.schemasfrom theopenapiSchemasmap inshared/schemas/index.tsviaz.toJSONSchema, and adds tags and security schemes. - A curated public document (
/openapi.json+/docson the API host) lists only the endpoints meant for integrators. - A unit test fails if any
/v1route lacksdefineRouteMeta.
- Sessions: our own
sessiontable. The cookie ({{app_slug}}_session) holds an opaque ~256-bit token; the database stores only its SHA-256.httpOnly,sameSite: lax,securein production, host-only to the app host. - Passwords: argon2 via
@node-rs/argon2, minimum 10 characters. - API keys:
{{app_slug}}_live_+ 40 random base62 characters; store the SHA-256 and a short visible prefix; show the full key once. Optional scopes (read / read_write, subset of resources). - Other secrets (invites, password resets, email confirmations): same opaque-token-plus-hash pattern, with TTLs from config.
server/middleware/10.auth.tsresolves the caller into a singleevent.context.auth(AuthContext) from either a Bearer key or the session cookie. Routes decide what's required withrequireAuth,requireUser,requireRole({ event, minimum: 'admin' }),requireSuperAdminfrom#server/utils/auth.ts.- CSRF: every non-GET request without an API key must carry an
Originmatching the app host. - Compare secrets with
timingSafeEqual. - Per-key in-memory rate limits with
X-RateLimit-*headers (fine on a single instance).
01.security-headers.ts:x-content-type-options: nosniff,referrer-policy: strict-origin-when-cross-origin, a restrictivepermissions-policy, HSTS in production.- Request size limits in middleware.
- Any server-side fetch of a user-supplied URL goes through
safeFetch(blocks private/loopback addresses, follows redirects manually, enforces a size cap). - Storage keys are resolved under the storage root and rejected if they escape it.
- Redirect targets from query strings must match
/^\/(?![/\\])/(same-site paths only). - Never print invite/reset links to production logs: the email adapter refuses the console fallback when
NODE_ENV=production.
Each external service gets a tiny interface in server/utils/<area>/ plus a registry function that picks the implementation from config:
- Email (
server/utils/email/):EmailProvider { name, send({ to, subject, html, text }) },ResendProvider,ConsoleProvider(dev). Messages always havehtmlandtext. Sending happens in a job, never inline in a request. - AI (
server/utils/ai/):AiProvider { extractDocument(), completeJson() }, chosen byAI_PROVIDER/AI_MODEL/AI_FALLBACK_MODEL. Structured output from zod → JSON Schema. Instructions live as numbered Markdown files (instructions/default/00-overview.md,10-…) so they can be edited, versioned and overridden per tenant. Use a cheap default model and retry with the fallback model only when the result is low-confidence. Keep an eval script (npm run eval:<thing>) that runs against local fixtures and scores the output. - Storage (
server/utils/storage.ts):putFile({ key, data }),readStoredFile({ key }),streamFile({ key }),fileExists({ key }), … over relative keys. Local disk now; S3/R2 later.
- One class per job in
jobs/<name>.job.ts, extendingJobwith arun(params)method. Params are plain JSON (usually just an id); the job loads state from the database so it's idempotent and resumable. - Every job class is exported from
sidequest.jobs.ts. Never rename a job class while jobs of that name may be queued; re-export the old name as an alias. - Jobs only import from
#server/utils/**,#server/database/**and#shared/**. - Enqueue through typed helpers in
server/utils/jobs/enqueue.tsthat set queue, attempts and timeout:
import { SendEmailJob } from '#root/jobs/send-email.job.ts'
import { Sidequest } from '#server/utils/jobs/sidequest.ts'
/**
* Queue one transactional email; retried up to 5 times on provider errors.
*
* @param input.to - Recipient address.
* @param input.subject - Subject line.
* @param input.html - HTML body.
* @param input.text - Plain-text body.
* @returns The queued Sidequest job.
*/
export function enqueueEmail({ to, subject, html, text }: { to: string; subject: string; html: string; text: string }) {
return Sidequest.build(SendEmailJob).queue('email').maxAttempts(5).enqueue({ to, subject, html, text })
}- Queues have small, explicit concurrency (SQLite has one writer): e.g.
email2,default2, a slow/expensive queue 2. manualJobResolution: true: worker threads import a standalone esbuild bundle ofsidequest.jobs.ts. In production the Nitrocompiledhook writes it to.output/server/sidequest.jobs.mjs; in dev a plugin rebuilds it into.nuxt/on start. esbuild resolves the#aliases frompackage.json. Native modules, Prisma and Sidequest are external;keepNames: truebecause jobs resolve by class name.- Set
nitro.externals.trace: false: Sidequest loads its driver, migrations and dashboard from disk at runtime, which tracing misses. Render runs.outputfrom the build checkout, so packages resolve fromnode_modules. - The Sidequest dashboard runs with basic auth and is proxied at
/admin/jobsfor super-admins only. Sidequest.start()whenNITRO_RUN_BACKGROUND_WORKERSis true, elseSidequest.configure()(enqueue only). Stop on Nitroclose.
Declared in nitro.scheduledTasks (cron, UTC; comment any timezone math). Each task imports defineTask from nitropack/runtime and returns early with 'skipped (workers disabled on this instance)' when workers are off. Defaults for every project:
| Task | When | Does |
|---|---|---|
cleanup |
hourly | Expired sessions, invites, resets, exports; purge files of soft-deleted rows past retention |
backup |
nightly | VACUUM INTO snapshots of app.db and jobs.db into DATA_DIR/backups, keep 7 |
Set headers explicitly; the CDN does what they say.
| Path | Cache-Control |
|---|---|
/_nuxt/** and other content-hashed assets |
public, max-age=31536000, immutable |
/v1/**, dashboard HTML |
private, no-store |
| Marketing pages (GET) | public, max-age=300, s-maxage=3600, stale-while-revalidate=86400 |
| Public pages whose views you count | private, no-store (or cache and count with a beacon) |
/healthz, 404s |
no-store |
Static rules go in routeRules; per-host rules in the host middleware.
nuxt.config.ts:modules: ['@nuxt/ui', 'nuxt-charts'],css: ['~/assets/css/main.css'],ui.theme.colorslists the semantic colors (primary,secondary,success,info,warning,error,neutral), one Google font viafonts.families(self-hosted), favicon SVG + apple-touch-icon inapp.head.app.config.ts: pick a Nuxt UI theme preset (primary + neutral color) and setdefaultVariantsso the app has one consistent look (e.g.variant: 'soft'on buttons, badges and every input type). Component slot overrides go here too.- Use Nuxt UI's semantic colors (
color="error",text-muted,bg-elevated) rather than raw palette colors (text-red-500), so theming and dark mode follow automatically. main.css:
@import "tailwindcss";
@import "@nuxt/ui";
@theme {
--font-sans: 'Figtree', sans-serif;
}
:root {
--ui-radius: 0.75rem;
}
/* Tailwind v4 dropped the pointer cursor on buttons; restore it for every interactive control. */
@layer base {
button:not(:disabled),
[role="button"]:not([aria-disabled="true"]),
[role="switch"]:not([aria-disabled="true"]),
[role="tab"]:not([aria-disabled="true"]),
[role="option"]:not([aria-disabled="true"]),
[role="menuitem"]:not([aria-disabled="true"]),
select:not(:disabled) {
cursor: pointer;
}
}- Dark mode is supported from day one: override
--ui-bg,--ui-bg-muted, etc. under:root, .lightand.dark. Marketing screenshots come in light and dark variants (*.webp,*-dark.webp). - Dashboard layout uses Nuxt UI's dashboard components (
UDashboardGroup,UDashboardSidebar,UDashboardPanel,UDashboardNavbar).
useApi()(~/composables/useApi.ts) returns a fetcher bound to/v1, called asapi({ path, method, body, query }), that forwards cookies during SSR (useRequestFetch) and adds tenant headers. Pages use it insideuseAsyncDatafor reads and directly for mutations.apiErrorMessage({ error, fallback })turns the API error shape into a user-facing message (first validation detail, else the message).- Plain links that can't send headers (downloads, images) carry context in a query param via an
apiLink()helper.
UForm with the same zod schema the server validates against. With auto-imports off, everything is imported explicitly:
<script setup lang="ts">
import type { FormSubmitEvent } from '@nuxt/ui'
import { reactive, ref } from 'vue'
import type { z } from 'zod'
import { definePageMeta, navigateTo, useSeoMeta } from '#imports'
import { LoginRequest } from '#shared/schemas/index.ts'
import { apiErrorMessage, useApi } from '~/composables/useApi.ts'
definePageMeta({ layout: 'auth', public: true })
useSeoMeta({ title: 'Log in · {{APP_NAME}}' })
const api = useApi()
const credentials = reactive({ email: '', password: '' })
const errorMessage = ref<string | null>(null)
const isSubmitting = ref(false)
/**
* Log in with the validated form values, then go to the dashboard.
*
* `UForm`'s `@submit` callback, so it takes the event shape Nuxt UI gives it.
*
* @param event - Submit event carrying the zod-validated form data.
* @returns Resolves after navigation, or once the error message is shown.
*/
async function submitLogin(event: FormSubmitEvent<z.output<typeof LoginRequest>>) {
errorMessage.value = null
isSubmitting.value = true
try {
await api({ path: '/auth/login', method: 'POST', body: { email: event.data.email, password: event.data.password } })
await navigateTo('/')
} catch (error) {
errorMessage.value = apiErrorMessage({ error })
} finally {
isSubmitting.value = false
}
}
</script>app/middleware/auth.global.tsloads/v1/auth/meonce, redirects to/login?redirect=…when signed out, and enforces page meta flags declared on#app'sPageMeta(public,superAdmin).- Layouts by audience:
default(dashboard),auth,onboarding,public,site(marketing). useSeoMetaon every page; title formatPage · {{APP_NAME}}.- Page paths are semantic and readable (
/settings/team,/things/{id}), never internal names or numbers. - Marketing pages are listed in one shared constant (
shared/constants/site.ts) that feeds the host router, sitemap and nav, so a new page is routable once listed.
Include the ones the product needs; each has a known shape.
company(tenant) →membership(user, role, optional resource restriction) →user. Roles:owner > admin > editor > viewer, checked withroleAtLeast({ role, minimum }).- Dashboard URLs name the tenant (
/c/{company_slug}/…). The client sends it asX-Company-Id(or?_company=on plain links), so tabs on different tenants don't interfere. The session only remembers the last-used tenant for bare URLs. - Platform super-admins (flag on
user) manage tenants;scripts/create-super-admin.tsbootstraps the first one and prints a set-password link. - Invites by email with expiring tokens; self-serve signup → email verification → onboarding wizard → trial plan (
plan,trial_ends_aton the tenant, limits inshared/constants/pricing.ts). - An integration test proves tenant isolation (tenant A can't read or write tenant B's rows through any route).
- API keys created in the dashboard; the same
/v1routes serve integrators on the API host. - An MCP server at
api.{{domain}}/mcp(@modelcontextprotocol/sdk) exposing a few task-level tools that callserver/utilsfunctions. Accepts an API key as Bearer, or OAuth (dynamic client registration,/.well-known/oauth-*) for Claude/ChatGPT connectors. llms.txton the marketing host.
Indexed raw usage_event rows (company_id, event_type, created_at, meta JSON). Summary and timeseries endpoints feed nuxt-charts on the overview page. Add a daily rollup table only when volume requires it.
POST /v1/exports creates a row and enqueues an ExportJob that streams a ZIP (archiver) plus a CSV (csv-stringify) into DATA_DIR/exports; tokenized download link with a 7-day expiry; email when ready.
vitest.config.ts:include: ['tests/**/*.test.ts'],environment: 'node'. Vitest resolves the#aliases frompackage.json; tests import with them like any other file (#server/utils/ids.ts), never relative paths.- Unit tests for pure logic in
server/utilsandshared(parsing, normalization, permissions, host routing, id generation, OpenAPI coverage). - Integration tests create a temp dir, point
DATA_DIRandDATABASE_URLat it, runnpx prisma migrate deploy, then dynamically import#server/utils/…modules. Mock#server/utils/jobs/enqueue.tsto capture emails and jobs instead of running them; mock outbound fetches. Clean up inafterAll. - Name the test file after the behaviour (
signup.test.ts,isolation.test.ts) and start it with a one-line comment saying what it covers. - Large or private fixtures (real customer documents) are git-ignored and copied in locally.
npm run typecheckandnpm testpass before every commit.
{
"type": "module",
"engines": {
"node": ">=24 <25"
},
"imports": {
"#root/*": "./*",
"#server/*": "./server/*",
"#shared/*": "./shared/*"
},
"scripts": {
"dev": "nuxt dev",
"build": "nuxt build",
"start": "node .output/server/index.mjs",
"start:render": "prisma migrate deploy && node .output/server/index.mjs",
"preview": "nuxt preview",
"postinstall": "nuxt prepare && prisma generate",
"db:migrate": "prisma migrate dev",
"typecheck": "nuxt typecheck",
"test": "vitest run",
"test:watch": "vitest",
"format": "prettier --write .",
"admin:create": "tsx scripts/create-super-admin.ts"
}
}engines.node and Render's NODE_VERSION both track the current Node LTS major.
# Local development defaults. Copy to .env.
# Hosts: *.localhost resolves to 127.0.0.1 in browsers and curl.
APP_URL=http://app.localhost:3000
API_URL=http://api.localhost:3000
SITE_URL=http://site.localhost:3000
# Persistent data (SQLite files, uploads). Render: /var/data
DATA_DIR=.data
# Email (Resend). Without a key, emails are logged to the console.
RESEND_API_KEY=
EMAIL_FROM="{{APP_NAME}} <noreply@mail.{{domain}}>"
# Background workers (Sidequest + Nitro cron) run in this process.
NITRO_RUN_BACKGROUND_WORKERS=true
SIDEQUEST_DASHBOARD_USER=admin
SIDEQUEST_DASHBOARD_PASSWORD=change-me
# AI (optional)
AI_PROVIDER=openai
AI_MODEL=
AI_FALLBACK_MODEL=
OPENAI_API_KEY=node_modules
.nuxt
.output
.nitro
.cache
.data
dist
logs
*.log
.env
.env.*
!.env.example
.DS_Store
server/generated
compatibilityDateset to the project start date.imports: { autoImport: false }andnitro.imports: false(see §4).routeRulesfor/_nuxt/**(immutable) and/v1/**(private, no-store).nitro.preset: 'node-server',experimental: { openAPI: true, tasks: true },scheduledTasks,openAPIconfig,externals.trace: false, and thecompiledhook that writes the jobs bundle.typescript.tsConfig.compilerOptions.allowImportingTsExtensions: true(needed for.tsimport extensions, and the Prisma client is generated as TypeScript with.tsimports).
{
"files": [],
"references": [
{ "path": "./.nuxt/tsconfig.app.json" },
{ "path": "./.nuxt/tsconfig.server.json" },
{ "path": "./.nuxt/tsconfig.shared.json" },
{ "path": "./.nuxt/tsconfig.node.json" }
]
}README.mdlives at the root and is the only doc there (agent instruction files likeCLAUDE.md/AGENTS.mdsit beside it). It covers a one-paragraph pitch, feature list, stack line, local setup, the host table for local URLs, project layout, commands, and a pointer to deploy notes.- Everything else lives in
docs/:docs/SPEC.md: product and technical spec, starting from this template. Numbered sections; a "Decisions locked with the user" list; an "Implementation status" section kept current.docs/api-guide.md: integrator-facing intro (auth, errors, pagination, rate limits), rendered at the top of the API reference.- Runbooks, decision notes, design docs, delivery plans: one file each, semantic kebab-case names (
docs/deploy-runbook.md, notdocs/notes2.md).
- Update docs in the same change as the code they describe.