Netflix clone: video streaming app
A streaming web app with profiles, browse rows, a player that switches quality with your internet speed, "continue watching" and My List, built with free open-licensed movies.
Educational project inspired by Netflix. Skills101 is not affiliated with Netflix. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆Adaptive streaming: how HLS and FFmpeg turn one video into many qualities
- ◆Modelling a catalogue, profiles and watch progress
- ◆A fast browse UI with server components and scroll-snap rows
- ◆Protecting video files with expiring signed URLs
What you’ll build
- ✓Sign up, then up to 4 profiles per account
- ✓Home page with a hero banner and rows by genre
- ✓Player with automatic quality and resume-where-you-stopped
- ✓Continue watching, My List and search
Before you start
What you need
- •Comfortable with JavaScript/TypeScript and React basics (components, props, state).
- •Node.js 20+, PostgreSQL (or Docker) and FFmpeg installed.
ffmpeg -versionshould print a version. - •3–5 open-licensed films to stream, for example the Blender open movies (Big Buck Bunny, Sintel, Tears of Steel). They are CC BY, so credit them in the app footer and README.
How it fits together
- 1Browser → Next.js app (pages, server actions and API routes) → PostgreSQL through Prisma for users, profiles, titles and watch progress.
- 2Each film is encoded once by FFmpeg into HLS: small 6-second segments in two qualities plus .m3u8 playlist files that list them.
- 3The player (hls.js) reads the master playlist and keeps switching between 360p and 720p depending on the viewer's bandwidth.
- 4Video files are served through a route that checks an expiring signature, so a copied link stops working after a few hours.
Project structure
streamly/
├─ prisma/
│ ├─ schema.prisma
│ └─ seed.ts
├─ scripts/encode.sh # FFmpeg → HLS
├─ media/<slug>/ # master.m3u8, v0/, v1/ (NOT in public/)
├─ src/app/
│ ├─ (auth)/login, signup
│ ├─ profiles/page.tsx # "Who's watching?"
│ ├─ browse/page.tsx # hero + rows
│ ├─ title/[slug]/page.tsx
│ ├─ watch/[slug]/page.tsx # the player
│ ├─ media/[exp]/[sig]/[slug]/[...file]/route.ts
│ └─ api/progress/route.ts
└─ src/components/Player.tsx, Row.tsx, SearchBox.tsxStep-by-step guide
Step 1
Plan v1 and give the app its own name
Goal: A one-page plan, five screen sketches and a name that is not Netflix.
Before code, write down exactly what version 1 does. A good v1 is: sign up, pick a profile, browse rows, open a title, watch it with automatic quality, resume later, add to My List, search. Downloads, payments, TV apps and recommendations are "later" items.
Pick your own name and logo, for example “Streamly”. Your project is inspired by Netflix, but do not use their name, red N, fonts or artwork. Interviewers care that you understand the engineering, not that it looks identical.
Sketch five screens on paper: Login, Who's watching, Browse, Title details and Player. Next to each, list the data it needs. The Browse screen needs titles grouped by genre plus this profile's progress; the Player needs the video URL and the saved position. This list becomes your database design in step 2.
✅ Check it works
You have a written v1 feature list, a “later” list, five sketches and a name.
⚠️ Common mistakes
- Starting with the UI polish. The hard, impressive parts are encoding, the player and progress tracking; build those first.
Step 2
Create the project and the database schema
Goal: A running Next.js app connected to PostgreSQL with tables for users, profiles, titles, progress and My List.
Create the app with
npx create-next-app@latest streamly --ts --tailwind --app --src-dir, thennpm i prisma @prisma/client bcryptjsandnpx prisma init. Put your database URL in.env(and add.envto.gitignore).Design the schema around the sketches. One account has many profiles; progress and My List belong to a profile, not to the account, because two people sharing an account watch different things. A
Progressrow is unique per (profile, title) so saving again updates the same row.Store durations and positions in whole seconds. Store the HLS folder name (
hlsPath) on the title instead of a full URL; URLs are built and signed at request time.prisma/schema.prismamodel User { id String @id @default(cuid()) email String @unique passwordHash String profiles Profile[] createdAt DateTime @default(now()) } model Profile { id String @id @default(cuid()) userId String user User @relation(fields: [userId], references: [id], onDelete: Cascade) name String avatar String @default("blue") progress Progress[] myList MyList[] } model Title { id String @id @default(cuid()) slug String @unique name String year Int genres String[] description String poster String backdrop String duration Int // seconds hlsPath String // folder name under /media featured Boolean @default(false) progress Progress[] inLists MyList[] } model Progress { profileId String titleId String seconds Int updatedAt DateTime @updatedAt profile Profile @relation(fields: [profileId], references: [id], onDelete: Cascade) title Title @relation(fields: [titleId], references: [id], onDelete: Cascade) @@id([profileId, titleId]) } model MyList { profileId String titleId String addedAt DateTime @default(now()) profile Profile @relation(fields: [profileId], references: [id], onDelete: Cascade) title Title @relation(fields: [titleId], references: [id], onDelete: Cascade) @@id([profileId, titleId]) }✅ Check it works
npx prisma migrate dev --name initsucceeds andnpx prisma studioshows the five empty tables.⚠️ Common mistakes
- Putting progress on User instead of Profile; then everyone on the account shares one “continue watching” row.
Step 3
Encode the films into HLS with FFmpeg
Goal: Each film turned into a master playlist with 360p and 720p versions cut into 6-second segments.
A single MP4 cannot adapt: a slow connection keeps buffering the same big file. HLS solves this by cutting the video into short segments at several qualities and listing them in playlists. The player measures download speed and fetches the next segment from whichever quality fits. This is the core idea behind every streaming service.
The script below makes two video qualities with matching audio.
-g 48 -keyint_min 48 -sc_threshold 0forces a keyframe every 2 seconds (at 24 fps), so every 6-second segment starts on a keyframe and the player can switch quality at any segment boundary.Also grab a poster frame for each film:
ffmpeg -ss 00:01:00 -i input.mp4 -frames:v 1 -q:v 3 poster.jpg. Keep the original MP4s out of the project folder; only themedia/<slug>/output is needed.scripts/encode.sh#!/usr/bin/env bash # usage: ./scripts/encode.sh input.mp4 big-buck-bunny set -euo pipefail IN="$1"; OUT="media/$2" mkdir -p "$OUT/v0" "$OUT/v1" ffmpeg -i "$IN" \ -filter_complex "[0:v]split=2[a][b];[a]scale=w=640:h=360[v360];[b]scale=w=1280:h=720[v720]" \ -map "[v360]" -c:v:0 libx264 -b:v:0 800k -maxrate:v:0 856k -bufsize:v:0 1200k \ -map "[v720]" -c:v:1 libx264 -b:v:1 2800k -maxrate:v:1 2996k -bufsize:v:1 4200k \ -map a:0 -c:a:0 aac -b:a:0 96k -map a:0 -c:a:1 aac -b:a:1 128k \ -preset veryfast -g 48 -keyint_min 48 -sc_threshold 0 \ -f hls -hls_time 6 -hls_playlist_type vod \ -hls_segment_filename "$OUT/v%v/seg_%03d.ts" \ -master_pl_name master.m3u8 \ -var_stream_map "v:0,a:0 v:1,a:1" "$OUT/v%v/index.m3u8"✅ Check it works
media/<slug>/master.m3u8lists two streams, andffplay media/<slug>/master.m3u8(or VLC) plays it.⚠️ Common mistakes
- A source with no audio track fails on
-map a:0; remove the audio maps for silent clips. - Odd widths or heights make libx264 fail. Always scale to even numbers.
- A source with no audio track fails on
Step 4
Seed the catalogue
Goal: Your films, genres, posters and durations in the database.
Write
prisma/seed.tsthat inserts one row per encoded film. Use real durations (ffprobe -v error -show_entries format=duration -of csv=p=0 input.mp4) so the progress bar and “95% watched” logic work.Give each film 2–3 genres and mark one as
featuredfor the hero banner. Put posters and backdrops inpublic/art/(your own frames from step 3, not artwork copied from streaming sites).Make the seed idempotent with
upsertonslug, so running it twice does not create duplicates.prisma/seed.tsimport { PrismaClient } from '@prisma/client' const db = new PrismaClient() const films = [ { slug: 'big-buck-bunny', name: 'Big Buck Bunny', year: 2008, genres: ['Comedy', 'Animation'], description: 'A giant rabbit takes gentle revenge on three bullies.', duration: 596, featured: true }, { slug: 'sintel', name: 'Sintel', year: 2010, genres: ['Fantasy', 'Animation'], description: 'A girl searches for the baby dragon she raised.', duration: 888, featured: false }, ] async function main() { for (const f of films) { const data = { ...f, poster: '/art/' + f.slug + '-poster.jpg', backdrop: '/art/' + f.slug + '-wide.jpg', hlsPath: f.slug } await db.title.upsert({ where: { slug: f.slug }, update: data, create: data }) } } main().finally(() => db.$disconnect())✅ Check it works
npx prisma db seedruns twice without errors and Prisma Studio shows each film once.Step 5
Accounts and the “Who's watching?” screen
Goal: Sign up, log in, create up to 4 profiles and pick one.
Hash passwords with bcrypt (
bcrypt.hash(password, 12)) and keep the session in an httpOnly, secure, sameSite=lax cookie. You can use Auth.js, or write a small session table yourself; either is fine for this project as long as passwords are hashed and cookies are httpOnly.After login, show the profiles grid. Picking a profile stores its id in a second cookie. Every page that reads progress or My List must check that this profile belongs to the logged-in user; never trust the cookie on its own, because anyone can edit cookies.
Limit profiles to 4 on the server (count before insert), not only by hiding the button.
src/lib/profile.tsimport { cookies } from 'next/headers' import { db } from './db' import { requireUser } from './auth' /** The current profile, only if it belongs to the logged-in user. */ export async function currentProfile() { const user = await requireUser() // redirects to /login if not signed in const id = (await cookies()).get('profile')?.value if (!id) return null return db.profile.findFirst({ where: { id, userId: user.id } }) }✅ Check it works
Log in as user A, copy A's profile id into user B's cookie in DevTools: B must not see A's progress.
⚠️ Common mistakes
- Reading
profileIdfrom the cookie and querying progress directly, without theuserIdcheck.
- Reading
Step 6
Build the browse page with rows
Goal: A hero banner and horizontally scrolling rows by genre that load fast on a phone.
Make
browse/page.tsxa server component: load all titles once, group them by genre in JavaScript, and render oneRowper genre. Add a “Continue watching” row at the top from the profile's progress (step 8 fills it).Rows are plain CSS:
overflow-x-autowithscroll-snap-type: x mandatoryon the row andscroll-snap-align: starton each card. This feels native on phones with no JavaScript carousel.Use
next/imagewith asizesattribute so phones download small posters. Only the first row's images should bepriority; the rest lazy-load.src/components/Row.tsximport Image from 'next/image' import Link from 'next/link' type Card = { slug: string; name: string; poster: string } export function Row({ title, items, eager = false }: { title: string; items: Card[]; eager?: boolean }) { return ( <section className="mt-8"> <h2 className="px-4 text-lg font-semibold">{title}</h2> <ul className="mt-3 flex snap-x snap-mandatory gap-3 overflow-x-auto px-4 pb-2"> {items.map((t) => ( <li key={t.slug} className="w-36 shrink-0 snap-start sm:w-44"> <Link href={'/title/' + t.slug}> <Image src={t.poster} alt={t.name} width={176} height={264} sizes="(max-width: 640px) 144px, 176px" priority={eager} className="rounded-md transition hover:scale-105" /> </Link> </li> ))} </ul> </section> ) }✅ Check it works
Lighthouse (mobile) performance is 90+ and rows swipe smoothly on a real phone.
Step 7
Build the player with hls.js
Goal: A player that starts fast, switches quality on its own and offers a manual quality menu.
Safari plays HLS natively, so set
video.srcto the playlist there. Chrome, Firefox and Edge need hls.js:npm i hls.js, create anHlsinstance,loadSource(url)andattachMedia(video). Alwaysdestroy()it when the component unmounts, or you will leak network requests when the user leaves the page.After
MANIFEST_PARSED,hls.levelslists the qualities (height and bitrate). Show them in a menu; settinghls.currentLevel = -1returns to automatic.Pass the saved position as a prop and seek to it once metadata has loaded, unless the viewer was within the last 5% of the film (then start from 0).
src/components/Player.tsx'use client' import Hls from 'hls.js' import { useEffect, useRef, useState } from 'react' export function Player({ src, startAt, duration, onProgress }: { src: string; startAt: number; duration: number; onProgress: (s: number) => void }) { const ref = useRef<HTMLVideoElement>(null) const [levels, setLevels] = useState<number[]>([]) const hlsRef = useRef<Hls | null>(null) useEffect(() => { const video = ref.current! const resume = () => { if (startAt < duration * 0.95) video.currentTime = startAt } video.addEventListener('loadedmetadata', resume, { once: true }) if (video.canPlayType('application/vnd.apple.mpegurl')) { video.src = src // Safari: native HLS } else if (Hls.isSupported()) { const hls = new Hls() hlsRef.current = hls hls.loadSource(src) hls.attachMedia(video) hls.on(Hls.Events.MANIFEST_PARSED, () => setLevels(hls.levels.map((l) => l.height))) } let last = 0 const tick = () => { // save at most every 10 s const s = Math.floor(video.currentTime) if (Math.abs(s - last) >= 10) { last = s; onProgress(s) } } video.addEventListener('timeupdate', tick) video.addEventListener('pause', () => onProgress(Math.floor(video.currentTime))) return () => { video.removeEventListener('timeupdate', tick); hlsRef.current?.destroy() } }, [src, startAt, duration, onProgress]) return ( <div className="relative"> <video ref={ref} controls playsInline className="w-full bg-black" /> {levels.length > 0 && ( <select className="absolute right-2 top-2 rounded bg-black/70 text-white" onChange={(e) => { if (hlsRef.current) hlsRef.current.currentLevel = Number(e.target.value) }}> <option value={-1}>Auto</option> {levels.map((h, i) => <option key={h} value={i}>{h}p</option>)} </select> )} </div> ) }✅ Check it works
In DevTools → Network, set throttling to “Slow 4G”: within a few segments the requests switch from
v1/(720p) tov0/(360p).⚠️ Common mistakes
- Forgetting
hls.destroy(): segments keep downloading after you navigate away. - Wrapping
onProgressin a new arrow function on every render re-runs the effect; wrap it inuseCallbackin the parent.
- Forgetting
Step 8
Save progress and build “Continue watching”
Goal: Leaving a film and coming back resumes it, and the home page shows what you were watching.
The player calls
onProgress(seconds)at most every 10 seconds and on pause. The parent sends it to/api/progresswithfetch(..., { method: "POST", keepalive: true });keepalivelets the last request finish even if the tab is closing.On the server, check the profile (step 5), then
upsertthe row keyed by (profileId, titleId). Reject values below 0 or above the film's duration.The Continue watching row is progress ordered by
updatedAtdesc, excluding films watched past 95%. Show a thin red bar under each poster withseconds / duration.src/app/api/progress/route.tsimport { NextResponse } from 'next/server' import { db } from '@/lib/db' import { currentProfile } from '@/lib/profile' export async function POST(req: Request) { const profile = await currentProfile() if (!profile) return NextResponse.json({ error: 'no profile' }, { status: 401 }) const { titleId, seconds } = await req.json() const title = await db.title.findUnique({ where: { id: String(titleId) }, select: { duration: true } }) const s = Math.floor(Number(seconds)) if (!title || !Number.isFinite(s) || s < 0 || s > title.duration) { return NextResponse.json({ error: 'bad input' }, { status: 400 }) } await db.progress.upsert({ where: { profileId_titleId: { profileId: profile.id, titleId: String(titleId) } }, update: { seconds: s }, create: { profileId: profile.id, titleId: String(titleId), seconds: s }, }) return NextResponse.json({ ok: true }) }✅ Check it works
Watch 2 minutes, close the tab, reopen the title: it resumes within 10 seconds of where you stopped, and the film appears in Continue watching.
⚠️ Common mistakes
- Saving on every
timeupdateevent (about 4 times a second) floods your server.
- Saving on every
Step 9
Add My List and search
Goal: Profiles can save titles to My List, and a search box finds titles by name as you type.
My List is a toggle: a server action that deletes the (profile, title) row if it exists, otherwise creates it, then
revalidatePath("/browse"). Show “✓ My List” or “+ My List” from the current state.For search, a client
SearchBoxupdates the URL (/search?q=...) after 300 ms of no typing. The search page is a server component that queriesname contains q (case-insensitive). With a few hundred titles this is instant; for thousands, add PostgreSQL full-text search (see the Amazon guide).Keep search results shareable: because the query is in the URL, the back button and copied links work.
src/app/search/page.tsx (query part)const q = (searchParams.q ?? '').trim().slice(0, 80) const results = q ? await db.title.findMany({ where: { name: { contains: q, mode: 'insensitive' } }, orderBy: { year: 'desc' }, take: 40, }) : []✅ Check it works
Typing “sin” shows Sintel; adding a film to My List on one profile does not show it on another.
Step 10
Protect the video files with signed URLs
Goal: Video links that expire, so nobody can share a permanent link to your files.
If videos sit in
public/, anyone can download them forever. Real services use DRM (Widevine, FairPlay), which needs licences and is beyond a student project. A signed URL is the practical step: the link contains an expiry time and an HMAC signature that only your server can create.Put the signature in the path, not the query string:
/media/<exp>/<sig>/<slug>/master.m3u8. The playlists refer to segments with relative paths (v0/seg_001.ts), so the browser automatically requests them under the same signed prefix.The route handler checks the expiry and signature with
timingSafeEqual, blocks..in paths, and streams the file with the right content type. In production you would hand this job to Nginx (secure_link) or CloudFront signed URLs, but the idea is identical.src/app/media/[exp]/[sig]/[slug]/[...file]/route.tsimport { createHmac, timingSafeEqual } from 'node:crypto' import { readFile } from 'node:fs/promises' import path from 'node:path' const SECRET = process.env.MEDIA_SECRET! export const sign = (slug: string, exp: number) => createHmac('sha256', SECRET).update(slug + ':' + exp).digest('base64url') const TYPES: Record<string, string> = { '.m3u8': 'application/vnd.apple.mpegurl', '.ts': 'video/mp2t' } export async function GET(_: Request, ctx: { params: Promise<{ exp: string; sig: string; slug: string; file: string[] }> }) { const { exp, sig, slug, file } = await ctx.params const good = Buffer.from(sign(slug, Number(exp))) const given = Buffer.from(sig) if (Number(exp) < Date.now() / 1000 || good.length !== given.length || !timingSafeEqual(good, given)) { return new Response('Link expired', { status: 403 }) } if ([slug, ...file].some((p) => p.includes('..'))) return new Response('Bad path', { status: 400 }) const full = path.join(process.cwd(), 'media', slug, ...file) const type = TYPES[path.extname(full)] if (!type) return new Response('Not found', { status: 404 }) try { return new Response(await readFile(full), { headers: { 'Content-Type': type, 'Cache-Control': 'private, max-age=3600' } }) } catch { return new Response('Not found', { status: 404 }) } } // In the watch page: const exp = Math.floor(Date.now() / 1000) + 4 * 3600 // src = '/media/' + exp + '/' + sign(title.hlsPath, exp) + '/' + title.hlsPath + '/master.m3u8'✅ Check it works
A copied playlist link plays now; change one character of the signature, or wait past the expiry, and it returns 403.
⚠️ Common mistakes
- Comparing signatures with
===leaks timing information; usetimingSafeEqual. - Putting the signature in
?sig=: segment requests from the playlist will not carry it.
- Comparing signatures with
Step 11
Deploy, credit the films and present it
Goal: A live link, a README with an architecture diagram and a 2-minute demo video.
Deploy the app to a VPS or a Node host, the database to a managed PostgreSQL free tier, and keep
media/on the server disk (or move it to object storage + CDN later). SetMEDIA_SECRETand the database URL as environment variables.Add the Blender films' CC BY credit in the footer and README. Add a line: “Educational project inspired by Netflix. Not affiliated with Netflix.”
Your README should show: the architecture (browser → Next.js → Postgres, FFmpeg → HLS → signed route → hls.js), the encoding command, a GIF of quality switching under throttling, and what you would do next (CDN, DRM, recommendations). Record a 2-minute demo; recruiters watch videos more than they read code.
✅ Check it works
A friend on mobile data can sign up, pick a profile, watch, close the app and resume.
🚀 Make it stand out
- +Move media to object storage + CDN and compare start-up time
- +Thumbnails on the seek bar from a sprite sheet (FFmpeg `tile` filter)
- +“Because you watched X” rows from shared genres
- +Subtitles with WebVTT files in the HLS playlist