Developer Guide
How to work on the Streamix codebase: local setup, conventions, and recipes for common changes. Read Technical Documentation for how the system fits together.
Local setup
npm install
# create .env with at least DATABASE_URL and JWT_SECRET
npm run db:init
npm run dev # next dev --turbopack on http://localhost:3000
Then run /install, connect storage in admin, and seed demo data:
npx tsx scripts/seed-ott.ts
npx tsx scripts/seed-demo-users.ts
Useful commands:
| Command | What it does |
|---|---|
npx tsc --noEmit -p tsconfig.json (or npm run type-check) |
Type check. Run it after every change. |
npm run lint |
ESLint |
npm test |
Unit tests (tests/*.test.ts, node test runner via tsx) |
npm run test:e2e |
Browser journey against a running server (BASE_URL, local Chrome or CHROME_PATH) |
npm run gen:openapi |
Regenerate the API spec after adding or renaming routes |
npm run worker:transcode |
HLS worker (needs storage configured) |
npm run addons:bundle |
Regenerate add-on indexes after changing src/product/addons |
Dev-server gotchas
- Adding or moving a route folder while
next devruns can make neighbouring routes 404 (Turbopack drops them).touchthe affectedpage.tsx/route.tsor restart the dev server. - The first request to a new or edited route can take several seconds while it compiles.
- Next 16 hydrates lazily. Anything that must work before the first interaction (deep links like
?jbv=, the first page of admin lists, the player's source) must be rendered or passed from the server, not fetched in a mount effect.
Conventions
These rules are enforced in review (see CLAUDE.md and .claude/rules/).
Reuse the building blocks
| Need | Use |
|---|---|
| Confirm/delete dialog | ConfirmDeleteModal from @/components/ui/modal |
| Other dialogs | ModalBase + ModalHeader/ModalBody/ModalFooter |
| Toasts | useToast() from @/components/ui/Toast |
| Form inputs | @/components/form (InputField, SelectField, …) |
| Validation | validateForm / hasErrors from @/lib/validation |
| Skeletons | @/components/ui/Skeleton (admin), @/components/ott/skeletons (storefront) |
| Uploads | ImageUpload, MediaUpload, VideoUpload (presigned, direct to bucket) |
| Translation | useT() (client), getServerT() (server) |
| Class names | cn() from @/utils/cn |
Non-negotiables
- Every data-loading page shows a layout-shaped skeleton.
- Validate on the client for UX and on the server for trust. Disable submit buttons while saving.
- Every API route checks auth first and scopes queries to the owner. Admin routes call
requirePermission(action, resource). - Member queries are filtered for the active profile (
getViewer()), never just the account. - Wrap user-facing strings in
t(). No hardcoded brand names, currencies or countries. - Design tokens only (
ink-*,brand-*,font-display), no raw hex. - Responsive: gate multi-column grids behind
sm:/lg:/xl:, wrap tables inoverflow-x-auto. - Money in integer minor units; format with
Intl.NumberFormat(undefined, { style: "currency", currency }).
Database access
import sql, { rawSql } from "@/lib/db";
const rows = await sql`SELECT id, title FROM titles WHERE status = 'published' AND id = ${id}`;
const more = await rawSql("SELECT id FROM titles WHERE id = ANY($1)", [ids]);
- Parameterised queries only; never concatenate input into SQL or build table/column names from input.
- New tables or columns go in an idempotent
ensure*Schema()(CREATE TABLE IF NOT EXISTS,ADD COLUMN IF NOT EXISTS), cached per process and skipped whenDB_SCHEMA_READY=1. Call it before touching the table. - Add
public_idwithensurePublicId("table")if the record appears in URLs.
Writing an API route
// src/app/api/v1/my-list/[key]/route.ts (shape)
import { NextRequest } from "next/server";
import sql from "@/lib/db";
import { ok, err, serverErr } from "@/lib/api-helpers";
import { requireProfile, titleIdFor } from "@/lib/ott/api";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function PUT(_req: NextRequest, { params }: { params: Promise<{ key: string }> }) {
try {
const ctx = await requireProfile(); // 1) auth + active profile
if (ctx instanceof Response) return ctx;
const titleId = await titleIdFor((await params).key); // 2) validate input
if (!titleId) return err("Not found", 404);
await sql`INSERT INTO my_list (profile_id, title_id)
VALUES (${ctx.profile.id}, ${titleId}) ON CONFLICT DO NOTHING`; // 3) scoped write
return ok({ in_my_list: true });
} catch (e) { return serverErr(e); }
}
Rate-limit public writes and auth with rateLimit(key, limit, windowMs) from @/lib/rate-limit. Never trust amounts from the client; price with quoteFor() in @/lib/billing.
After adding routes, run npm run gen:openapi. Every member-facing screen should have a matching /api/v1 endpoint so a future app can use it.
Recipes
Add a new row type
- Add the key to
ROW_TYPESinsrc/lib/ott-schema.ts. - Resolve it in
src/lib/ott/catalog.ts(wherepageRowsmapsrow_typeto a query), using the shared visibility filter so maturity, availability, blocks and country rules apply. - Add it to the Merchandising row-type picker in the admin.
- Optionally seed it in
scripts/seed-ott.ts.
Add a streaming setting
- Add the field, default and clamping to
StreamingSettings,STREAMING_DEFAULTSandcleanStreamingSettings()insrc/lib/ott/settings.ts. - Add the input to
src/app/admin/(panel)/settings/streaming. - Read it with
getStreamingSettings()where it applies.
Add a lifecycle email
- Add a template to
OTT_EMAILSinsrc/product/content.ts(inserted lazily if missing). - Send with
sendAppEmail(slug, email, vars). For marketing-type messages, followsrc/lib/ott/lifecycle.ts: claim inmember_message_logfirst, respecttemplateOptIn(), and keep batches bounded. - If it runs on a schedule, call it from
/api/v1/cron.
Add a column to titles
ALTER TABLE titles ADD COLUMN IF NOT EXISTS …inensureCatalogueSchema().- Admin: the Titles editor (
src/components/admin/ott/TitlesManager.tsx) andsrc/lib/ott/admin.tssave path; re-validate server-side. - Storefront: map it in
toCard()/titleDetail()incatalog.ts.
Scripts
Put one-off and seed scripts in scripts/*.ts. Load .env with dotenv first, then await import("../src/lib/db") dynamically. Make them idempotent. Don't import modules that use server-only from a script (they only resolve inside Next). Run with npx tsx scripts/<name>.ts.
Translations
npx tsx scripts/extract-i18n.tscollectst("…")strings intosrc/data/i18n-source.json.- Translators work in admin → Localization → Languages; catalogues are stored in the bucket, with
translations/<lang>/as the shipped baseline. npx tsx scripts/upload-translations.ts [lang]publishes the repo catalogues to the bucket.
Testing
- Keep pure logic in modules without
server-onlyso it can be unit-tested (seematch.ts,subtitles.ts,billing-dates.ts). - The e2e journey (
tests/e2e/journey.test.mjs) signs in asstandard@streamix.test, picks a profile, opens a deep-linked title, plays and saves progress, loads the account pages, cancels and restarts the membership, and checks that member APIs refuse anonymous callers.
© CreativeCape Solutions · creative-cape.com · support@creative-cape.com