Technical Documentation
A developer's tour of how Streamix works: the request path, data access, the catalogue and viewer model, playback, billing, background work and extension points. For the file layout see Folder Structure.
Stack
| Concern | Implementation |
|---|---|
| Framework | Next.js 16 App Router (next dev --turbopack), React 19 server and client components |
| Language | TypeScript (strict), @/ alias → src/ |
| Styling | Tailwind CSS 3, CSS-variable tokens (ink-*, brand-*, secondary-*), cn() = tailwind-merge |
| Database | PostgreSQL via a tagged-template client (import sql from "@/lib/db"). Neon HTTP driver for *.neon.tech, postgres (postgres.js) for any other host. rawSql(query, params) for $1 queries. Prisma is generated but only used by a few legacy core screens. |
| Auth | jose JWTs in httpOnly cookies: member_session (members, 30 days or session-only), admin_token (admin, JWT_EXPIRES_IN, default 7 days). bcrypt passwords. |
| Storage | AWS SDK v3 S3 client over any S3-compatible bucket (src/lib/r2.ts) |
| Video | hls.js in the player; ffmpeg-static / ffprobe-static in the transcode worker |
| Email / push | nodemailer (SMTP) or provider add-ons; web-push (VAPID) |
Request flow
src/middleware.tshandles locale prefixes (/fr/browse→/browsewithx-locale: fr), setsx-pathnameand thelangcookie.- Server components in
src/app/(site)load data directly fromsrc/lib/**and render the first paint with data (Next 16 hydrates lazily, so anything needed before the first interaction is rendered on the server). - Client components call
/api/v1/**for interactions (My List, ratings, progress, account changes). - Route handlers follow one shape: auth first → validate and coerce input → owner-scoped SQL →
ok()/err()/serverErr().
The viewer
Every member query runs for a viewer, returned by getViewer() in src/lib/ott/profiles.ts:
const { viewer, profile, customerId } = await getViewer();
// viewer = { customerId, profileId, maxLevel, isKids, country? }
- The active profile is read from the
sx_profilecookie (web) or theX-Profile-Idheader (API clients) and is only accepted if it belongs to the signed-in account. maxLevelis the profile's maturity level, capped at 7 for Kids profiles.- API helpers in
src/lib/ott/api.ts:requireProfile()(401 without session, 409 without a profile) andrequireOwnProfile(publicId)for account pages.
Catalogue queries
src/lib/ott/catalog.ts builds every list through one visibility predicate:
status = 'published', insideavailable_from/available_until;- maturity level ≤ the viewer's
maxLevel; - not in the profile's blocked titles;
- country allow/deny lists, using the request country (
x-vercel-ip-country/cf-ipcountry).
Main functions: pageRows() and billboard() (browse pages), continueWatching(), top10(), myList(), moreLikeThis(), topPicks(), youWillLove(), browseGrid(), languageOptions(), titleDetail(), searchTitles() (trigram fallback via pg_trgm).
Rows are defined in browse_rows per page (home, tv, movies, kids, latest, genre) and resolved by row_type. Personalisation:
- Match % (
src/lib/ott/match.ts): 40-98 from how the title's genres and moods line up with what the profile watched, rated and saved. Unit-tested. - More Like This / Because You Watched use
title_similar, rebuilt by the cron (src/lib/ott/recommendations.ts): co-watch cosine similarity blended with genre/mood similarity, top 30 per title, at most every 6 hours. - Top 10 is a daily snapshot in
top10_snapshots, from hours watched over 7 days, with editor overrides kept.
Playback
src/lib/ott/playback.ts:
entitlement(customerId)finds a live subscription (activeorcancelled, not expired) and returns plan limits (max_streams,max_resolution).playbackFor()resolves the title or episode (resume target for series), checks maturity and availability, and returns the source, markers, next episode, tracks, resume position and limits.GET /api/v1/playback/[key]exposes it.- When the asset's HLS conversion is ready, the source is a capped master playlist for the plan's max height, and the uploaded MP4 is kept as a fallback. Otherwise the MP4 or HLS URL plays as stored.
POST /api/v1/playback/sessionstarts a session and refuses with 409 when live sessions (heartbeat in the last 90 s) already fill the plan's screens (unless disabled in Settings → Streaming). The player sendsPATCHheartbeats; a session ended elsewhere returns 410 and the player stops.POST /api/v1/playback/progresssaves position, duration and watched seconds per profile and title/episode. A play is complete within the credits or at 95 %.
Admins signed in to the back office can preview any title from the same browser; those sessions are not counted.
Video pipeline
- Upload: the admin requests a presigned PUT (
/api/v1/admin/upload/presign) and the browser uploads straight to the bucket (VideoUpload/MediaUpload). Large files never pass through the server. - Transcode (
src/lib/ott/transcode.ts,transcode-runner.ts,scripts/transcode-worker.ts):video_assets.transcode_statusis the queue (none → queued → processing → ready | failed). The worker claims a job withFOR UPDATE SKIP LOCKED, builds an H.264/AAC ladder (240p to 2160p, never above the source), 6-second segments, master playlists per plan cap and a seek-bar sprite withthumbnails.vtt, uploads toott/hls/<asset id>/<version>/and marks the asset ready. Leases expire after 10 minutes; up to 3 attempts. - Subtitles (
src/lib/ott/subtitles.ts,tracks.ts): SRT or VTT up to 2 MB is converted to clean WebVTT and written toott/subtitles/…. Audio tracks are stored as URLs and listed in the player, but not switchable in the browser.
Billing
src/lib/billing.ts: plans, coupons,quoteFor()(the only place an amount is computed),availableMethods(),memberBilling().src/core/payments/*:PaymentDrivercontract with built-in drivers (cod,bank,paypal) plus premium gateway drivers registered by add-ons.- Checkout:
/api/v1/checkout/quote→/checkout/subscription→ provider →/checkout/verify. Renewal:/api/v1/checkout/renew. A transaction's(provider, provider_ref)is unique, so a replayed return cannot grant access twice. src/lib/ott/renewal.ts:active → on_hold(period ended unpaid)→ expiredafter 30 days; paying extends from the old end date if still ahead, else from now. There is no stored-card charging.
Background work
/api/v1/cron (GET or POST, Authorization: Bearer <CRON_SECRET> or ?key=) runs in parallel, each task idempotent and bounded:
| Task | Source |
|---|---|
| "Remind me" notifications when a title goes live | runTitleReminders (src/lib/cron-tasks.ts) |
| Daily Top 10 | runTop10 |
| Recommendations rebuild | runRecommendations |
| Renewal reminder, on hold, expired emails | runSubscriptionLifecycle |
| AI translation backstop for blog posts | runTranslateContent |
| Weekly new-arrivals digest, new-season alerts | src/lib/ott/lifecycle.ts |
Lifecycle messages claim a row in member_message_log before sending, respect the member's communication settings for email and push, and always write the in-app notification.
Settings
getStreamingSettings()(src/lib/ott/settings.ts) reads thestreamingsection with safe defaults:max_profiles5,enforce_stream_limitstrue,still_watching_after3,hover_preview_delay_ms500,next_episode_countdown_seconds10,allowed_countries[],default_maturity_level18.- Integration credentials are encrypted in
integration_connections(src/lib/secrets.ts).
Extension points
- Add-ons (
src/product/addons/<id>): channel providers and feature plugins, bundled withnpm run addons:bundle. See the Add-on Development Guide. - Feature plugins can add admin pages (
/admin/x/...), public pages (/x/...) and API routes (/api/v1/ext/...). See the Plugin Development Guide. - API: every user-facing surface has a REST endpoint; regenerate the spec with
npm run gen:openapi.
Testing
npm test: unit tests intests/*.test.ts(billing dates, match score, subtitle conversion, validation, analytics ranges) run withtsx --test.npm run test:e2e: a Playwright (playwright-core) member journey against a running server (BASE_URL, demo memberstandard@streamix.test, local Chrome orCHROME_PATH).npx tsc --noEmit -p tsconfig.jsonfor type checking.
© CreativeCape Solutions · creative-cape.com · support@creative-cape.com