Skip to content

Instantly share code, notes, and snippets.

@drewbaker
Last active October 9, 2026 05:34
Show Gist options
  • Select an option

  • Save drewbaker/f19515fb14ec00d459ea5c3c9ed7810d to your computer and use it in GitHub Desktop.

Select an option

Save drewbaker/f19515fb14ec00d459ea5c3c9ed7810d to your computer and use it in GitHub Desktop.
spec_scaffold.md

Project Template: Nuxt + Nitro + SQLite on Render

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).


0. The product (fill this in)

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, /v1 resources 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.

1. Principles

  • 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 /v1 handlers 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/** and server/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").

2. Stack

Version policy

  • 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, next tags) 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.

Choices

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
Email 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

3. Hosting and environments

Hosts

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.com health 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.

Local development

*.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.

Production (Render)

  • 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 /healthz runs SELECT 1 and returns { ok: true } with no-store.
  • Edge caching set to "All files"; caching is then driven entirely by Cache-Control headers the app sends (see §8). Responses with Set-Cookie are never cached, so public routes must never touch the session.
  • Secrets use sync: false in render.yaml (set in the dashboard); generated secrets use generateValue: 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: true

Data on disk

Everything 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

Scaling path (not now)

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.


4. Project layout

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

Import aliases

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 ~/ (the app/ folder) and #shared/.
  • Always include the .ts extension on internal imports (allowImportingTsExtensions is on). External packages don't take one.
  • #root/ is for files outside server/ and shared/: #root/jobs/send-email.job.ts, #root/sidequest.jobs.ts.
  • If a tool ever fails to pick up the package.json imports, mirror the same three entries in nuxt.config.ts → alias and vitest.config.ts → resolve.alias rather 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'

No auto-imports

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.


5. Code style

Formatting

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.ts and sidequest.jobs.ts.

Functions

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.

Semantic naming

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.

Casing

  • 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 via z.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 @@map to snake_case tables.

6. Server conventions

Config

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).

Database

  • db() in server/utils/db.ts returns a lazily created, process-wide Prisma client (better-sqlite3 adapter, 5s timeout). A Nitro plugin runs PRAGMA journal_mode = WAL and PRAGMA foreign_keys = ON at 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…, from newId({ kind }). A single ID_PREFIXES map in server/utils/ids.ts lists every kind. Sorting by id sorts by creation time, which makes cursor pagination cheap.
  • Timestamps: created_at @default(now()), updated_at @updatedAt. Soft delete with deleted_at / archived_at where 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 just id.
  • Migrations: npm run db:migrate after editing schema.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.ts so migrate ignores it; keep the index in sync inside the same transaction as writes.

API handlers

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 (in server/utils/api.ts) sets cache-control: private, no-store and maps errors: ApiError → its status, ZodError → 422 with details: [{ 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 call JSON.stringify or send yourself.
  • Error shape is always { error: { code, message, details? } }. Helpers in server/utils/errors.ts: badRequest, unauthorized, forbidden, notFound, conflict, tooManyRequests. Error codes are semantic snake_case strings (invalid_api_key, validation_error).
  • parseBody / parseQuery validate with shared zod schemas.
  • Serializers per resource (serializeThing({ thing }), in server/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) in shared/schemas/common.ts), cursor = last id.
  • A catch-all server/routes/v1/[...path].ts returns 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-For entry (the one Render's proxy added).

OpenAPI

  • Nitro experimental.openAPI with production: 'runtime', the full document at /_openapi.json and Scalar at /_scalar (app host only). docs/api-guide.md is read into openAPI.meta.description.
  • Route meta only accepts static literals, so routes reference #/components/schemas/<Name>. A Nitro plugin fills components.schemas from the openapiSchemas map in shared/schemas/index.ts via z.toJSONSchema, and adds tags and security schemes.
  • A curated public document (/openapi.json + /docs on the API host) lists only the endpoints meant for integrators.
  • A unit test fails if any /v1 route lacks defineRouteMeta.

Auth

  • Sessions: our own session table. The cookie ({{app_slug}}_session) holds an opaque ~256-bit token; the database stores only its SHA-256. httpOnly, sameSite: lax, secure in 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.ts resolves the caller into a single event.context.auth (AuthContext) from either a Bearer key or the session cookie. Routes decide what's required with requireAuth, requireUser, requireRole({ event, minimum: 'admin' }), requireSuperAdmin from #server/utils/auth.ts.
  • CSRF: every non-GET request without an API key must carry an Origin matching the app host.
  • Compare secrets with timingSafeEqual.
  • Per-key in-memory rate limits with X-RateLimit-* headers (fine on a single instance).

Security baseline

  • 01.security-headers.ts: x-content-type-options: nosniff, referrer-policy: strict-origin-when-cross-origin, a restrictive permissions-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.

Vendor adapters

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 have html and text. Sending happens in a job, never inline in a request.
  • AI (server/utils/ai/): AiProvider { extractDocument(), completeJson() }, chosen by AI_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.

7. Background jobs and scheduled tasks

Sidequest jobs

  • One class per job in jobs/<name>.job.ts, extending Job with a run(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.ts that 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. email 2, default 2, a slow/expensive queue 2.
  • manualJobResolution: true: worker threads import a standalone esbuild bundle of sidequest.jobs.ts. In production the Nitro compiled hook writes it to .output/server/sidequest.jobs.mjs; in dev a plugin rebuilds it into .nuxt/ on start. esbuild resolves the # aliases from package.json. Native modules, Prisma and Sidequest are external; keepNames: true because 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 .output from the build checkout, so packages resolve from node_modules.
  • The Sidequest dashboard runs with basic auth and is proxied at /admin/jobs for super-admins only.
  • Sidequest.start() when NITRO_RUN_BACKGROUND_WORKERS is true, else Sidequest.configure() (enqueue only). Stop on Nitro close.

Nitro tasks

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

8. Caching

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.


9. Frontend conventions

Nuxt UI setup

  • nuxt.config.ts: modules: ['@nuxt/ui', 'nuxt-charts'], css: ['~/assets/css/main.css'], ui.theme.colors lists the semantic colors (primary, secondary, success, info, warning, error, neutral), one Google font via fonts.families (self-hosted), favicon SVG + apple-touch-icon in app.head.
  • app.config.ts: pick a Nuxt UI theme preset (primary + neutral color) and set defaultVariants so 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, .light and .dark. Marketing screenshots come in light and dark variants (*.webp, *-dark.webp).
  • Dashboard layout uses Nuxt UI's dashboard components (UDashboardGroup, UDashboardSidebar, UDashboardPanel, UDashboardNavbar).

Data fetching

  • useApi() (~/composables/useApi.ts) returns a fetcher bound to /v1, called as api({ path, method, body, query }), that forwards cookies during SSR (useRequestFetch) and adds tenant headers. Pages use it inside useAsyncData for 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.

Forms

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>

Routing and auth

  • app/middleware/auth.global.ts loads /v1/auth/me once, redirects to /login?redirect=… when signed out, and enforces page meta flags declared on #app's PageMeta (public, superAdmin).
  • Layouts by audience: default (dashboard), auth, onboarding, public, site (marketing).
  • useSeoMeta on every page; title format Page · {{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.

10. Optional modules

Include the ones the product needs; each has a known shape.

Multi-tenancy

  • company (tenant) → membership (user, role, optional resource restriction) → user. Roles: owner > admin > editor > viewer, checked with roleAtLeast({ role, minimum }).
  • Dashboard URLs name the tenant (/c/{company_slug}/…). The client sends it as X-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.ts bootstraps 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_at on the tenant, limits in shared/constants/pricing.ts).
  • An integration test proves tenant isolation (tenant A can't read or write tenant B's rows through any route).

Public API + MCP

  • API keys created in the dashboard; the same /v1 routes serve integrators on the API host.
  • An MCP server at api.{{domain}}/mcp (@modelcontextprotocol/sdk) exposing a few task-level tools that call server/utils functions. Accepts an API key as Bearer, or OAuth (dynamic client registration, /.well-known/oauth-*) for Claude/ChatGPT connectors.
  • llms.txt on the marketing host.

Usage analytics

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.

Exports

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.


11. Testing

  • vitest.config.ts: include: ['tests/**/*.test.ts'], environment: 'node'. Vitest resolves the # aliases from package.json; tests import with them like any other file (#server/utils/ids.ts), never relative paths.
  • Unit tests for pure logic in server/utils and shared (parsing, normalization, permissions, host routing, id generation, OpenAPI coverage).
  • Integration tests create a temp dir, point DATA_DIR and DATABASE_URL at it, run npx prisma migrate deploy, then dynamically import #server/utils/… modules. Mock #server/utils/jobs/enqueue.ts to capture emails and jobs instead of running them; mock outbound fetches. Clean up in afterAll.
  • 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 typecheck and npm test pass before every commit.

12. Files to start with

package.json (excerpt)

{
    "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.

.env.example

# 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=

.gitignore

node_modules
.nuxt
.output
.nitro
.cache
.data
dist
logs
*.log
.env
.env.*
!.env.example
.DS_Store
server/generated

nuxt.config.ts essentials

  • compatibilityDate set to the project start date.
  • imports: { autoImport: false } and nitro.imports: false (see §4).
  • routeRules for /_nuxt/** (immutable) and /v1/** (private, no-store).
  • nitro.preset: 'node-server', experimental: { openAPI: true, tasks: true }, scheduledTasks, openAPI config, externals.trace: false, and the compiled hook that writes the jobs bundle.
  • typescript.tsConfig.compilerOptions.allowImportingTsExtensions: true (needed for .ts import extensions, and the Prisma client is generated as TypeScript with .ts imports).

tsconfig.json

{
    "files": [],
    "references": [
        { "path": "./.nuxt/tsconfig.app.json" },
        { "path": "./.nuxt/tsconfig.server.json" },
        { "path": "./.nuxt/tsconfig.shared.json" },
        { "path": "./.nuxt/tsconfig.node.json" }
    ]
}

13. Documentation

  • README.md lives at the root and is the only doc there (agent instruction files like CLAUDE.md / AGENTS.md sit 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, not docs/notes2.md).
  • Update docs in the same change as the code they describe.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment