Back

Introduction#

Building a video-sharing platform like YouTube is one of the most challenging yet rewarding projects for full-stack developers. It involves complex requirements: video processing, real-time streaming, user authentication, subscription systems, and much more.

In this technical deep dive, I’ll walk you through how I built NewTube - a fully functional YouTube clone using modern web technologies. This isn’t just a UI clone; it’s a production-ready application with real video processing, AI-powered features, and a scalable architecture.

GitHub Repository: NewTube Clone

Source and setup instructions: NewTube Clone on GitHub. A hosted demo is not currently published.


Project Overview#

What is NewTube?#

NewTube is a full-featured video-sharing platform that includes:

  • Video Upload & Streaming: Powered by Mux with HLS adaptive streaming
  • User Authentication: Complete auth flow with Clerk
  • Creator Studio: Dashboard for video management and analytics
  • Subscription System: Follow your favorite creators
  • Comments & Reactions: Full engagement features
  • Playlists: Create and manage video collections
  • AI Features: Auto-generate titles, descriptions, and thumbnails
  • Responsive Design: Works seamlessly on all devices

Tech Stack at a Glance#

LayerTechnology
FrontendNext.js 15, React 19, TypeScript, Tailwind CSS
BackendtRPC, Drizzle ORM
DatabasePostgreSQL (Neon)
AuthClerk
VideoMux
StorageUploadThing
CacheUpstash Redis
QueueQStash

Architecture Deep Dive#

System Architecture#

The application follows a three-tier architecture with serverless patterns optimized for modern cloud deployment:

Project Structure#

I organized the codebase using a feature-based module structure (which I call “moubles”):

moubles/
├── videos/
│   ├── server/
│   │   └── procedures.ts    # tRPC API endpoints
│   ├── ui/
│   │   └── components/      # React components
│   └── type.ts              # TypeScript types
├── comments/
├── subscriptions/
├── playlists/
└── ... (other features)
plaintext

This approach keeps related code together, making the codebase more maintainable as it grows.

Request Flow Example#

Here’s how a typical API request flows through the system:


Core Technologies and Features#

1. Server Components with SSR Prefetching#

Next.js 15’s App Router allows us to prefetch data on the server and hydrate it to the client:

Benefits:

  • Zero loading states for initial page load
  • Better SEO with server-rendered content
  • Reduced client-side JavaScript

2. Type-Safe API Layer with tRPC#

tRPC provides end-to-end type safety without code generation:

3. Authentication Middleware with Caching#

The authentication flow is optimized with a three-tier caching strategy:

4. Video Processing Pipeline#

The video upload and processing flow uses webhooks for async updates:

User Upload → Mux Upload URL → Mux Processing → Webhook → Database Update
     │              │                │               │            │
     └──────────────┴────────────────┴───────────────┴────────────┘
                    Asynchronous flow with real-time updates
plaintext

5. AI-Powered Content Generation#

Using QStash for async AI tasks:

6. Optimistic Updates for Better UX#


Challenges and Solutions#

Challenge 1: SSR Authentication with Protected Routes#

Problem: When using SSR with protected routes, the server doesn’t have access to the client’s authentication state, causing 401 errors or hydration mismatches.

Solution: Implement a multi-layered approach:

Key Insight: Using useRef prevents the sign-in modal from opening multiple times during React’s strict mode double-render.

Challenge 2: Hydration Mismatch in Mobile Detection#

Problem: A mobile detection hook caused hydration errors because the initial value differed between server and client.

// ❌ Problem: undefined on server, boolean on client
const [isMobile, setIsMobile] = useState<boolean | undefined>(undefined);
return !!isMobile;
typescript

Solution: Default to false and only update on client:

// ✅ Fixed: Consistent initial value
const [isMobile, setIsMobile] = useState<boolean>(false);

useEffect(() => {
	const checkMobile = () => {
		setIsMobile(window.innerWidth < 768);
	};

	checkMobile();
	window.addEventListener('resize', checkMobile);
	return () => window.removeEventListener('resize', checkMobile);
}, []);

return isMobile;
typescript

Challenge 3: Cache Invalidation Across Features#

Problem: When a user likes a video, the “Liked Videos” playlist wasn’t updating in real-time.

Solution: Invalidate all related queries:

const likeMutation = trpc.videoReactions.like.useMutation({
	onSuccess: () => {
		// Primary data
		utils.videos.getOne.invalidate({ id: videoId });

		// Related features
		utils.playlists.getLiked.invalidate();
		utils.playlists.getLikedPreview.invalidate();
	}
});
typescript

Challenge 4: CORS Configuration for Video Uploads#

Problem: In production, Mux uploads failed due to CORS restrictions.

Solution: Use environment-based CORS configuration:

const upload = await mux.video.uploads.create({
	new_asset_settings: {
		/* ... */
	},
	// Development: "*" | Production: specific domain
	cors_origin: process.env.MUX_CORS_ORIGIN || '*'
});
typescript

Challenge 5: Real-time Video Processing Status#

Problem: Users couldn’t see when their video finished processing.

Solution: Implement polling with automatic cleanup:


Conclusion#

Building NewTube was an incredible learning experience that pushed me to solve real-world problems at scale. Here’s what I learned:

Key Takeaways#

  1. Type Safety is Non-Negotiable: tRPC + TypeScript + Zod eliminated entire categories of bugs
  2. Server Components are Game-Changers: SSR prefetching dramatically improved UX and SEO
  3. Caching Strategy Matters: The three-tier auth caching reduced database queries by 90%
  4. Webhooks Enable Async Workflows: Critical for video processing and AI tasks
  5. Feature-Based Architecture Scales: The “moubles” structure kept the codebase maintainable

What’s Next?#

Future improvements I’m planning:

  • Real-time notifications with Server-Sent Events
  • Video chapters and timestamps
  • Live streaming support
  • Advanced analytics dashboard
  • Mobile app with React Native

Resources#


Thank you for reading! If you found this article helpful, please give the repository a ⭐ and feel free to reach out with questions.

Happy coding! 🚀

Building a Full-Stack YouTube Clone with Next.js 15
https://lora-sys.github.io/loraSys/blog/newtube
Author Lora
Published at March 10, 2026

读完了,Mochi 帮你夹了书签 · 回笔记列表