Chrysolites Tech Academy

Building React Apps: Weather, Music and Video · Course book

Chapter 4: A Video Platform with Next.js

Pairs with Lesson 4: A Video-Sharing Platform with Next.js 15

A video-sharing platform is one of the most demanding apps a web developer can build. Creators upload large files that must be processed into streamable formats; the app must track each video's state from upload to ready; a studio lets creators edit titles, descriptions, thumbnails and visibility; viewers browse by category with endlessly loading lists; and modern platforms add AI features such as generated titles and thumbnails. This chapter explains how such a platform is built with Next.js 15 and React, Tailwind CSS, Clerk for authentication, a PostgreSQL database accessed through Drizzle, tRPC for type-safe APIs, Mux for video and background jobs for slow AI tasks. Each section works through the key logic, from data modelling and webhooks to pagination and job processing.

The stack and the project layout

Each tool in the stack has one clear job.

ToolRole in the app
Next.js 15 (App Router)Pages, layouts, server components and API routes
Tailwind CSS with a component libraryStyling and ready-made accessible components such as sidebars and dialogs
ClerkSign-in, user accounts and session tokens
PostgreSQL with Drizzle ORMTables for users, videos and categories, with typed queries
tRPC with React QueryType-safe procedures between server and client, with caching
MuxVideo upload, encoding, streaming and thumbnails
A background job serviceLong-running AI tasks outside the request cycle

The project is organised by feature modules, for example modules/videos, modules/studio and modules/categories, each holding its own UI components, server procedures and types, while the app folder contains only thin route files. The basic layout has a top navigation bar with a search box and sign-in button, and a collapsible sidebar with sections for home, subscriptions and the user's own content. Route groups let the public site and the creator studio use different layouts without affecting their URLs.

Users, the database and webhooks

Clerk owns the accounts, but the app's own database needs a users table so that videos can reference their creators. Keeping the two in step is done with webhooks: whenever a user is created, updated or deleted in Clerk, Clerk sends an HTTP request to an endpoint in the app, which inserts, updates or deletes the matching row.

A webhook endpoint is public, so it must verify that requests really come from the sender. Providers sign each request: they compute a hash-based message authentication code, an HMAC, of the request body using a secret shared only with you, and send it in a header. The endpoint recomputes the HMAC with the same secret and accepts the request only if the two match. Changing even one character of the body produces a completely different code, so forged or altered requests are rejected. A tunnelling tool makes a local development server reachable from the internet so that webhooks can be tested before deployment.

The database schema is written in TypeScript with Drizzle, which generates SQL migrations from it. A videos table includes the title, description, the creator's user id, a category id, a visibility setting of public or private, and several Mux fields: the upload id, the asset id, the playback id, the processing status and the duration. Typed queries mean that a misspelt column name is a compile-time error, not a runtime surprise.

tRPC: type-safe procedures

tRPC lets the client call server functions, called procedures, as if they were local functions, with TypeScript checking inputs and outputs on both sides. A procedure declares its input with a validation schema, such as a string id or a cursor object, and returns data; the client calls it through a React Query hook, gaining caching, loading states and automatic refetching. Changing a procedure's return type immediately flags every component that uses it incorrectly.

Two kinds of procedure are created from a base: a public procedure for anyone, and a protected procedure whose middleware checks the Clerk session, loads the matching user row and adds it to the procedure's context, rejecting the call otherwise. A rate limit can be added to the protected base as well, so every protected call is limited per user. With Next.js server components, data can be prefetched on the server and hydrated on the client, so pages arrive with data already filled in, and suspense boundaries show skeletons for any parts still loading.

Categories, the studio and infinite loading

Video categories are seeded into the database with a script and shown as a horizontally scrolling row of chips; choosing one filters the home feed. The studio is the creator's area: a table of their videos with thumbnail, title, visibility, date and status, and a page for editing each video.

Lists that can grow without limit use infinite loading: the first page shows, say, 20 videos, and more are fetched as the user scrolls. The efficient way to page through a table is cursor pagination. Instead of saying "skip 400 rows and take 20", which forces the database to walk past all 400, each request says "give me 20 rows older than this cursor", where the cursor is the last row's timestamp and id. With an index on those columns, the database jumps straight to the right place. Fetching 21 rows and returning 20 reveals whether another page exists: if the 21st row is present, there is more to load and the cursor for the next page is the 20th row.

offset: 20 × page cursor: about 21 0200400 15101520 page numberrows read
Figure 4.1 — Rows read to fetch each page of 20. Offset pagination reads all earlier rows again; cursor pagination with an index reads only the page plus one.

On the client, an infinite query hook keeps the pages, and a small component at the bottom of the list watches whether it has scrolled into view, using the browser's intersection observer, and fetches the next page when it has, with a "load more" button as a fallback. When the last page arrives with no further cursor, the component stops watching and shows a short "end of list" note instead.

Video upload with Mux, and AI background jobs

Large video files should never pass through the app's own server. Instead, the app asks Mux for a direct upload URL, creates a video row with status "waiting", and the browser uploads the file straight to Mux. Mux then encodes the video into streaming formats and reports progress with webhooks, verified like Clerk's: when the asset is created the app stores the asset id; when it is ready, it stores the playback id, the duration and the thumbnail and preview addresses that Mux generates, and sets the status to ready; on errors or deletion it updates or removes the row. Mux reports durations in seconds; a duration of 754.2 seconds is displayed as 12:34.

Watching works differently from downloading a file. Mux encodes each video at several qualities and serves it with adaptive bitrate streaming: the player downloads the video in short segments and, before each one, picks the quality that the viewer's connection can sustain. On a fast connection it streams a high resolution; when the network slows, it drops to a lower one rather than pausing to buffer. A ready-made player component handles this, given only the playback id. Because the status is stored in the database, pages can show a "processing" placeholder for videos that are not ready yet instead of a broken player.

Visibility must be enforced wherever videos are read, not only hidden in the interface. Public procedures that list or fetch videos should filter for public, ready videos, while a creator viewing their own studio may see their private and processing ones. Writing that rule once in a shared query helper, rather than repeating it in every procedure, makes it much harder to leak a private video by mistake.

The video form in the studio edits the title, description, category and visibility, shows the player and offers to copy the video's link. Thumbnails can be chosen from Mux's generated image, uploaded through a file-upload service, or created by AI.

AI tasks, such as generating a title from the video's transcript or creating a thumbnail from a text prompt, can take many seconds, longer than a web request should wait and sometimes longer than serverless functions are allowed to run. They are therefore handed to a background job service: the procedure starts a workflow and returns immediately; the workflow calls the AI service, retries automatically if a step fails, and writes the result to the database when done; and the studio refetches to show it. Each workflow checks that the requesting user owns the video before changing anything.

Practice tasks

  1. Convert a Mux duration of 3,725 seconds into hours, minutes and seconds.
  2. With pages of 25 and offset pagination, how many rows does the database read to return page 12? About how many with cursor pagination?
  3. Explain the "fetch 21, return 20" trick and how the next cursor is chosen.
  4. Why must a webhook endpoint verify the signature, and what does it compare?
  5. Describe the life of a video row from the moment upload starts until it is ready to watch.
  6. Why are AI title and thumbnail generation run as background jobs rather than inside the procedure that requests them?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.