Next.js: From React to Production
Build modern full-stack web applications with React and Next.js App Router.
Next.js 15+
From React to Production
Master modern full-stack web engineering with React Server Components, App Router, Server Actions, PostgreSQL integration, and cloud deployment workflows. រៀនបង្កើត Web Application កម្រិតខ្ពស់ជាមួយ React Server Components, App Router, Server Actions, ការតភ្ជាប់ PostgreSQL និងការ Deploy ទៅកាន់ Production ដោយរលូន។
What You Will Learn
The complete path from React basics to full-stack production architecture.
1. Foundation to App Router
Understand why React needs a framework, the mental shift from client SPA to hybrid Server/Client components, and file-based routing.យល់ដឹងពីមូលហេតុដែល React ត្រូវការ framework និងការប្ដូរផ្នត់គំនិតពី SPA ធម្មតាទៅជា Hybrid Server/Client Components។
2. Full-Stack Data & Database
Fetch data directly in Server Components, execute server mutations with Server Actions, connect to PostgreSQL, and handle streaming UI.ទាញទិន្នន័យផ្ទាល់លើ Server Components, ធ្វើការកែប្រែទិន្នន័យតាម Server Actions, ភ្ជាប់ជាមួយ PostgreSQL និងប្រើ Streaming UI។
3. Security, Project & Shipping
Secure routes with authentication, manage environment secrets safely, build the complete TaskFlow SaaS, and ship to Vercel via Git.ការពារ Routes ដោយ Authentication, គ្រប់គ្រង Env Secrets ឱ្យមានសុវត្ថិភាព, បង្កើតគម្រោង TaskFlow SaaS និង Deploy ទៅកាន់ Vercel។
What Is Next.js?
Understanding the full-stack React framework and its core capabilities.
The React Framework for the WebReact Framework សម្រាប់ Full-Stack Web
Next.js is an open-source React framework created by Vercel. While React is a library for building user interfaces, Next.js provides the full architecture needed for production: routing, rendering, backend actions, and optimization.Next.js គឺជា React framework បង្កើតឡើងដោយក្រុមហ៊ុន Vercel។ ខណៈពេលដែល React គឺជា UI Library, Next.js ផ្ដល់នូវរចនាសម្ព័ន្ធពេញលេញសម្រាប់ Production ដូចជា Routing, Rendering, Backend និង Optimization។
- File-System Routing: Folder-based pages, layouts, and nested routes
- Server Components: Fast rendering with zero client-side JS bundle overhead
- Server Actions: Type-safe asynchronous mutations directly from forms
- Asset Optimization: Automatic WebP images, self-hosted fonts, scripts
- Metadata & SEO: Dynamic Open Graph and search engine tags built-in
React vs Next.js
Detailed architectural comparison between React and Next.js.
| FEATURE / CRITERIA | STANDALONE REACT (VITE / CRA) | NEXT.JS (APP ROUTER) |
|---|---|---|
| Category | UI Library (view layer only) | Full-Stack Framework |
| Routing | Third-party required (React Router, etc.) | Built-in File-System Routing (Folders & Pages) |
| Rendering | Client-Side Rendering (CSR) by default | Server Components (RSC), SSR, SSG, Streaming |
| Data Fetching | Client useEffect / TanStack Query | Direct async/await on Server & Server Actions |
| Backend / DB | Requires separate Express/Nest/FastAPI backend | Direct DB access & Route Handlers built-in |
| SEO & Metadata | Difficult, requires React Helmet or prerender | Built-in static and dynamic Metadata API |
When Should You Use Next.js?
Primary use cases and production scenarios where Next.js excels.
Web Applications
Multi-tenant software, subscription dashboards, complex authenticated workflows, and rich data visualization.កម្មវិធី SaaS, ប្រព័ន្ធ Dashboard មាន Login, ការគ្រប់គ្រងទិន្នន័យស្មុគស្មាញ និងទាមទារសុវត្ថិភាពខ្ពស់។
Online Stores
Instant page loads via static rendering for products, dynamic cart interactions, and superior SEO for high search ranking.ហាងលក់ទំនិញអនឡាញ ទាមទារល្បឿនលឿនខ្លាំង (SEO) និងការទាញទិន្នន័យស្តុកតាម Real-time។
Blogs & News
Content sites requiring incremental static regeneration, dynamic markdown rendering, and instant image optimization.គេហទំព័រព័ត៌មាន ប្លុក ឬ Documentation ដែលត្រូវការ SEO ល្អ និងការ Render អត្ថបទរហ័ស។
Admin Portals
Internal company portals, inventory trackers, and CRM systems with direct PostgreSQL database connections.ប្រព័ន្ធគ្រប់គ្រងផ្ទៃក្នុងក្រុមហ៊ុន (Admin CRM / ERP) ដែលភ្ជាប់ទៅកាន់ PostgreSQL ដោយផ្ទាល់។
Before Learning Next.js
Prerequisites and recommended background knowledge.
Essential Prerequisites
Before learning Next.js, you should have a solid grasp of web fundamentals. Next.js builds on top of React, so attempting Next.js without React basics will lead to confusion about what comes from React vs what comes from Next.js.មុននឹងរៀន Next.js អ្នកគប្បីយល់ច្បាស់ពីមូលដ្ឋានគ្រឹះ Web។ ដោយសារ Next.js បង្កើតលើ React បើគ្មានមូលដ្ឋាន React ទេ អ្នកនឹងច្រឡំរវាងអ្វីជារបស់ React និងអ្វីជារបស់ Next.js។
React Fundamentals You Need
The essential React building blocks required for Next.js App Router.
Reusable UI Functions
Components are JavaScript functions returning JSX markup describing what the interface should look like.Components គឺជា functions ដែល return JSX ដើម្បីកំណត់ទម្រង់ UI។
Data Transfer
Passing data from parent to child components via attributes and the special children prop.ការបញ្ជូនទិន្នន័យពី Parent ទៅកាន់ Child តាមរយៈ props និង children។
Interactive Memory
Using useState and useEffect for client-side state and life-cycle events.ការប្រើប្រាស់ useState និង useEffect សម្រាប់រក្សាទុក state និងគ្រប់គ្រង lifecycle។
Handling Clicks & Inputs
Listening to user events via onClick, onChange, and onSubmit handlers.ការចាប់ព្រឹត្តិការណ៍របស់អ្នកប្រើប្រាស់ដូចជា onClick, onChange និង onSubmit។
Asynchronous Data
Handling asynchronous JavaScript promises using modern async and await syntax.ការប្រើប្រាស់ async/await ដើម្បីរង់ចាំទិន្នន័យពី Network ឬ Database។
Execution Boundaries
Understanding that code can run either on the server environment or in the browser window.ការបែងចែកថាតើកូដមួយណាត្រូវដំណើរការលើ Server ឬលើ Browser Client។
Install Requirements
Setting up Node.js, package manager, and development tools.
Environment Prerequisites
Next.js 15 requires Node.js version 18.18 or higher (version 20+ LTS is recommended). You also need a package manager (pnpm, npm, or bun) and a code editor like VS Code.Next.js 15 តម្រូវឱ្យមាន Node.js កំណែ 18.18 ឡើងទៅ (ណែនាំ Node 20+ LTS)។ អ្នកក៏ត្រូវការ Package Manager (pnpm, npm, bun) និង Editor ដូចជា VS Code។
node -v. If outdated, install the latest LTS release from nodejs.org.ពិនិត្យមើលកំណែ Node ក្នុង Terminal ដោយប្រើ node -v។ ប្រសិនបើយឺត សូមដំឡើងកំណែ LTS ចុងក្រោយពី nodejs.org។Create a Next.js Application
Bootstrapping a modern full-stack project with create-next-app.
Recommended Configuration Options
The CLI sets up everything needed for modern development in seconds.CLI នឹងរៀបចំអ្វីៗទាំងអស់ដោយស្វ័យប្រវត្តិតែប៉ុន្មានវិនាទីប៉ុណ្ណោះ។
Start Development Server
Launching the development server with Turbopack and Fast Refresh.
Fast Refresh & Instant Feedback
Open http://localhost:3000 in your browser. Next.js includes Fast Refresh: whenever you edit any file inside app/, the browser updates instantaneously while preserving your application's state.បើក http://localhost:3000 លើ Browser។ Next.js មានមុខងារ Fast Refresh៖ រាល់ពេលអ្នកកែប្រែកូដក្នុង folder app/ Browser នឹង Update ភ្លាមៗដោយមិនបាត់បង់ State ឡើយ។
Next.js Project Structure
Understanding the App Router layout, folders, and configuration files.
my-app/ ├── app/ # App Router routes & pages │ ├── favicon.ico │ ├── globals.css # Global CSS & Tailwind │ ├── layout.tsx # Root layout wrapper │ └── page.tsx # Root page (/) ├── public/ # Static assets (images, SVGs) │ └── next.svg ├── node_modules/ ├── next.config.ts # Next.js config ├── package.json # Dependencies & scripts ├── postcss.config.mjs ├── tailwind.config.ts # Tailwind CSS config └── tsconfig.json # TypeScript config
App Router Architecture
In Next.js App Router, routing is entirely determined by folders inside app/. Files named page.tsx become publicly accessible routes, while layout.tsx provides wrapping layouts.ក្នុង Next.js App Router ការកំណត់ Routing ត្រូវបានធ្វើឡើងតាមរយៈ folders ក្នុង app/។ ឯកសារឈ្មោះ page.tsx ក្លាយជា Route សាធារណៈ ហើយ layout.tsx ផ្ដល់នូវ Layout រួម។
app/page.tsx
The entry route file and main page component.
export default function HomePage() {
return (
<main className="flex min-h-screen flex-col items-center justify-center p-24">
<h1 className="text-4xl font-bold tracking-tight">
Hello Next.js
</h1>
<p className="mt-4 text-slate-400">
Welcome to your modern full-stack web application.
</p>
</main>
);
}
Simulated Browser Output (localhost:3000)
Hello Next.js
Welcome to your modern full-stack web application.
Server Componentpage.tsx is the UI rendered for this route segment.វិធាន៖ Default export ពី page.tsx គឺជា UI ដែលត្រូវបង្ហាញសម្រាប់ Route Segment នោះ។app/layout.tsx
Root layout, shared UI, and global HTML shell.
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "My Application",
description: "Built with Next.js App Router",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className="bg-slate-950 text-slate-50 antialiased">
{children}
</body>
</html>
);
}
Root Layout Responsibilities
The Root Layout is required and defines the top-level <html> and <body> tags. It is shared across all pages in the app and never re-renders during navigation, preserving client state.Root Layout គឺចាំបាច់ត្រូវតែមាន ដើម្បីកំណត់ tag <html> និង <body>។ វាត្រូវបានប្រើរួមគ្នានៅគ្រប់ទំព័រ ហើយមិនត្រូវ Re-render ឡើងវិញពេល Navigation ឡើយ។
File-System Routing
How folders and pages map directly to public URLs.
app/ ├── page.tsx → / ├── about/ │ └── page.tsx → /about └── contact/ └── page.tsx → /contact
Automatic Routing by Convention
You never have to maintain a separate route configuration file like in React Router. Simply create a folder with a page.tsx file, and Next.js automatically creates the endpoint URL.អ្នកមិនបាច់សរសេរឯកសារ Route Config ស្មុគស្មាញឡើយ។ គ្រាន់តែបង្កើត folder និងដាក់ page.tsx ចូល Next.js នឹងបង្កើត URL នោះដោយស្វ័យប្រវត្តិ។
Nested Routes
Hierarchical route segments and nested UI layouts.
app/
└── dashboard/
├── layout.tsx # Dashboard sidebar layout
├── page.tsx → /dashboard
├── users/
│ └── page.tsx → /dashboard/users
└── settings/
└── page.tsx → /dashboard/settings
Nested Layouts & Preserved State
The dashboard/layout.tsx wraps all routes beneath it. When a user switches between /dashboard/users and /dashboard/settings, the dashboard layout remains intact and only the inner page content re-renders!dashboard/layout.tsx នឹងរុំព័ទ្ធគ្រប់ Sub-routes ទាំងអស់។ ពេល User ប្ដូរពី /users ទៅ /settings នោះ Sidebar នឹងមិនបាត់បង់ state ឬ refresh ឡើយ។
Dynamic Routes
Capturing URL parameters with dynamic folder segments [id].
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
// In Next.js 15+, params is a Promise
const { id } = await params;
return (
<div className="p-8">
<h1 className="text-2xl font-bold">Product Details</h1>
<p className="font-mono text-blue-400 mt-2">Product ID: {id}</p>
</div>
);
}
Square Brackets [id] Convention
Any folder with brackets creates dynamic segments that capture URL parameters.Folder ដែលមានសញ្ញាវង់ក្រចក [id] នឹងចាប់យក Parameter ពី URL។
Link Component
Client-side navigation and automatic background route prefetching.
import Link from "next/link";
export default function Navbar() {
return (
<nav className="flex gap-4 p-4 bg-slate-900 border-b border-slate-800">
<Link href="/" className="hover:text-blue-400">
Home
</Link>
<Link href="/dashboard" className="hover:text-blue-400">
Dashboard
</Link>
<Link href="/about" className="hover:text-blue-400">
About
</Link>
</nav>
);
}
Why next/link instead of <a>?
The <Link> component performs client-side transitions without full page reloads. Crucially, Next.js automatically prefetches linked pages in the viewport in the background, making navigation feel instant!<Link> ធ្វើការផ្លាស់ប្ដូរទំព័រដោយមិនបាច់ Reload ទំព័រទាំងមូលឡើយ។ Next.js ថែមទាំង Pre-fetch ទិន្នន័យទំព័រនោះទុកជាមុន ធ្វើឱ្យការចុចបើកលឿនដូចផ្លេកបន្ទោរ!
Navigation Architecture
Application site hierarchy and active navigation highlighting.
Active Links with usePathname()
In Client Components, import usePathname from next/navigation to read the current URL path and apply active highlight styles to your nav items.ក្នុង Client Components អ្នកអាចប្រើ usePathname() ពី next/navigation ដើម្បីដឹងពី Path បច្ចុប្បន្ន និងដាក់ពណ៌ Active លើ Nav link។
"use client";
import { usePathname } from "next/navigation";
import Link from "next/link";
export function NavLink({ href, label }: { href: string; label: string }) {
const pathname = usePathname();
const isActive = pathname === href;
return (
<Link href={href} className={isActive ? "text-blue-400 font-bold" : "text-slate-400"}>
{label}
</Link>
);
}
What Is a Component?
Reusable UI building blocks in React and Next.js.
export default function Button() {
return (
<button className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium text-sm transition">
Click me
</button>
);
}
Reusable UI Units
Components are the core foundation of React and Next.js applications. They encapsulate markup, styling, and behavior into self-contained, composable building blocks that can be reused anywhere.Components គឺជាគ្រឹះចម្បងរបស់ React និង Next.js។ វាបូកបញ្ចូល Markup, Styling និង Behavior ទៅជាដុំកូដដែលអាចយកទៅប្រើឡើងវិញនៅគ្រប់ទីកន្លែង។
Props
Passing dynamic data and children to reusable components.
interface ButtonProps {
children: React.ReactNode;
variant?: "primary" | "secondary";
}
export function Button({ children, variant = "primary" }: ButtonProps) {
const styles = variant === "primary"
? "bg-blue-600 text-white hover:bg-blue-700"
: "bg-slate-800 text-slate-200 hover:bg-slate-700";
return (
<button className={`px-4 py-2 font-medium text-sm transition ${styles}`}>
{children}
</button>
);
}
TypeScript Interface for Props
Props pass configuration and data into components. Using TypeScript guarantees compile-time safety.Props បញ្ជូនទិន្នន័យចូល component ហើយ TypeScript ជួយពិនិត្យកំហុសកូដជាមុន។
<Button variant="primary">Save Changes</Button>
<Button variant="secondary">Cancel</Button>
Component Architecture
Organizing components, modularity, and colocation best practices.
app/ ├── components/ # Shared UI components │ ├── Button.tsx │ ├── Card.tsx │ ├── Modal.tsx │ └── Navbar.tsx └── dashboard/ ├── components/ # Dashboard-specific components │ └── UserTable.tsx └── page.tsx
Modularity & Colocation
Colocate components close to where they are used. If a component is only used on the dashboard, keep it in app/dashboard/components/. If it is reused across the entire app, place it in a top-level components/ folder.ដាក់ component ជិតកន្លែងដែលវាត្រូវប្រើ។ បើប្រើតែលើ Dashboard ទុកក្នុង folder របស់ Dashboard។ បើប្រើទូទៅ ដាក់ក្នុង root components/។
Server Components
Default server execution, direct async/await, and zero bundle size.
// Server Component by default in App Router
export default async function ProductsPage() {
// Direct async data fetching on the server
const res = await fetch("https://api.example.com/products");
const products = await res.json();
return (
<div className="p-8">
<h1 className="text-2xl font-bold">Products List</h1>
<ul className="mt-4 space-y-2">
{products.map((p: any) => (
<li key={p.id} className="p-3 bg-slate-900 border border-slate-800">
{p.name} - ${p.price}
</li>
))}
</ul>
</div>
);
}
Zero Client-Side JavaScript
In Next.js App Router, all components inside app/ are React Server Components (RSC) by default. They run only on the server, have direct database access, and send pure rendered HTML to the browser with zero JavaScript bundle overhead!ក្នុង App Router គ្រប់ component ទាំងអស់គឺជា Server Components ដោយស្វ័យប្រវត្តិ។ វាដំណើរការតែលើ Server អាចទាញទិន្នន័យពី DB ផ្ទាល់ និងមិនបន្ថែមទំហំ JS ទៅកាន់ Browser ឡើយ!
Client Components
Using the "use client" directive for browser interactivity and state.
"use client";
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button
onClick={() => setCount(count + 1)}
className="px-4 py-2 bg-blue-600 text-white font-mono"
>
Clicks: {count}
</button>
);
}
Interactive Simulator
Test this client component live right here:សាកល្បងចុចលើ Client Component ជាក់ស្ដែងនៅទីនេះ៖
"use client" directive marks the boundary between server-rendered code and browser-interactive code.ពាក្យបញ្ជា "use client" កំណត់ព្រំដែនរវាងកូដ Server និងកូដ Interactive លើ Browser។Server vs Client
Direct comparison of capabilities, environments, and performance impacts.
| TASK / REQUIREMENT | SERVER COMPONENT (DEFAULT) | CLIENT COMPONENT ("use client") |
|---|---|---|
| Fetch data from API or DB | Yes (Direct async/await) | Not recommended (use server first) |
| Access Backend Resources / Secrets | Yes (Completely secure) | No (Leaks to browser window) |
| Client-Side State (useState, useReducer) | No | Yes |
| Event Listeners (onClick, onChange) | No | Yes |
| Browser APIs (localStorage, window) | No (window is undefined) | Yes (inside useEffect) |
Choosing Server or Client
A decision tree to determine component boundaries.
Tailwind CSS in Next.js
Modern utility-first styling configured with zero setup overhead.
export function DashboardCard({ title, value, change }: any) {
return (
<div className="rounded-none bg-slate-900 border border-slate-800 p-6 shadow-sm">
<h3 className="text-sm font-medium text-slate-400">{title}</h3>
<div className="mt-2 flex items-baseline gap-2">
<span className="text-3xl font-extrabold text-white">{value}</span>
<span className="text-xs font-semibold text-green-400 font-mono">{change}</span>
</div>
</div>
);
}
Tailwind CSS Built-in Integration
Next.js automatically compiles Tailwind CSS during build, generating only the minimal CSS classes used.Next.js នឹង Compile Tailwind CSS ដោយស្វ័យប្រវត្តិតែ class ណាដែលបានប្រើប៉ុណ្ណោះ។
Responsive UI
Building adaptable, mobile-first layouts with Tailwind breakpoints.
export default function DashboardPage() {
return (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 p-6">
<div className="p-4 bg-slate-900 border border-slate-800">Card 1</div>
<div className="p-4 bg-slate-900 border border-slate-800">Card 2</div>
<div className="p-4 bg-slate-900 border border-slate-800">Card 3</div>
<div className="p-4 bg-slate-900 border border-slate-800">Card 4</div>
</div>
);
}
Mobile-First Breakpoints
Always design mobile-first: default styles apply to mobile devices, and prefix modifiers like sm: (640px), md: (768px), and lg: (1024px) enhance the layout as screen size increases.រចនា Mobile-first ជានិច្ច៖ Style ដើមសម្រាប់ Mobile ហើយប្រើ sm:, md:, lg: ដើម្បីពង្រីក Layout ពេលអេក្រង់ធំឡើង។
Fetching Data
Direct async/await data fetching in React Server Components.
export default async function InvoicesPage() {
// Directly awaited on the server during rendering
const res = await fetch("https://api.example.com/invoices", {
// Next.js caching options:
next: { revalidate: 60 }, // ISR: cache for 60 seconds
});
const invoices = await res.json();
return (
<div className="p-6">
<h1 className="text-xl font-bold">Invoices ({invoices.length})</h1>
{/* Render list */}
</div>
);
}
Native fetch() Enhancements
In Server Components, you do NOT need useEffect or loading spinners for initial data! Next.js extends the native Web fetch API to allow granular caching, revalidation, and request deduplication.ក្នុង Server Components អ្នកលែងត្រូវការ useEffect ទៀតហើយ! Next.js បានពង្រីក Web fetch() ឱ្យគាំទ្រ Caching, Revalidation និងកាត់បន្ថយ Request ស្ទួនដោយស្វ័យប្រវត្តិ។
Database Access
Direct database querying on the server without intermediary API endpoints.
import { sql } from "@/lib/db";
export default async function UsersPage() {
// Direct SQL query execution on the server!
const users = await sql`SELECT id, name, email FROM users ORDER BY created_at DESC LIMIT 10`;
return (
<div className="p-6">
<h2 className="text-xl font-bold">Registered Users</h2>
<ul className="mt-3 divide-y divide-slate-800">
{users.map((u) => (
<li key={u.id} className="py-2 text-sm">{u.name} ({u.email})</li>
))}
</ul>
</div>
);
}
No Extra API Layer Required
Because Server Components run securely on the server, you can query your database directly using SQL or an ORM like Prisma or Drizzle. You do not need to create an intermediate REST endpoint just to read data!ដោយសារ Server Components ដំណើរការលើ Server អ្នកអាច Query Database ផ្ទាល់តាម SQL ឬ ORM ដោយមិនបាច់បង្កើត REST API កណ្ដាលឱ្យហត់ឡើយ!
PostgreSQL & Cloud DBs
Connecting Next.js to PostgreSQL, Neon, and serverless databases.
import { neon } from "@neondatabase/serverless";
if (!process.env.DATABASE_URL) {
throw new Error("DATABASE_URL is missing in environment variables");
}
export const sql = neon(process.env.DATABASE_URL);
Modern Cloud Databases
Serverless Postgres providers like Neon and Supabase provide connection pooling over HTTP/WebSockets, making them perfect for serverless Next.js functions and Vercel edge runtime.Database ដូចជា Neon និង Supabase ផ្ដល់នូវ Connection Pooling តាម HTTP ដែលស័ក្តិសមបំផុតសម្រាប់ Serverless Next.js និង Vercel Edge Runtime។
Rendering in Next.js
Static, Dynamic, and Streaming rendering strategies explained.
Build Time Pre-render
Routes are rendered once at build time or revalidated incrementally. Best for blogs, docs, and public marketing pages.Render តែម្ដងពេល Build ឬ Revalidate តាមកាលកំណត់។ ល្អបំផុតសម្រាប់ប្លុក និងទំព័រព័ត៌មាន។
On-Demand Server Render
Routes are rendered for each user request. Best for user dashboards, personalized carts, and real-time feeds.Render ថ្មីរាល់ពេលមាន Request ពី User។ ល្អសម្រាប់ Dashboard និងទិន្នន័យជាក់ស្ដែង។
Progressive Delivery
HTML is progressively streamed from server to client as data becomes ready, reducing Time to First Byte (TTFB).បញ្ជូន HTML ជាបណ្ដើរៗពី Server ទៅ Browser ជួយឱ្យ User ឃើញ UI ភ្លាមៗមិនបាច់ចាំ។
Static vs Dynamic
Choosing between CDN cached static pages and fresh server requests.
cookies(), headers(), or read searchParams.Next.js នឹងប្ដូរ Route ទៅជា Dynamic ដោយស្វ័យប្រវត្តិកាលណាអ្នកប្រើ cookies(), headers() ឬអាន searchParams។Streaming & Suspense
Breaking down pages with React Suspense for progressive loading.
import { Suspense } from "react";
import RevenueChart from "./RevenueChart";
import { RevenueSkeleton } from "./Skeletons";
export default function DashboardPage() {
return (
<div className="p-6">
<h1 className="text-2xl font-bold">Analytics</h1>
{/* Streaming Boundary */}
<Suspense fallback={<RevenueSkeleton />}>
<RevenueChart />
</Suspense>
</div>
);
}
Instant Loading Skeletons
React <Suspense> breaks down your page into independent chunks. The browser immediately receives the shell and skeleton UI, and slow data components stream into place as soon as they finish!React Suspense បំបែកទំព័រជាចំណែកតូចៗ។ Browser នឹងទទួលបាន Skeleton UI ភ្លាមៗ ហើយទិន្នន័យដែលដំណើរការយឺតនឹង Stream ចូលតាមក្រោយពេលរួចរាល់។
loading.tsx
Automatic loading states and skeleton UI screens.
export default function Loading() {
return (
<div className="p-6 space-y-4 animate-pulse">
<div className="h-8 w-48 bg-slate-800" />
<div className="grid grid-cols-3 gap-4">
<div className="h-32 bg-slate-800" />
<div className="h-32 bg-slate-800" />
<div className="h-32 bg-slate-800" />
</div>
</div>
);
}
Zero-Config Suspense Boundary
Adding a loading.tsx file automatically wraps your entire page.tsx in a React Suspense boundary. Next.js displays this skeleton immediately on navigation while the server prepares page data.ការបង្កើត loading.tsx នឹងរុំ page.tsx ក្នុង React Suspense ដោយស្វ័យប្រវត្តិ។ User នឹងឃើញ Skeleton ភ្លាមៗពេលចុចចូលទំព័រនោះ។
error.tsx
Graceful error boundaries and recovery handling.
"use client";
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<div className="p-8 text-center bg-red-950/20 border border-red-800/40">
<h2 className="text-xl font-bold text-red-400">Something went wrong!</h2>
<p className="text-xs text-slate-400 mt-1">{error.message}</p>
<button
onClick={() => reset()}
className="mt-4 px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-mono text-xs"
>
Try again
</button>
</div>
);
}
Isolated Error Recovery
error.tsx must always be a Client Component ("use client"). It catches runtime errors without crashing the whole application, allowing users to retry via reset().error.tsx ត្រូវតែជា Client Component។ វាចាប់យក Error ដោយមិនធ្វើឱ្យគាំងទំព័រទាំងមូល និងផ្ដល់ប៊ូតុង reset() ដើម្បីសាកល្បងម្ដងទៀត។
notFound() & not-found.tsx
Gracefully handling 404 not found states.
import { notFound } from "next/navigation";
import { getProduct } from "@/lib/db";
export default async function ProductPage({ params }: any) {
const { id } = await params;
const product = await getProduct(id);
// Trigger 404 if item doesn't exist
if (!product) {
notFound();
}
return <h1>{product.name}</h1>;
}
Custom 404 Handlers
Calling notFound() immediately halts rendering and displays your customized not-found.tsx file with proper HTTP 404 status codes for search engines.ការហៅ notFound() នឹងបង្ហាញទំព័រ not-found.tsx ភ្លាមៗជាមួយកូដ HTTP 404 ត្រឹមត្រូវសម្រាប់ Search Engines។
Reading vs Changing Data
Understanding the mental model of reads and writes in App Router.
Server Components & async/await
Reading data happens directly in Server Components during rendering. No client JavaScript overhead or boilerplate state hooks required.ការអានទិន្នន័យធ្វើឡើងក្នុង Server Components ផ្ទាល់ពេល Render។ មិនត្រូវការ boilerplate code ឬ state ស្មុគស្មាញឡើយ។
Server Actions & Forms
Creating, updating, and deleting data is handled securely by Server Actions invoked directly from native forms or button handlers.ការបង្កើត កែប្រែ និងលុបទិន្នន័យ ត្រូវបានធ្វើឡើងដោយសុវត្ថិភាពតាមរយៈ Server Actions ពី Form ឬ Button។
Server Action Concept
Defining asynchronous mutations with the "use server" directive.
"use server";
import { sql } from "@/lib/db";
import { revalidatePath } from "next/cache";
export async function createTask(formData: FormData) {
const title = formData.get("title") as string;
if (!title || title.trim().length === 0) {
throw new Error("Title is required");
}
// Secure server-side database insertion
await sql`INSERT INTO tasks (title, completed) VALUES (${title}, false)`;
// Instant cache revalidation!
revalidatePath("/dashboard/tasks");
}
Asynchronous Server Mutations
The "use server" directive defines functions that run exclusively on the server. You can pass them directly to HTML forms. Next.js handles POST request serialization automatically!ពាក្យបញ្ជា "use server" បង្កើត function ដែលដំណើរការលើ Server។ អ្នកអាចហៅវាពី Form ដោយផ្ទាល់ ហើយ Next.js នឹងចាត់ចែង POST Request ដោយស្វ័យប្រវត្តិ!
Form + Server Action
Connecting native HTML forms directly to server action mutations.
import { createTask } from "@/app/actions/tasks";
export function TaskForm() {
return (
<form action={createTask} className="flex gap-2">
<input
type="text"
name="title"
placeholder="Enter new task..."
required
className="px-3 py-2 bg-slate-900 border border-slate-700 text-sm flex-1"
/>
<button type="submit" className="px-4 py-2 bg-blue-600 text-white text-sm font-bold">
Add Task
</button>
</form>
);
}
Live Simulated Server Action
URL Search Parameters
Managing shareable search queries and pagination via the URL.
export default async function InvoicesPage({
searchParams,
}: {
searchParams: Promise<{ query?: string; page?: string }>;
}) {
const { query = "", page = "1" } = await searchParams;
// Query DB filtered by search params
const invoices = await fetchInvoices(query, Number(page));
return (
<div>
<SearchInput defaultValue={query} />
<InvoiceTable invoices={invoices} />
<Pagination currentPage={Number(page)} />
</div>
);
}
Live SearchParams Simulator
Type below to see URL query string update:
Authentication Architecture
Modern session management, HttpOnly cookies, and security flow.
Secure Cookie Sessions
Modern Next.js auth stores session tokens in HttpOnly, Secure cookies. Unlike localStorage, HttpOnly cookies cannot be stolen by client-side XSS attacks.Auth ក្នុង Next.js ប្រើ HttpOnly Cookies ដើម្បីរក្សាទុក Session Token។ ខុសពី localStorage, HttpOnly Cookies មិនអាចត្រូវបានលួចដោយ XSS Script ឡើយ។
Industry Standards
Popular production choices include NextAuth.js (Auth.js), Clerk, Supabase Auth, or lightweight custom JWT session verifiers.ជម្រើសពេញនិយមសម្រាប់ Production មានដូចជា Auth.js, Clerk, Supabase Auth ឬ Custom JWT Session។
Public vs Protected Routes
Securing routes with Next.js edge middleware.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const sessionToken = request.cookies.get("session")?.value;
const isDashboard = request.nextUrl.pathname.startsWith("/dashboard");
// Protect private routes
if (isDashboard && !sessionToken) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};
Edge-Speed Route Interception
Next.js middleware.ts runs before a request completes. If an unauthenticated user tries to visit /dashboard, the middleware redirects them to /login before any page code even executes!middleware.ts ដំណើរការមុនពេល Request ទៅដល់ទំព័រ។ បើ User មិនទាន់ Login ព្យាយាមចូល /dashboard នោះ Middleware នឹងបញ្ជូនទៅ /login ភ្លាមៗ!
Environment Variables
Managing secrets safely with server-only vs NEXT_PUBLIC_ variables.
# SERVER ONLY (Secrets - never exposed to browser)
DATABASE_URL="postgres://user:pass@ep-cool.neon.tech/neondb"
AUTH_SECRET="super-secret-key-12345"
STRIPE_SECRET_KEY="sk_live_xyz..."
# CLIENT EXPOSED (Safe public values only)
NEXT_PUBLIC_APP_URL="https://taskflow.io"
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_live_abc..."
NEXT_PUBLIC_! Variables without that prefix remain strictly on the server.វិធានសុវត្ថិភាពសំខាន់៖ កុំប្រើ Prefix NEXT_PUBLIC_ លើ Database Password ឬ Secret Keys ឱ្យសោះ! បើគ្មាន Prefix នោះទេ វាមានសុវត្ថិភាពលើ Server ជានិច្ច។Metadata API
Defining static and dynamic document metadata for search ranking.
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "About TaskFlow • Modern Task Management",
description: "Learn how TaskFlow empowers agile teams to ship faster.",
openGraph: {
title: "About TaskFlow",
description: "Built for modern developers.",
images: ["/og-about.png"],
},
};
export default function AboutPage() {
return <h1>About Us</h1>;
}
Built-in SEO Optimization
Exporting a metadata object injects the correct <title>, <meta name="description">, and Open Graph cards into the document <head> automatically.ការ Export metadata នឹងបង្កើត tag <title>, <meta> និង Open Graph ក្នុង tag <head> ដោយស្វ័យប្រវត្តិ។
SEO Best Practices
Building production sitemaps, robots rules, and social preview cards.
app/sitemap.ts
Generate a standard XML sitemap dynamically from your database records so Google indexers find every page.បង្កើត sitemap.xml ដោយស្វ័យប្រវត្តិពីទិន្នន័យក្នុង DB ដើម្បីឱ្យ Google ងាយស្រួល Index។
app/robots.ts
Define crawler indexing rules, disallow private admin routes, and link directly to your sitemap URL.កំណត់វិធាន robots.txt ដើម្បីការពារផ្លូវ Private និងប្រាប់ទីតាំង Sitemap ដល់ Search Engines។
Open Graph & Twitter
Generate automated share preview images using Next.js ImageResponse or static OG image assets.បង្កើតរូបភាព Preview ពេល Share លើ Facebook, Telegram ឬ X ដោយស្វ័យប្រវត្តិ។
next/image
High performance, zero-CLS responsive image optimization.
import Image from "next/image";
export function HeroBanner() {
return (
<Image
src="/hero-dashboard.png"
alt="TaskFlow SaaS Dashboard Preview"
width={1200}
height={630}
priority // High priority preloading for above-the-fold image
className="border border-slate-800 shadow-2xl"
/>
);
}
Automatic Image Optimizations
- • Converts PNG/JPEG to modern WebP & AVIF
- • Resizes images dynamically based on device screen
- • Zero Cumulative Layout Shift (CLS) via width/height
- • Lazy loads off-screen images automatically
next/font
Automatic font self-hosting and zero layout shift.
import { Plus_Jakarta_Sans, JetBrains_Mono } from "next/font/google";
const sans = Plus_Jakarta_Sans({
subsets: ["latin"],
variable: "--font-sans",
});
const mono = JetBrains_Mono({
subsets: ["latin"],
variable: "--font-mono",
});
export default function RootLayout({ children }: any) {
return (
<html lang="en" className={`${sans.variable} ${mono.variable}`}>
<body className="font-sans">{children}</body>
</html>
);
}
Zero External Font Requests
next/font downloads Google Fonts at build time and self-hosts them with your deployment assets. The browser never makes requests to Google servers, ensuring total privacy and eliminating layout shift!next/font ទាញយក Fonts មកទុកក្នុងកញ្ចប់ Build ដោយខ្លួនឯង។ Browser មិនចាំបាច់ផ្ញើ Request ទៅកាន់ Google ឡើយ ជួយការពារ Privacy និងគ្មាន Layout Shift។
Next.js as Full Stack
Unified full-stack architecture combining frontend, backend, and database.
Unified Repository
One language (TypeScript), one project structure, and one deployment pipeline for both frontend and backend.ប្រើភាសាតែមួយ (TypeScript) និង Project តែមួយ ទាំង Frontend និង Backend។
Shared Types
Database schemas and TypeScript types flow directly into UI components without code generation or API drift.Types និង Data Models ត្រូវបានប្រើរួមគ្នារវាង DB និង UI ដោយគ្មានការភាន់ច្រឡំ។
Edge & Serverless
Scales automatically to zero when idle and handles high traffic spikes seamlessly on cloud infrastructure.Auto-scale តាមតម្រូវការជាក់ស្ដែងលើ Serverless Cloud Infrastructure។
Route Handlers
Building REST endpoints and external webhook receivers with route.ts.
import { NextResponse } from "next/server";
import { sql } from "@/lib/db";
// Standard Web GET Handler
export async function GET(request: Request) {
const users = await sql`SELECT id, name, email FROM users`;
return NextResponse.json({ success: true, data: users });
}
// Standard Web POST Handler
export async function POST(request: Request) {
const body = await request.json();
const res = await sql`INSERT INTO users (name, email) VALUES (${body.name}, ${body.email}) RETURNING *`;
return NextResponse.json({ success: true, user: res[0] }, { status: 201 });
}
REST API & Webhooks
route.ts files create RESTful API endpoints using standard Web Request and Response objects. Use Route Handlers for mobile app APIs, public developer SDKs, and Stripe webhooks.route.ts បង្កើត REST API Endpoints តាមស្តង់ដារ Web Request/Response។ ប្រើវាសម្រាប់ Mobile App API ឬ Webhooks ដូចជា Stripe ជាដើម។
Security Basics
Core web security principles: validation, authorization, and sanitization.
Never Trust Input
Client-side validation is only for UX. Always validate and sanitize all form fields and parameters on the server using Zod.ការពិនិត្យកូដលើ Browser គឺសម្រាប់តែ UX ប៉ុណ្ណោះ។ ត្រូវ Validate ទិន្នន័យលើ Server ជានិច្ចដោយប្រើ Zod។
Check Permissions
Always verify that the authenticated user owns the resource before executing any SQL update or deletion.ត្រូវពិនិត្យមើលសិទ្ធិរបស់ User មុនពេលអនុញ្ញាតឱ្យកែប្រែ ឬលុបទិន្នន័យក្នុង Database។
Prevent Injections
Never concatenate raw strings into SQL queries. Always use tagged template literals or ORMs to ensure automatic escaping.កុំតភ្ជាប់ String ចូលក្នុង SQL Query ដោយផ្ទាល់។ ត្រូវប្រើ Parameterized Queries ដើម្បីការពារ SQL Injection។
Client vs Server Security
Understanding the security boundary between client and server.
Any user can inspect network traffic, edit DOM elements, and bypass client form checks.User អាចកែប្រែ DOM និងបន្លំទិន្នន័យលើ Browser បានយ៉ាងងាយ។
- • Do NOT put secret keys in Client Components
- • Do NOT perform authorization checks on client alone
Protected execution environment isolated behind reverse proxies and private networks.បរិស្ថានសុវត្ថិភាពខ្ពស់ មិនអាចមើលឃើញពីខាងក្រៅដោយគ្មានការអនុញ្ញាត។
- • Safely query PostgreSQL via private connection strings
- • Validate input schemas strictly with Zod
Real Application Structure
Production-grade folder architecture and route groups.
taskflow/ ├── app/ │ ├── (auth)/ # Route group (no URL impact) │ │ ├── login/page.tsx │ │ └── register/page.tsx │ ├── (dashboard)/ # Authenticated layout │ │ ├── layout.tsx │ │ ├── page.tsx │ │ └── tasks/page.tsx │ ├── api/ # Webhooks & public APIs │ ├── layout.tsx │ └── globals.css ├── actions/ # Server Actions (mutations) ├── components/ui/ # Design system components ├── lib/db.ts # Database connection client └── middleware.ts # Route protection guard
Route Groups (auth) & (dashboard)
Folders wrapped in parentheses like (auth) organize your routes without adding their folder name to the URL path. This allows separate layouts for public login pages vs internal app dashboards!Folder ក្នុងវង់ក្រចកដូចជា (auth) ជួយរៀបចំ Route ដោយមិនប៉ះពាល់ដល់ URL ឡើយ។ វាអនុញ្ញាតឱ្យយើងមាន Layout ដាច់ដោយឡែករវាង Login និង Dashboard!
TaskFlow Architecture
Architectural blueprint of our production task management application.
TaskFlow Features
A complete modern task management web application with authentication, real-time filters, PostgreSQL storage, and instant updates.កម្មវិធីគ្រប់គ្រងកិច្ចការងារពេញលេញ មានប្រព័ន្ធ Login, តម្រងស្វែងរក, រក្សាទុកក្នុង PostgreSQL និង Update ភ្លាមៗ។
App Router Patterns
Leverages Server Components for lightning-fast reads and Server Actions for zero-API mutation handling.ប្រើ Server Components សម្រាប់ទាញទិន្នន័យលឿន និង Server Actions សម្រាប់កែប្រែទិន្នន័យ។
Production Ready
Equipped with error boundaries, loading skeletons, responsive Tailwind UI, and Vercel edge deployment.រៀបចំជាមួយ Loading Skeletons, Error Boundary និងត្រៀមសម្រាប់ Deploy លើ Vercel។
TaskFlow Routes
Complete route specification and access matrix for TaskFlow.
| URL ROUTE | FILE LOCATION | PURPOSE & ACCESS |
|---|---|---|
| / | app/page.tsx | Public marketing landing page |
| /login | app/(auth)/login/page.tsx | User authentication form |
| /dashboard | app/(dashboard)/page.tsx | Private overview metrics (Protected) |
| /dashboard/tasks | app/(dashboard)/tasks/page.tsx | Task management list with search & filters |
| /dashboard/tasks/[id] | app/(dashboard)/tasks/[id]/page.tsx | Dynamic detail view and task editor |
TaskFlow Database
Relational database schema with PostgreSQL and indexes.
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE tasks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(500) NOT NULL,
completed BOOLEAN DEFAULT FALSE,
due_date DATE,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_tasks_user_id ON tasks(user_id);
Relational Data Modeling
Foreign key constraints enforce referential integrity between users and their tasks. Indexes on user_id ensure lightning-fast dashboard queries even with millions of records.ការប្រើ Foreign Key ធានានូវទំនាក់ទំនងត្រឹមត្រូវរវាង User និង Tasks។ Index លើ user_id ជួយឱ្យ Query ទិន្នន័យបានលឿនបំផុត។
TaskFlow Data Flow
End-to-end data mutation lifecycle from form to database and revalidation.
Why Next.js Can Be Fast
Architectural factors that power high performance in Next.js applications.
Zero Client Bundle
Server Components do not ship JavaScript to the client. The browser downloads and parses less code, leading to instant First Contentful Paint.Server Components មិនបញ្ជូនកូដ JavaScript ទៅ Browser ឡើយ ធ្វើឱ្យទំព័រដំណើរការលឿនខ្លាំង។
Parallel Data Pipelines
Pages stream progressively over HTTP/2, letting users interact with parts of the page before slow data finishes loading.ទំព័រ Stream តាម HTTP/2 ធ្វើឱ្យ User អាចចុចលើទំព័របាន ទោះបីជាទិន្នន័យខ្លះកំពុងដំណើរការក៏ដោយ។
Vercel Edge Network
Static routes and cached assets are served from hundreds of Edge CDN locations worldwide within milliseconds.ទំព័រ Static ត្រូវបានរក្សាទុកលើ Edge CDN ទូទាំងពិភពលោក ផ្ដល់ការឆ្លើយតបត្រឹមតែប៉ុន្មាន Millisecond។
Avoid Unnecessary Client Components
Pushing the "use client" boundary down to interactive leaf components.
// app/dashboard/page.tsx
"use client"; // Marks whole page as client!
export default function Dashboard() {
// Now entire tree ships to client bundle
return <div>...</div>;
}
// app/dashboard/page.tsx (Server Component)
import { LikeButton } from "./LikeButton"; // "use client"
export default async function Dashboard() {
const data = await getDbData();
return <div><LikeButton /></div>;
}
Production Build
Building and previewing the optimized production bundle.
Build Output Inspection
npm run build validates all TypeScript types, optimizes bundles, and generates the build summary indicating which routes are Static (○) vs Dynamic (ƒ). Test locally with npm run start.npm run build ពិនិត្យ TypeScript, Optimize JS bundles និងបង្ហាញថាតើ Route ណាជា Static (○) ឬ Dynamic (ƒ)។ សាកល្បងដោយ npm run start។
GitHub Workflow
Pushing branches and triggering continuous integration from GitHub.
Connection to Git & GitHub
Following our previous Git course, every production Next.js project is version-controlled with Git. Pushing your branch to GitHub automatically triggers continuous integration and preview deployments!ដូចដែលបានរៀនក្នុងវគ្គ Git កន្លងមក គ្រប់គម្រោង Next.js ត្រូវគ្រប់គ្រងដោយ Git។ ការ Push ទៅ GitHub នឹងបញ្ឆេះ CI/CD និងបង្កើត Preview Deployment ដោយស្វ័យប្រវត្តិ!
Vercel Deployment
Zero-config Git integration, automatic builds, and preview environments.
Zero Configuration
Import your GitHub repo into Vercel and it configures build commands and output directories automatically.ភ្ជាប់ GitHub Repo ទៅកាន់ Vercel វានឹងរៀបចំការ Build និង Deploy ដោយមិនបាច់ Config អ្វីឡើយ។
Preview Environments
Every pull request receives a unique preview URL for testing before merging to production.រាល់ Pull Request ទទួលបាន Preview URL ផ្ទាល់ខ្លួនសម្រាប់ Test មុនពេល Merge។
Instant Rollbacks
Revert to any previous deployment instantly with a single click if an issue ever occurs.អាច Rollback ទៅកាន់ Deployment ចាស់វិញបានភ្លាមៗបើមានបញ្ហាកើតឡើង។
Develop -> Preview -> Ship
The complete modern full-stack shipping cycle.
Mistake: Everything Is Client
Why excessive client components degrade performance and bundle sizes.
Beginners often add "use client" to every file as soon as they encounter any issue. This converts your app back into a heavy client SPA, discarding all performance and SEO benefits of Server Components!អ្នកទើបរៀនតែងតែដាក់ "use client" លើគ្រប់ file។ ការធ្វើបែបនេះធ្វើឱ្យ Next.js ក្លាយជា Client SPA ធម្មតាវិញ និងបាត់បង់អត្ថប្រយោជន៍ល្បឿនទាំងអស់!
Only introduce "use client" when you explicitly need useState, useEffect, or click event handlers. Keep all layouts and pages as Server Components.ប្រើ "use client" តែពេលត្រូវការ useState, useEffect ឬ Click Handler ពិតប្រាកដប៉ុណ្ណោះ។ ទុក Layouts និង Pages ជា Server Components ជានិច្ច។
Mistake: Exposing Secrets
Preventing accidental credential leaks via NEXT_PUBLIC_ prefixes.
Prefixing secret keys with NEXT_PUBLIC_ embeds them directly into the public JavaScript bundle downloaded by every visitor!ការដាក់ Prefix NEXT_PUBLIC_ លើ Secret Key នឹងបញ្ជូន Password នោះទៅកាន់ Browser របស់មនុស្សគ្រប់គ្នា!
Without the prefix, Next.js prevents this variable from ever leaking to the browser window.បើគ្មាន Prefix ទេ Next.js នឹងរក្សាទុក Variable នោះលើ Server ដោយសុវត្ថិភាព 100%។
Mistake: No Server Validation
Why client-side form validation is never sufficient for security.
Mistake: Poor Folder Architecture
Avoiding disorganized directories and maintainability nightmares.
components/
components2/
final_ui/
old_code/
test_page/
app/
components/ui/
actions/
lib/
types/
Debugging Next.js
Mastering tools for diagnosing server and client execution issues.
Server Logs
Console.log inside Server Components and Server Actions prints directly to your VS Code terminal, not browser.Console.log លើ Server Components បង្ហាញក្នុង Terminal មិនមែនលើ Browser ឡើយ។
Component Tree
Inspect props, state, and client component boundaries visually in your browser DevTools extension.ពិនិត្យមើល Props, State និង Component Tree តាមរយៈ Extension React DevTools។
RSC Payload
Inspect the React Server Component payload streams and Server Action POST requests in real-time.ពិនិត្យមើល Payload របស់ Server Components និង Server Action ក្នុង Network Tab។
TypeScript Debug
Set breakpoints in original TypeScript source files directly inside Chrome DevTools or VS Code debugger.ដាក់ Breakpoint លើកូដ TypeScript ដើមក្នុង Chrome ឬ VS Code Debugger។
Common Errors & Fixes
Diagnosing hydration mismatches, missing directives, and boundary errors.
| ERROR MESSAGE | COMMON ROOT CAUSE | PROVEN FIX |
|---|---|---|
| Hydration failed because initial UI does not match | Using browser values (window, Date.now()) during server render | Move browser checks into useEffect or use suppressHydrationWarning |
| window is not defined | Accessing browser window API inside a Server Component | Add "use client" directive or check typeof window !== "undefined" |
| Event handlers cannot be passed to Client Component props | Passing function props across Server to Client boundary | Use Server Actions or declare event handlers inside the Client Component |
Modern Next.js Architecture
Master architectural diagram connecting all full-stack layers.
Next.js Commands Cheat Sheet
Essential CLI commands for daily development and deployment.
Next.js Special Files
Reference summary of App Router special file conventions.
| FILE CONVENTION | ROLE IN APP ROUTER | EXECUTION DEFAULT |
|---|---|---|
| page.tsx | Defines the unique UI for a route segment | Server Component |
| layout.tsx | Shared UI wrapper that preserves state across navigation | Server Component |
| loading.tsx | Instant loading skeleton wrapped in React Suspense | Server Component |
| error.tsx | Error boundary UI for catching runtime exceptions | Client Component ("use client") |
| not-found.tsx | Custom 404 page rendered when notFound() is invoked | Server Component |
| route.ts | RESTful API endpoint responding with Request/Response | Server Route Handler |
Next.js Core Concepts
Comprehensive summary of core concepts mastered in this course.
- • App Router folders
- • Server Components
- • "use client" boundaries
- • Streaming & Suspense
- • Server async/await
- • Direct PostgreSQL queries
- • Server Actions ("use server")
- • revalidatePath cache
- • next/image & next/font
- • Metadata API & SEO
- • Middleware auth guards
- • Vercel edge deployment
Final Challenge: Build Your Own SaaS
Comprehensive project requirements for the TaskFlow application.
- User Authentication (Register & Login)
- Protected Dashboard layout with Middleware
- PostgreSQL Database integration via Neon
- Server Actions for Creating & Updating Tasks
- Search query & pagination via searchParams
- Loading skeleton & Error boundary recovery
- Production deployment to Vercel via GitHub
Put Theory Into Practice
Building TaskFlow will solidify your understanding of real-world full-stack Next.js engineering. Complete this project and add it to your portfolio!ការអនុវត្តបង្កើត TaskFlow នឹងពង្រឹងសមត្ថភាព Full-Stack Next.js របស់អ្នកឱ្យកាន់តែច្បាស់។ បញ្ចប់គម្រោងនេះដើម្បីដាក់ក្នុង Portfolio របស់អ្នក!
Development Roadmap
Your complete full-stack web developer journey from fundamentals to production.
Final Message
Closing congratulations and call to action for production builders.
"Learn the fundamentals. Understand the architecture. Build real applications. Ship to production." "រៀនមូលដ្ឋានឱ្យរឹងមាំ។ យល់ពី Architecture។ បង្កើត Application ពិតប្រាកដ។ ហើយ Deploy ទៅ Production។"
Congratulations on completing the Next.js Mastery Course. You now possess the architectural foundation and hands-on skills to engineer world-class full-stack applications. សូមអបអរសាទរដែលបានបញ្ចប់វគ្គសិក្សា Next.js Mastery! ឥឡូវនេះអ្នកមានចំណេះដឹងរឹងមាំក្នុងការបង្កើត Full-Stack Web Applications កម្រិតពិភពលោក។