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

Terminal
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:

Terminal
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 dev runs can make neighbouring routes 404 (Turbopack drops them). touch the affected page.tsx/route.ts or 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 in overflow-x-auto.
  • Money in integer minor units; format with Intl.NumberFormat(undefined, { style: "currency", currency }).

Database access

TS
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 when DB_SCHEMA_READY=1. Call it before touching the table.
  • Add public_id with ensurePublicId("table") if the record appears in URLs.

Writing an API route

TS
// 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

  1. Add the key to ROW_TYPES in src/lib/ott-schema.ts.
  2. Resolve it in src/lib/ott/catalog.ts (where pageRows maps row_type to a query), using the shared visibility filter so maturity, availability, blocks and country rules apply.
  3. Add it to the Merchandising row-type picker in the admin.
  4. Optionally seed it in scripts/seed-ott.ts.

Add a streaming setting

  1. Add the field, default and clamping to StreamingSettings, STREAMING_DEFAULTS and cleanStreamingSettings() in src/lib/ott/settings.ts.
  2. Add the input to src/app/admin/(panel)/settings/streaming.
  3. Read it with getStreamingSettings() where it applies.

Add a lifecycle email

  1. Add a template to OTT_EMAILS in src/product/content.ts (inserted lazily if missing).
  2. Send with sendAppEmail(slug, email, vars). For marketing-type messages, follow src/lib/ott/lifecycle.ts: claim in member_message_log first, respect templateOptIn(), and keep batches bounded.
  3. If it runs on a schedule, call it from /api/v1/cron.

Add a column to titles

  1. ALTER TABLE titles ADD COLUMN IF NOT EXISTS … in ensureCatalogueSchema().
  2. Admin: the Titles editor (src/components/admin/ott/TitlesManager.tsx) and src/lib/ott/admin.ts save path; re-validate server-side.
  3. Storefront: map it in toCard() / titleDetail() in catalog.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.ts collects t("…") strings into src/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-only so it can be unit-tested (see match.ts, subtitles.ts, billing-dates.ts).
  • The e2e journey (tests/e2e/journey.test.mjs) signs in as standard@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