▲ Next.js Full Stack Architecture & RSC Masterclass
1️⃣ Evolution of Next.js: Pages Router vs App Router
Definition: Next.js Vercel dwara banaya gaya ek enterprise full-stack React framework hai. Iska modern App Router (app/ directory) React 19 architecture, nested layouts, streaming execution aur direct asynchronous server rendering ko support karta hai.
| Architectural Dimension | Legacy Pages Router (pages/) |
Modern App Router (app/) |
|---|---|---|
| Component Model | Every component shipped as client-side JS bundle. | Default React Server Components (RSC): Zero JS bundle shipped to client. |
| Data Fetching | Page-level hooks only (getServerSideProps, getStaticProps). |
Component-level async/await: Direct data fetching inside any nested component. |
| Layout Re-rendering | Page transitions re-render the entire view tree. | Preserved Nested Layouts: Only page leaf nodes re-render on navigation. |
2️⃣ React Server Components (RSC) vs Client Components
App Router me har file default roop se Server Component hoti hai jab tak aap top par 'use client' directive na lagayein:
| Criteria | Server Component (Default) | Client Component ('use client') |
|---|---|---|
| Execution Location | Server only (Node.js or Edge Runtime). | Server (pre-rendered HTML) + Client Browser Hydration. |
| Client Bundle Impact | 0 KB (Dependencies server par rehti hain). | Shops bundled JavaScript code to browser. |
| Access Capabilities | Direct Database queries, secrets (process.env), OS filesystem. |
Browser APIs (window, localStorage), React hooks (useState, useEffect). |
// app/jobs/page.tsx (Server Component - Zero client bundle!)
import db from '@/lib/db';
import JobSearchInput from './JobSearchInput'; // Client Component child
export default async function JobsPage() {
// Direct DB query inside component!
const jobs = await db.jobs.findMany({ where: { active: true } });
return (
<main>
<h1>Explore Tech Vacancies</h1>
<JobSearchInput /> {/* Hydrated on client for real-time keystrokes */}
<ul>
{jobs.map((job) => (
<li key={job.id}>{job.title} — ₹{job.salaryLpa} LPA</li>
))}
</ul>
</main>
);
}
3️⃣ Server Actions: Form Mutations & Revalidation
Bina separate REST API endpoints (/api/jobs/create) banaye direct backend functions ko form submission se trigger karna:
// app/actions/jobActions.ts
'use server'
import { revalidatePath } from 'next/cache';
import db from '@/lib/db';
export async function createJobAction(formData: FormData) {
const title = formData.get('title') as string;
const salary = parseFloat(formData.get('salary') as string);
// Secure Server Execution
await db.jobs.create({
data: { title, salaryLpa: salary }
});
// Purges cached HTML and re-renders the page instantly
revalidatePath('/jobs');
}
4️⃣ Streaming SSR & React Suspense
Agar page ka koi data source slow hai, toh poora page block karne ke bajay fast content instantly render hota hai aur slow content stream hota hai:
import { Suspense } from 'react';
import FastNavbar from './FastNavbar';
import SlowAnalyticsFeed from './SlowAnalyticsFeed';
import SkeletonLoader from './SkeletonLoader';
export default function Dashboard() {
return (
<section>
<FastNavbar /> {/* Rendered instantly in 10ms */}
<Suspense fallback={<SkeletonLoader />}>
<SlowAnalyticsFeed /> {/* Streamed as chunk over HTTP/2 */}
</Suspense>
</section>
);
}
5️⃣ The Next.js 4-Tier Caching Engine
| Cache Layer | What It Caches | Where It Lives | Duration / Invalidation |
|---|---|---|---|
| Request Memoization | Duplicate fetch() calls inside same render tree. |
Server Memory | Per-request lifecycle (Automatically garbage collected). |
| Data Cache | Data fetched across different incoming requests. | Server Disk / KV | Persistent across builds (revalidateTag() or time-based). |
| Full Route Cache | Static HTML and RSC Payload for static routes. | Server Disk | Invalidated on deployment or dynamic revalidation. |
| Router Cache | Prefetched RSC payloads in client browser. | Client Browser Memory | Session-based (30s dynamic, 5m static). |
6️⃣ Route Handlers & Edge Middleware
// middleware.ts (Runs before request hits routing system)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const authToken = request.cookies.get('auth_token')?.value;
// Protect /dashboard routes at the network Edge
if (request.nextUrl.pathname.startsWith('/dashboard') && !authToken) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*'],
};
7️⃣ Production Optimization & Standalone Deployments
•
next/image: Automatically converts images to modern WebP/AVIF format, lazy-loads offscreen images, prevents Cumulative Layout Shift (CLS).•
next/font: Zero layout shift self-hosted web fonts with automatic subsetting.•
output: 'standalone': Production Docker image size ko 1.2 GB se reduce karke ~120 MB banata hai (Copies only used node_modules).