YouTube clone: upload, process and watch videos
Anyone can upload a video; a background worker converts it to adaptive HLS with thumbnails; viewers watch, like, comment, subscribe and get recommendations, with view counts that cannot be faked by refreshing.
Educational project inspired by YouTube. Skills101 is not affiliated with YouTube. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆Direct-to-storage uploads with presigned URLs
- ◆Background job queues with retries and progress (BullMQ)
- ◆Counting views correctly at scale with Redis
- ◆Simple recommendations from watch history
What you’ll build
- ✓Channels, uploads with progress and processing status
- ✓HLS playback in 360p/720p with thumbnails
- ✓Likes, comments with replies, subscriptions
- ✓Search, trending and “Up next” recommendations
Before you start
What you need
- •Do the Netflix guide first, or understand HLS and the FFmpeg command there.
- •Node.js 20+, PostgreSQL, Redis and an S3-compatible bucket (MinIO in Docker works locally).
- •Only upload videos you own or that have a free licence. Add a report button and a note about copyright.
How it fits together
- 1Browser uploads the original file straight to object storage using a presigned URL; your server never holds the big file.
- 2The API adds a job to a BullMQ queue in Redis; separate worker processes run FFmpeg, create HLS and thumbnails, upload them and mark the video READY.
- 3Next.js serves channel, watch and search pages from PostgreSQL; hls.js plays the video.
- 4View events are de-duplicated and counted in Redis, then written to PostgreSQL in batches every minute.
Project structure
vidshare/
├─ web/ (Next.js)
│ ├─ src/app/watch/[id]/page.tsx, channel/[handle]/page.tsx
│ ├─ src/app/upload/page.tsx
│ └─ src/app/api/(videos, views, comments)
├─ worker/
│ ├─ transcode.ts # BullMQ worker
│ └─ ffmpeg.ts
├─ docker-compose.yml # postgres, redis, minio
└─ prisma/schema.prismaStep-by-step guide
Step 1
Plan how it differs from Netflix
Goal: A v1 focused on user uploads, processing, engagement and discovery.
Netflix has a small catalogue encoded once by the company. YouTube's hard problems are different: anyone uploads at any time, so processing must be automatic and queued; there are millions of videos, so discovery (search, trending, recommendations) matters; and counts (views, likes, subscribers) must be fast and hard to fake.
v1: sign in, create a channel with a @handle, upload with progress, see processing status, watch, like, comment with replies, subscribe, search, home page with trending, “Up next”.
Name it (“VidShare”) and add “Educational project inspired by YouTube. Not affiliated.” to the README.
✅ Check it works
You can list the three hard problems above in your own words.
Step 2
Design the schema with a status for each video
Goal: Channels, videos with a processing status, comments with replies, likes and subscriptions.
A video moves through
UPLOADING → PROCESSING → READY(orFAILED). Only READY videos appear in search and feeds. Keepprogress(0–100) for the processing screen.Comments have an optional
parentIdfor replies (one level deep is enough). Likes are (userId, videoId, value) with value +1 or −1, primary key (userId, videoId), so switching like to dislike is one update.Store
viewCountandlikeCountas counters on Video, and index(status, createdAt)and(channelId, createdAt).prisma/schema.prisma (core)model Video { id String @id @default(cuid()) channelId String title String description String @default("") status String @default("UPLOADING") // UPLOADING | PROCESSING | READY | FAILED progress Int @default(0) sourceKey String // original file in the bucket hlsUrl String? thumbUrl String? duration Int? // seconds viewCount BigInt @default(0) likeCount Int @default(0) createdAt DateTime @default(now()) comments Comment[] @@index([status, createdAt]) @@index([channelId, createdAt]) } model Comment { id String @id @default(cuid()) videoId String video Video @relation(fields: [videoId], references: [id], onDelete: Cascade) userId String parentId String? text String likeCount Int @default(0) createdAt DateTime @default(now()) @@index([videoId, parentId, createdAt]) } model Subscription { userId String channelId String createdAt DateTime @default(now()) @@id([userId, channelId]) }✅ Check it works
Migrations run and you can explain why
viewCountis BigInt.Step 3
Upload straight to storage with a presigned URL
Goal: A 500 MB upload goes from the browser to the bucket with a progress bar, without passing through your server.
Sending big files through your Next.js server wastes its memory and bandwidth and often hits time limits. Instead, your API creates the Video row and returns a presigned PUT URL: a link that allows uploading one specific object for a few minutes.
The browser uploads with
XMLHttpRequest(it reports upload progress;fetchdoes not yet in all browsers) and, when finished, callsPOST /api/videos/<id>/uploaded. That endpoint checks the object exists (HeadObject), sets status PROCESSING and adds a job to the queue.Validate type and size before signing (video/mp4, video/webm, video/quicktime; max 2 GB), and configure CORS on the bucket to allow PUT from your site.
web/src/app/api/videos/route.tsimport { PutObjectCommand } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' const ALLOWED = ['video/mp4', 'video/webm', 'video/quicktime'] export async function POST(req: Request) { const user = await requireUser() const { title, type, size } = await req.json() if (!ALLOWED.includes(type) || !(size > 0 && size <= 2 * 1024 ** 3)) { return Response.json({ error: 'MP4, WebM or MOV up to 2 GB' }, { status: 400 }) } const channel = await db.channel.findUniqueOrThrow({ where: { userId: user.id } }) const video = await db.video.create({ data: { channelId: channel.id, title: String(title).slice(0, 100), sourceKey: 'src/' + crypto.randomUUID() }, }) const uploadUrl = await getSignedUrl(s3, new PutObjectCommand({ Bucket: BUCKET, Key: video.sourceKey, ContentType: type }), { expiresIn: 900 }) return Response.json({ id: video.id, uploadUrl }) }✅ Check it works
Watching the Network tab, the big PUT request goes to the bucket's domain, not to your app, and the progress bar moves smoothly.
Step 4
Process videos in a background worker
Goal: A BullMQ worker turns each upload into HLS plus thumbnails, reports progress and retries on failure.
Transcoding takes minutes and lots of CPU, so it must not run inside a web request. BullMQ stores jobs in Redis; a separate worker process (or several machines) takes them one at a time. If a worker crashes, the job is retried.
The worker: download the source, run
ffprobeto read duration and check it is really a video (reject over 1 hour for this project), run the HLS command from the Netflix guide, extract a thumbnail at 10% of the duration, upload the output folder, set READY with URLs and duration. Update progress (10%, 50%, 90%) so the uploader sees it.Keep concurrency low (1–2 per CPU-heavy machine). On final failure, set FAILED and tell the uploader why.
worker/transcode.tsimport { Queue, Worker } from 'bullmq' const connection = { host: process.env.REDIS_HOST ?? 'localhost', port: 6379 } export const transcodeQueue = new Queue('transcode', { connection }) // API side: await transcodeQueue.add('video', { videoId }, { attempts: 3, backoff: { type: 'exponential', delay: 30_000 } }) new Worker('transcode', async (job) => { const { videoId } = job.data as { videoId: string } const video = await db.video.findUniqueOrThrow({ where: { id: videoId } }) const dir = await mkTempDir() const src = await download(video.sourceKey, dir) const info = await probe(src) // ffprobe: duration, has video stream? if (!info.hasVideo || info.duration > 3600) throw new UnrecoverableError('Not a video, or longer than 1 hour') await job.updateProgress(10) await encodeHls(src, dir + '/hls', (pct) => job.updateProgress(10 + Math.round(pct * 0.8))) await thumbnail(src, dir + '/thumb.jpg', info.duration * 0.1) const base = await uploadFolder(dir, 'v/' + videoId) await db.video.update({ where: { id: videoId }, data: { status: 'READY', progress: 100, duration: Math.round(info.duration), hlsUrl: base + '/hls/master.m3u8', thumbUrl: base + '/thumb.jpg', } }) }, { connection, concurrency: 1 }) .on('failed', async (job, err) => { if (job && job.attemptsMade >= (job.opts.attempts ?? 1)) { await db.video.update({ where: { id: job.data.videoId }, data: { status: 'FAILED' } }) } })✅ Check it works
Upload 3 videos quickly: they process one after another; killing the worker mid-job and restarting it finishes the job.
⚠️ Common mistakes
- Running FFmpeg inside the Next.js request: it times out and blocks other users.
UnrecoverableError(from bullmq) stops retries for bad files; network errors should still retry.
Step 5
Watch page with player and processing status
Goal: The watch page plays READY videos and shows a live progress bar while processing.
Reuse the hls.js player from the Netflix guide. Below it: title, channel with subscribe button and subscriber count, like/dislike, description (collapsed), comments.
While status is PROCESSING, the uploader sees “Processing 45%” that refreshes every 3 seconds (poll
GET /api/videos/<id>), and others get a 404 until it is READY.Add Open Graph tags (title, thumbnail) so shared links look good, and a
VideoObjectJSON-LD for search engines.✅ Check it works
Uploading then opening the watch page shows progress climbing to 100%, then the video plays without reloading.
Step 6
Count views correctly
Goal: Views count real watching, ignore refresh spam, and do not hammer the database.
Rule: a view counts after 30 seconds of watching (or half the video if it is shorter), at most once per viewer per video per 24 hours. Logged-out viewers are identified by a random id cookie.
De-duplicate with Redis:
SET view:<videoId>:<viewer> 1 EX 86400 NX. If it was set (first time today), increment a bufferINCR views:pending:<videoId>. A job runs every minute, reads and resets the buffers, and adds them toviewCountin PostgreSQL. One update per video per minute instead of one per view.Also record watch history rows (userId, videoId, watchedAt) for logged-in users; step 9 uses them.
web/src/app/api/views/route.ts + flush jobexport async function POST(req: Request) { const { videoId, watchedSeconds } = await req.json() const viewer = (await currentUserId()) ?? (await anonymousId()) // cookie for logged-out viewers const video = await db.video.findUnique({ where: { id: String(videoId) }, select: { duration: true, status: true } }) if (!video || video.status !== 'READY') return Response.json({ counted: false }) const needed = Math.min(30, (video.duration ?? 60) / 2) if (!(Number(watchedSeconds) >= needed)) return Response.json({ counted: false }) const first = await redis.set('view:' + videoId + ':' + viewer, '1', { EX: 86400, NX: true }) if (first) await redis.incr('views:pending:' + videoId) return Response.json({ counted: Boolean(first) }) } // every minute (worker) for await (const key of redis.scanIterator({ MATCH: 'views:pending:*', COUNT: 100 })) { const n = Number(await redis.getDel(key)) // read and reset atomically if (n > 0) await db.video.update({ where: { id: key.slice(14) }, data: { viewCount: { increment: n } } }) }✅ Check it works
Refreshing a video 20 times counts 1 view; watching from another account counts a second view within a minute.
Step 7
Likes, comments and subscriptions
Goal: Engagement features with counters that stay correct.
Like/dislike: upsert the (user, video) row with +1 or −1; clicking the same button again deletes it. Recompute
likeCountchange in the same transaction (for example −1 → +1 adds 1 like).Comments: top-level sorted by likes then newest, replies under them (“View 12 replies”), max 1,000 characters, rate-limited, and the channel owner can pin one and delete any. Escape text (React does) and turn URLs into links with
rel="nofollow ugc".Subscriptions: toggle a row and a
subscriberCounton Channel. The “Subscriptions” feed is READY videos from subscribed channels, newest first, with cursor pagination.✅ Check it works
Like → dislike → remove leaves likeCount where it started; the subscriptions feed shows a new upload from a subscribed channel.
Step 8
Search, trending and “Up next”
Goal: Users find videos by text, see what is trending, and get sensible next videos.
Search: PostgreSQL full-text search over title (weight A) and description (weight B), only READY videos (see the Amazon guide for the generated column + GIN index).
Trending: score views gained in the last 48 hours (keep hourly view counts per video) divided by age, similar to the Instagram explore formula.
“Up next”: collaborative filtering in plain SQL. People who watched this video also watched which others? Count co-watches in history, exclude what you already watched, and fall back to the same channel's latest videos.
up next (co-watch) querySELECT h2."videoId", count(*) AS together FROM "WatchHistory" h1 JOIN "WatchHistory" h2 ON h2."userId" = h1."userId" AND h2."videoId" <> h1."videoId" JOIN "Video" v ON v.id = h2."videoId" AND v.status = 'READY' WHERE h1."videoId" = $1 AND h2."videoId" NOT IN (SELECT "videoId" FROM "WatchHistory" WHERE "userId" = $2) GROUP BY h2."videoId" ORDER BY together DESC LIMIT 10;✅ Check it works
After 5 test accounts each watch videos A and B, video B appears in “Up next” on A for a new account.
Step 9
Moderation, limits and deployment
Goal: A safe, deployed platform with separate web and worker processes.
Add Report (reason + details) on videos and comments, an admin queue to hide content, upload limits per user per day, and a clear policy page (“Upload only videos you own”).
Deploy the web app, run the worker as a separate process (or machine) with FFmpeg installed, use managed PostgreSQL and Redis, and put a CDN in front of the bucket for HLS files.
README: architecture diagram (browser → bucket, API → queue → worker → bucket → CDN → player), view-counting design, the co-watch query, costs per hour of video, and the not-affiliated note.
✅ Check it works
A friend uploads from their phone and watches it processed and playing within a few minutes.
🚀 Make it stand out
- +Shorts: vertical videos with swipe navigation
- +Auto-generated captions with a speech-to-text model
- +Live streaming (see the Hotstar guide)
- +Creator analytics: views per day and average watch time