SECTION 01 — WEB TO NEXT.JS
1 / 75
SECTION 01 — WEB TO NEXT.JS • SLIDE 01 / 75

Next.js: From React to Production

Build modern full-stack web applications with React and Next.js App Router.

Next.js App Router
PRODUCTION-READY FULL-STACK FRAMEWORK FRAMEWORK ពេញលេញសម្រាប់ PRODUCTION

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 ដោយរលូន។

Core Stack App Router
React 19 • TS
Server Components
Server Actions
PostgreSQL • Neon
Bilingual English • Khmer Support • Press F for Fullscreen
SECTION 01 — WEB TO NEXT.JS • SLIDE 02 / 75

What You Will Learn

The complete path from React basics to full-stack production architecture.

Next.js App Router
React Fundamentals
→
Next.js App Router
→
Routing & Layouts
→
Server Components
→
Data Fetching
→
PostgreSQL DB
→
Authentication
→
Vercel Production

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។

SECTION 01 — WEB TO NEXT.JS • SLIDE 03 / 75

What Is Next.js?

Understanding the full-stack React framework and its core capabilities.

Next.js App Router

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។

Official Definition: Next.js is a React framework for building full-stack web applications. You use React Components to build user interfaces, and Next.js for additional features and optimizations.និយមន័យផ្លូវការ៖ Next.js គឺជា React framework សម្រាប់បង្កើត full-stack web applications។ អ្នកប្រើ React ដើម្បីបង្កើត UI និងប្រើ Next.js សម្រាប់មុខងារ full-stack និងការបង្កើនល្បឿន។
Next.js Built-in Capabilities
  • 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
SECTION 01 — WEB TO NEXT.JS • SLIDE 04 / 75

React vs Next.js

Detailed architectural comparison between React and Next.js.

Next.js App Router
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
React UI Library
+
Next.js Framework Architecture
=
Production Full-Stack Application
SECTION 01 — WEB TO NEXT.JS • SLIDE 05 / 75

When Should You Use Next.js?

Primary use cases and production scenarios where Next.js excels.

Next.js App Router
01 • SAAS PLATFORMS

Web Applications

Multi-tenant software, subscription dashboards, complex authenticated workflows, and rich data visualization.កម្មវិធី SaaS, ប្រព័ន្ធ Dashboard មាន Login, ការគ្រប់គ្រងទិន្នន័យស្មុគស្មាញ និងទាមទារសុវត្ថិភាពខ្ពស់។

02 • E-COMMERCE

Online Stores

Instant page loads via static rendering for products, dynamic cart interactions, and superior SEO for high search ranking.ហាងលក់ទំនិញអនឡាញ ទាមទារល្បឿនលឿនខ្លាំង (SEO) និងការទាញទិន្នន័យស្តុកតាម Real-time។

03 • CONTENT & CMS

Blogs & News

Content sites requiring incremental static regeneration, dynamic markdown rendering, and instant image optimization.គេហទំព័រព័ត៌មាន ប្លុក ឬ Documentation ដែលត្រូវការ SEO ល្អ និងការ Render អត្ថបទរហ័ស។

04 • INTERNAL TOOLS

Admin Portals

Internal company portals, inventory trackers, and CRM systems with direct PostgreSQL database connections.ប្រព័ន្ធគ្រប់គ្រងផ្ទៃក្នុងក្រុមហ៊ុន (Admin CRM / ERP) ដែលភ្ជាប់ទៅកាន់ PostgreSQL ដោយផ្ទាល់។

SECTION 02 — REQUIREMENTS • SLIDE 06 / 75

Before Learning Next.js

Prerequisites and recommended background knowledge.

Next.js App Router

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។

Good News: You do NOT need advanced React state machines or external router knowledge. Next.js simplifies routing and data fetching compared to old client SPAs!ដំណឹងល្អ៖ អ្នកមិនចាំបាច់ចេះបណ្ណាល័យ Router ស្មុគស្មាញនោះទេ! Next.js ជួយសម្រួល Routing និង Data Fetching ឱ្យកាន់តែងាយស្រួល។
Prerequisite Checklist
1. HTML5 & Semantic Elements Required
2. Modern CSS & Tailwind CSS Required
3. JavaScript ES6+ (Async, Arrow, Destructuring) Required
4. React Core Basics (JSX, Components, Props) Required
SECTION 02 — REQUIREMENTS • SLIDE 07 / 75

React Fundamentals You Need

The essential React building blocks required for Next.js App Router.

Next.js App Router
01 • COMPONENTS & JSX

Reusable UI Functions

Components are JavaScript functions returning JSX markup describing what the interface should look like.Components គឺជា functions ដែល return JSX ដើម្បីកំណត់ទម្រង់ UI។

02 • PROPS & CHILDREN

Data Transfer

Passing data from parent to child components via attributes and the special children prop.ការបញ្ជូនទិន្នន័យពី Parent ទៅកាន់ Child តាមរយៈ props និង children។

03 • STATE & HOOKS

Interactive Memory

Using useState and useEffect for client-side state and life-cycle events.ការប្រើប្រាស់ useState និង useEffect សម្រាប់រក្សាទុក state និងគ្រប់គ្រង lifecycle។

04 • EVENT LISTENERS

Handling Clicks & Inputs

Listening to user events via onClick, onChange, and onSubmit handlers.ការចាប់ព្រឹត្តិការណ៍របស់អ្នកប្រើប្រាស់ដូចជា onClick, onChange និង onSubmit។

05 • ASYNC / PROMISES

Asynchronous Data

Handling asynchronous JavaScript promises using modern async and await syntax.ការប្រើប្រាស់ async/await ដើម្បីរង់ចាំទិន្នន័យពី Network ឬ Database។

06 • SERVER VS CLIENT

Execution Boundaries

Understanding that code can run either on the server environment or in the browser window.ការបែងចែកថាតើកូដមួយណាត្រូវដំណើរការលើ Server ឬលើ Browser Client។

SECTION 03 — CREATE NEXT.JS PROJECT • SLIDE 08 / 75

Install Requirements

Setting up Node.js, package manager, and development tools.

Next.js App Router

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។

Check your installed version in terminal using node -v. If outdated, install the latest LTS release from nodejs.org.ពិនិត្យមើលកំណែ Node ក្នុង Terminal ដោយប្រើ node -v។ ប្រសិនបើយឺត សូមដំឡើងកំណែ LTS ចុងក្រោយពី nodejs.org។
Verify Developer Environment
$ node -v
v20.18.0 (LTS verified)
$ pnpm -v
9.12.0
$ git --version
git version 2.43.0
SECTION 03 — CREATE NEXT.JS PROJECT • SLIDE 09 / 75

Create a Next.js Application

Bootstrapping a modern full-stack project with create-next-app.

Next.js App Router
Bootstrap Next.js Project
$ npx create-next-app@latest my-app
# Interactive CLI Prompts:
? Would you like to use TypeScript? ... Yes
? Would you like to use ESLint? ... Yes
? Would you like to use Tailwind CSS? ... Yes
? Would you like your code inside a `src/` directory? ... No
? Would you like to use App Router? (recommended) ... Yes
? Would you like to use Turbopack for `next dev`? ... Yes
? Would you like to customize the import alias (@/*)? ... No

Recommended Configuration Options

The CLI sets up everything needed for modern development in seconds.CLI នឹងរៀបចំអ្វីៗទាំងអស់ដោយស្វ័យប្រវត្តិតែប៉ុន្មានវិនាទីប៉ុណ្ណោះ។

TypeScriptType safety
Tailwind CSSUtility styling
App RouterModern standard
TurbopackBlazing dev server
SECTION 03 — CREATE NEXT.JS PROJECT • SLIDE 10 / 75

Start Development Server

Launching the development server with Turbopack and Fast Refresh.

Next.js App Router
Start Local Development Server
$ cd my-app
$ npm run dev
▲ Next.js 15.0.0 (Turbopack)
- Local: http://localhost:3000
- Network: http://192.168.1.50:3000
Ready in 450ms
Compiling / ...
Compiled / in 120ms (482 modules)

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 ឡើយ។

SECTION 04 — PROJECT STRUCTURE • SLIDE 11 / 75

Next.js Project Structure

Understanding the App Router layout, folders, and configuration files.

Next.js App Router
my-app/ Directory Tree
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 រួម។

SECTION 04 — PROJECT STRUCTURE • SLIDE 12 / 75

app/page.tsx

The entry route file and main page component.

Next.js App Router
app/page.tsx
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 Component
Rule: The default export from page.tsx is the UI rendered for this route segment.វិធាន៖ Default export ពី page.tsx គឺជា UI ដែលត្រូវបង្ហាញសម្រាប់ Route Segment នោះ។
SECTION 04 — PROJECT STRUCTURE • SLIDE 13 / 75

app/layout.tsx

Root layout, shared UI, and global HTML shell.

Next.js App Router
app/layout.tsx
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 ឡើយ។

SECTION 05 — ROUTING • SLIDE 14 / 75

File-System Routing

How folders and pages map directly to public URLs.

Next.js App Router
Folders Map Directly to 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 នោះដោយស្វ័យប្រវត្តិ។

SECTION 05 — ROUTING • SLIDE 15 / 75

Nested Routes

Hierarchical route segments and nested UI layouts.

Next.js App Router
Nested Dashboard Structure
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 ឡើយ។

SECTION 05 — ROUTING • SLIDE 16 / 75

Dynamic Routes

Capturing URL parameters with dynamic folder segments [id].

Next.js App Router
app/products/[id]/page.tsx
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។

/products/123 → id = "123"
/products/macbook → id = "macbook"
SECTION 06 — NAVIGATION • SLIDE 17 / 75

Link Component

Client-side navigation and automatic background route prefetching.

Next.js App Router
app/ui/Navbar.tsx
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 ទិន្នន័យទំព័រនោះទុកជាមុន ធ្វើឱ្យការចុចបើកលឿនដូចផ្លេកបន្ទោរ!

SECTION 06 — NAVIGATION • SLIDE 18 / 75

Navigation Architecture

Application site hierarchy and active navigation highlighting.

Next.js App Router
Home (/)
•
Products (/products)
•
Product 1 (/products/1)
•
Dashboard (/dashboard)
•
Users (/dashboard/users)

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។

Active Nav Link Pattern
"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>
  );
}
SECTION 07 — COMPONENTS • SLIDE 19 / 75

What Is a Component?

Reusable UI building blocks in React and Next.js.

Next.js App Router
components/Button.tsx
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 ទៅជាដុំកូដដែលអាចយកទៅប្រើឡើងវិញនៅគ្រប់ទីកន្លែង។

SECTION 07 — COMPONENTS • SLIDE 20 / 75

Props

Passing dynamic data and children to reusable components.

Next.js App Router
components/Button.tsx with Props
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 ជួយពិនិត្យកំហុសកូដជាមុន។

Usage in Any Page
<Button variant="primary">Save Changes</Button>
<Button variant="secondary">Cancel</Button>
SECTION 07 — COMPONENTS • SLIDE 21 / 75

Component Architecture

Organizing components, modularity, and colocation best practices.

Next.js App Router
Recommended Component Organization
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/។

SECTION 08 — SERVER & CLIENT COMPONENTS • SLIDE 22 / 75

Server Components

Default server execution, direct async/await, and zero bundle size.

Next.js App Router
app/products/page.tsx (Server Component)
// 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 ឡើយ!

SECTION 08 — SERVER & CLIENT COMPONENTS • SLIDE 23 / 75

Client Components

Using the "use client" directive for browser interactivity and state.

Next.js App Router
components/Counter.tsx (Client Component)
"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 ជាក់ស្ដែងនៅទីនេះ៖

Count: 0
The "use client" directive marks the boundary between server-rendered code and browser-interactive code.ពាក្យបញ្ជា "use client" កំណត់ព្រំដែនរវាងកូដ Server និងកូដ Interactive លើ Browser។
SECTION 08 — SERVER & CLIENT COMPONENTS • SLIDE 24 / 75

Server vs Client

Direct comparison of capabilities, environments, and performance impacts.

Next.js App Router
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)
SECTION 08 — SERVER & CLIENT COMPONENTS • SLIDE 25 / 75

Choosing Server or Client

A decision tree to determine component boundaries.

Next.js App Router
Does this component need interactivity, state, or browser APIs?
YES ↓
Client Component ("use client")
Buttons, dropdowns, forms with live state
NO ↓
Server Component (Default)
Data fetching, static cards, layouts, footers
Best Practice: Keep Client Components at the leaves of your component tree. Fetch data in the Server Component parent and pass it down as props.វិធីសាស្ត្រល្អបំផុត៖ ប្រើ Client Components តែនៅចុងស្លឹកនៃ Component Tree (ដូចជា Button, Dialog) និងរក្សា Parent ឱ្យនៅជា Server Component។
SECTION 09 — STYLING • SLIDE 26 / 75

Tailwind CSS in Next.js

Modern utility-first styling configured with zero setup overhead.

Next.js App Router
components/DashboardCard.tsx
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 ណាដែលបានប្រើប៉ុណ្ណោះ។

Total Users
24,520 +18.2%
SECTION 09 — STYLING • SLIDE 27 / 75

Responsive UI

Building adaptable, mobile-first layouts with Tailwind breakpoints.

Next.js App Router
app/dashboard/page.tsx (Responsive Grid)
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 ពេលអេក្រង់ធំឡើង។

SECTION 10 — DATA FETCHING • SLIDE 28 / 75

Fetching Data

Direct async/await data fetching in React Server Components.

Next.js App Router
app/invoices/page.tsx
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 ស្ទួនដោយស្វ័យប្រវត្តិ។

SECTION 10 — DATA FETCHING • SLIDE 29 / 75

Database Access

Direct database querying on the server without intermediary API endpoints.

Next.js App Router
app/users/page.tsx (Direct SQL Query)
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 កណ្ដាលឱ្យហត់ឡើយ!

SECTION 10 — DATA FETCHING • SLIDE 30 / 75

PostgreSQL & Cloud DBs

Connecting Next.js to PostgreSQL, Neon, and serverless databases.

Next.js App Router
lib/db.ts (Neon PostgreSQL Driver)
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។

SECTION 11 — RENDERING • SLIDE 31 / 75

Rendering in Next.js

Static, Dynamic, and Streaming rendering strategies explained.

Next.js App Router
01 • STATIC RENDERING

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 តាមកាលកំណត់។ ល្អបំផុតសម្រាប់ប្លុក និងទំព័រព័ត៌មាន។

02 • DYNAMIC RENDERING

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 និងទិន្នន័យជាក់ស្ដែង។

03 • STREAMING UI

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 ភ្លាមៗមិនបាច់ចាំ។

SECTION 11 — RENDERING • SLIDE 32 / 75

Static vs Dynamic

Choosing between CDN cached static pages and fresh server requests.

Next.js App Router
STATIC (DEFAULT)
Generated at Build & Cached on CDN
• Fastest possible TTFB • Low server costs
VS
DYNAMIC (REQUEST-TIME)
Executed on Server for Each Request
• Access cookies, headers, searchParams
Next.js automatically switches a route to Dynamic if you use dynamic functions like cookies(), headers(), or read searchParams.Next.js នឹងប្ដូរ Route ទៅជា Dynamic ដោយស្វ័យប្រវត្តិកាលណាអ្នកប្រើ cookies(), headers() ឬអាន searchParams។
SECTION 11 — RENDERING • SLIDE 33 / 75

Streaming & Suspense

Breaking down pages with React Suspense for progressive loading.

Next.js App Router
app/dashboard/page.tsx with Suspense
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 ចូលតាមក្រោយពេលរួចរាល់។

SECTION 12 — LOADING & ERRORS • SLIDE 34 / 75

loading.tsx

Automatic loading states and skeleton UI screens.

Next.js App Router
app/dashboard/loading.tsx
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 ភ្លាមៗពេលចុចចូលទំព័រនោះ។

SECTION 12 — LOADING & ERRORS • SLIDE 35 / 75

error.tsx

Graceful error boundaries and recovery handling.

Next.js App Router
app/dashboard/error.tsx
"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() ដើម្បីសាកល្បងម្ដងទៀត។

SECTION 12 — LOADING & ERRORS • SLIDE 36 / 75

notFound() & not-found.tsx

Gracefully handling 404 not found states.

Next.js App Router
app/products/[id]/page.tsx
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។

SECTION 13 — SERVER ACTIONS / MUTATIONS • SLIDE 37 / 75

Reading vs Changing Data

Understanding the mental model of reads and writes in App Router.

Next.js App Router
READ OPERATIONS

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 ស្មុគស្មាញឡើយ។

WRITE MUTATIONS

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។

SECTION 13 — SERVER ACTIONS / MUTATIONS • SLIDE 38 / 75

Server Action Concept

Defining asynchronous mutations with the "use server" directive.

Next.js App Router
app/actions/tasks.ts
"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 ដោយស្វ័យប្រវត្តិ!

SECTION 13 — SERVER ACTIONS / MUTATIONS • SLIDE 39 / 75

Form + Server Action

Connecting native HTML forms directly to server action mutations.

Next.js App Router
components/TaskForm.tsx
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

Ready to invoke server action
Initial Task: Build SaaS UI
SECTION 14 — SEARCH & PAGINATION • SLIDE 40 / 75

URL Search Parameters

Managing shareable search queries and pagination via the URL.

Next.js App Router
app/invoices/page.tsx
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:

Current URL: /dashboard/invoices
Using URL state makes pages bookmarkable, shareable, and supports browser back/forward buttons naturally!ការប្រើ URL State ជួយឱ្យ User អាច Share Link, Bookmark និងប្រើប៊ូតុង Back/Forward របស់ Browser បានយ៉ាងត្រឹមត្រូវ!
SECTION 15 — AUTHENTICATION • SLIDE 41 / 75

Authentication Architecture

Modern session management, HttpOnly cookies, and security flow.

Next.js App Router
User Login Form
→
Server Action Validate
→
Create HttpOnly Cookie
→
Middleware Guard
→
Protected Dashboard

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។

SECTION 15 — AUTHENTICATION • SLIDE 42 / 75

Public vs Protected Routes

Securing routes with Next.js edge middleware.

Next.js App Router
middleware.ts (Route Guard)
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 ភ្លាមៗ!

SECTION 16 — ENVIRONMENT VARIABLES • SLIDE 43 / 75

Environment Variables

Managing secrets safely with server-only vs NEXT_PUBLIC_ variables.

Next.js App Router
.env.local
# 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..."
Critical Security Rule: Never prefix database passwords or private API tokens with NEXT_PUBLIC_! Variables without that prefix remain strictly on the server.វិធានសុវត្ថិភាពសំខាន់៖ កុំប្រើ Prefix NEXT_PUBLIC_ លើ Database Password ឬ Secret Keys ឱ្យសោះ! បើគ្មាន Prefix នោះទេ វាមានសុវត្ថិភាពលើ Server ជានិច្ច។
SECTION 17 — SEO & METADATA • SLIDE 44 / 75

Metadata API

Defining static and dynamic document metadata for search ranking.

Next.js App Router
app/about/page.tsx
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "About TaskFlow &bull; 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> ដោយស្វ័យប្រវត្តិ។

SECTION 17 — SEO & METADATA • SLIDE 45 / 75

SEO Best Practices

Building production sitemaps, robots rules, and social preview cards.

Next.js App Router
01 • SITEMAP GENERATION

app/sitemap.ts

Generate a standard XML sitemap dynamically from your database records so Google indexers find every page.បង្កើត sitemap.xml ដោយស្វ័យប្រវត្តិពីទិន្នន័យក្នុង DB ដើម្បីឱ្យ Google ងាយស្រួល Index។

02 • ROBOTS RULES

app/robots.ts

Define crawler indexing rules, disallow private admin routes, and link directly to your sitemap URL.កំណត់វិធាន robots.txt ដើម្បីការពារផ្លូវ Private និងប្រាប់ទីតាំង Sitemap ដល់ Search Engines។

03 • SOCIAL CARDS

Open Graph & Twitter

Generate automated share preview images using Next.js ImageResponse or static OG image assets.បង្កើតរូបភាព Preview ពេល Share លើ Facebook, Telegram ឬ X ដោយស្វ័យប្រវត្តិ។

SECTION 18 — IMAGES & FONTS • SLIDE 46 / 75

next/image

High performance, zero-CLS responsive image optimization.

Next.js App Router
components/HeroBanner.tsx
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
SECTION 18 — IMAGES & FONTS • SLIDE 47 / 75

next/font

Automatic font self-hosting and zero layout shift.

Next.js App Router
app/layout.tsx (Google Fonts Self-Hosting)
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។

SECTION 19 — API / BACKEND • SLIDE 48 / 75

Next.js as Full Stack

Unified full-stack architecture combining frontend, backend, and database.

Next.js App Router
React UI (Client & Server)
←→
Next.js App Server (Actions & Handlers)
←→
PostgreSQL Database (Neon)

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។

SECTION 19 — API / BACKEND • SLIDE 49 / 75

Route Handlers

Building REST endpoints and external webhook receivers with route.ts.

Next.js App Router
app/api/users/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 ជាដើម។

SECTION 20 — SECURITY • SLIDE 50 / 75

Security Basics

Core web security principles: validation, authorization, and sanitization.

Next.js App Router
RULE 01 • UNTRUSTED CLIENT

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។

RULE 02 • AUTHORIZE EVERY ACTION

Check Permissions

Always verify that the authenticated user owns the resource before executing any SQL update or deletion.ត្រូវពិនិត្យមើលសិទ្ធិរបស់ User មុនពេលអនុញ្ញាតឱ្យកែប្រែ ឬលុបទិន្នន័យក្នុង Database។

RULE 03 • SQL PARAMETERIZATION

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។

SECTION 20 — SECURITY • SLIDE 51 / 75

Client vs Server Security

Understanding the security boundary between client and server.

Next.js App Router
CLIENT BROWSER (UNTRUSTED)

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
NEXT.JS SERVER (TRUSTED)

Protected execution environment isolated behind reverse proxies and private networks.បរិស្ថានសុវត្ថិភាពខ្ពស់ មិនអាចមើលឃើញពីខាងក្រៅដោយគ្មានការអនុញ្ញាត។

  • • Safely query PostgreSQL via private connection strings
  • • Validate input schemas strictly with Zod
SECTION 21 — PROJECT ARCHITECTURE • SLIDE 52 / 75

Real Application Structure

Production-grade folder architecture and route groups.

Next.js App Router
Production SaaS Folder Layout
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!

SECTION 22 — BUILD A REAL PROJECT • SLIDE 53 / 75

TaskFlow Architecture

Architectural blueprint of our production task management application.

Next.js App Router
Next.js 15 Frontend (Tailwind UI)
←→
Server Actions & React Server Components
←→
Neon PostgreSQL (Serverless)

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។

SECTION 22 — BUILD A REAL PROJECT • SLIDE 54 / 75

TaskFlow Routes

Complete route specification and access matrix for TaskFlow.

Next.js App Router
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
SECTION 22 — BUILD A REAL PROJECT • SLIDE 55 / 75

TaskFlow Database

Relational database schema with PostgreSQL and indexes.

Next.js App Router
PostgreSQL Schema (Neon)
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 ទិន្នន័យបានលឿនបំផុត។

SECTION 22 — BUILD A REAL PROJECT • SLIDE 56 / 75

TaskFlow Data Flow

End-to-end data mutation lifecycle from form to database and revalidation.

Next.js App Router
1. User Submits Form
→
2. Server Action (createTask)
→
3. Zod Validate Input
→
4. SQL Insert (PostgreSQL)
→
5. revalidatePath()
→
6. UI Updates Instantly
The Power of revalidatePath: Notice that no manual client state updates or cache invalidation libraries were needed! Next.js re-renders the server component and streams the updated HTML list automatically.អត្ថប្រយោជន៍នៃ revalidatePath៖ អ្នកមិនបាច់សរសេរកូដ Update State ដោយដៃឡើយ! Next.js នឹង Re-render Server Component និងបញ្ជូនបញ្ជីទិន្នន័យថ្មីមកកាន់ UI ដោយស្វ័យប្រវត្តិ។
SECTION 23 — PERFORMANCE • SLIDE 57 / 75

Why Next.js Can Be Fast

Architectural factors that power high performance in Next.js applications.

Next.js App Router
01 • MINIMAL JS

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 ឡើយ ធ្វើឱ្យទំព័រដំណើរការលឿនខ្លាំង។

02 • EDGE STREAMING

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 អាចចុចលើទំព័របាន ទោះបីជាទិន្នន័យខ្លះកំពុងដំណើរការក៏ដោយ។

03 • GLOBAL CACHING

Vercel Edge Network

Static routes and cached assets are served from hundreds of Edge CDN locations worldwide within milliseconds.ទំព័រ Static ត្រូវបានរក្សាទុកលើ Edge CDN ទូទាំងពិភពលោក ផ្ដល់ការឆ្លើយតបត្រឹមតែប៉ុន្មាន Millisecond។

SECTION 23 — PERFORMANCE • SLIDE 58 / 75

Avoid Unnecessary Client Components

Pushing the "use client" boundary down to interactive leaf components.

Next.js App Router
POOR PATTERN: Client at the Root
// 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>;
}
    
RECOMMENDED: Client at Leaf Nodes
// 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>;
}
    
SECTION 24 — DEPLOYMENT • SLIDE 59 / 75

Production Build

Building and previewing the optimized production bundle.

Next.js App Router
Create Production Build
$ npm run build
▲ Next.js 15.0.0
Route (app) Size First Load JS
┌ ○ / 5.2 kB 92.4 kB
├ ○ /_not-found 872 B 88.1 kB
├ ƒ /dashboard 1.4 kB 95.2 kB
└ ƒ /dashboard/tasks 2.1 kB 96.8 kB
+ First Load JS shared by all 87.2 kB
○ (Static) prerendered as static content
ƒ (Dynamic) server-rendered on demand
Done: Compiled successfully

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។

SECTION 24 — DEPLOYMENT • SLIDE 60 / 75

GitHub Workflow

Pushing branches and triggering continuous integration from GitHub.

Next.js App Router
Git Workflow for Next.js
$ git checkout -b feature/taskflow-auth
$ git status
$ git add .
$ git commit -m "feat: implement auth middleware and server actions"
$ git push origin feature/taskflow-auth

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 ដោយស្វ័យប្រវត្តិ!

SECTION 24 — DEPLOYMENT • SLIDE 61 / 75

Vercel Deployment

Zero-config Git integration, automatic builds, and preview environments.

Next.js App Router
GitHub Repository
→
Vercel Auto-Detect Next.js
→
Edge Network Build
→
Live Production URL

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 ចាស់វិញបានភ្លាមៗបើមានបញ្ហាកើតឡើង។

SECTION 24 — DEPLOYMENT • SLIDE 62 / 75

Develop -> Preview -> Ship

The complete modern full-stack shipping cycle.

Next.js App Router
1. DEVELOP (Local)
→
2. PREVIEW (Branch PR)
→
3. TEST (QA Team)
→
4. SHIP (Main Production)
This modern development workflow connects code authoring, version control, automated testing, and cloud infrastructure into a seamless engineering pipeline.Workflow ទំនើបនេះភ្ជាប់ការសរសេរកូដ Git Version Control ការតេស្តស្វ័យប្រវត្តិ និង Cloud Deployment ទៅជាប្រព័ន្ធតែមួយយ៉ាងរលូន។
SECTION 25 — COMMON MISTAKES • SLIDE 63 / 75

Mistake: Everything Is Client

Why excessive client components degrade performance and bundle sizes.

Next.js App Router
MISTAKE: Adding "use client" everywhere

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 ធម្មតាវិញ និងបាត់បង់អត្ថប្រយោជន៍ល្បឿនទាំងអស់!

SOLUTION: Keep Server as Default

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 ជានិច្ច។

SECTION 25 — COMMON MISTAKES • SLIDE 64 / 75

Mistake: Exposing Secrets

Preventing accidental credential leaks via NEXT_PUBLIC_ prefixes.

Next.js App Router
CRITICAL DANGER: Leaked Credentials
NEXT_PUBLIC_DATABASE_URL="postgres://..."

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 របស់មនុស្សគ្រប់គ្នា!

SECURE FIX: Keep Secrets Private
DATABASE_URL="postgres://..."

Without the prefix, Next.js prevents this variable from ever leaking to the browser window.បើគ្មាន Prefix ទេ Next.js នឹងរក្សាទុក Variable នោះលើ Server ដោយសុវត្ថិភាព 100%។

SECTION 25 — COMMON MISTAKES • SLIDE 65 / 75

Mistake: No Server Validation

Why client-side form validation is never sufficient for security.

Next.js App Router
Browser HTML <input required /> (Bypassed in 2 seconds via curl/Postman)
≠
Server Action Zod Schema Validation (Enforced 100%)
Always remember: Anyone can send raw HTTP POST requests to your server action endpoints. Never trust incoming formData without server-side validation!ចងចាំជានិច្ច៖ នរណាក៏អាចផ្ញើ HTTP POST មកកាន់ Server Action បានដែរ។ កុំទុកចិត្ត formData ដោយគ្មានការពិនិត្យលើ Server ឱ្យសោះ!
SECTION 25 — COMMON MISTAKES • SLIDE 66 / 75

Mistake: Poor Folder Architecture

Avoiding disorganized directories and maintainability nightmares.

Next.js App Router
CHAOTIC ANTI-PATTERN
components/
components2/
final_ui/
old_code/
test_page/
    
CLEAN PRODUCTION PATTERN
app/
components/ui/
actions/
lib/
types/
    
SECTION 26 — DEBUGGING • SLIDE 67 / 75

Debugging Next.js

Mastering tools for diagnosing server and client execution issues.

Next.js App Router
01 • TERMINAL LOGS

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 ឡើយ។

02 • REACT DEVTOOLS

Component Tree

Inspect props, state, and client component boundaries visually in your browser DevTools extension.ពិនិត្យមើល Props, State និង Component Tree តាមរយៈ Extension React DevTools។

03 • NETWORK TAB

RSC Payload

Inspect the React Server Component payload streams and Server Action POST requests in real-time.ពិនិត្យមើល Payload របស់ Server Components និង Server Action ក្នុង Network Tab។

04 • SOURCE MAPS

TypeScript Debug

Set breakpoints in original TypeScript source files directly inside Chrome DevTools or VS Code debugger.ដាក់ Breakpoint លើកូដ TypeScript ដើមក្នុង Chrome ឬ VS Code Debugger។

SECTION 26 — DEBUGGING • SLIDE 68 / 75

Common Errors & Fixes

Diagnosing hydration mismatches, missing directives, and boundary errors.

Next.js App Router
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
SECTION 27 — FINAL ARCHITECTURE • SLIDE 69 / 75

Modern Next.js Architecture

Master architectural diagram connecting all full-stack layers.

Next.js App Router
CLIENT BROWSER (User Interaction & State)
↓ HTTP/2 Requests • Form Server Actions ↓
NEXT.JS APP ROUTER (Server Components • Middleware • Layouts)
↓ Direct Type-Safe Server Calls ↓
PostgreSQL (Neon)
Auth / Session Engine
External APIs & S3
SECTION 28 — CHEAT SHEET • SLIDE 70 / 75

Next.js Commands Cheat Sheet

Essential CLI commands for daily development and deployment.

Next.js App Router
npx create-next-app@latest
Scaffolds a new project with TypeScript, Tailwind, and App Router.
npm run dev
Starts the local development server with Fast Refresh on port 3000.
npm run build
Compiles the optimized production application and checks types.
npm run start
Runs the production server locally to verify the production build.
SECTION 28 — CHEAT SHEET • SLIDE 71 / 75

Next.js Special Files

Reference summary of App Router special file conventions.

Next.js App Router
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
SECTION 28 — CHEAT SHEET • SLIDE 72 / 75

Next.js Core Concepts

Comprehensive summary of core concepts mastered in this course.

Next.js App Router
ROUTING & RENDERING
  • • App Router folders
  • • Server Components
  • • "use client" boundaries
  • • Streaming & Suspense
DATA & MUTATIONS
  • • Server async/await
  • • Direct PostgreSQL queries
  • • Server Actions ("use server")
  • • revalidatePath cache
OPTIMIZATION & SHIPPING
  • • next/image & next/font
  • • Metadata API & SEO
  • • Middleware auth guards
  • • Vercel edge deployment
SECTION 29 — FINAL CHALLENGE • SLIDE 73 / 75

Final Challenge: Build Your Own SaaS

Comprehensive project requirements for the TaskFlow application.

Next.js App Router
TaskFlow SaaS Project Checklist
  • 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 របស់អ្នក!

SECTION 29 — FINAL CHALLENGE • SLIDE 74 / 75

Development Roadmap

Your complete full-stack web developer journey from fundamentals to production.

Next.js App Router
HTML & CSS
→
JavaScript ES6+
→
React Basics
→
Next.js App Router
→
PostgreSQL & Auth
→
Production Engineering
You have completed the entire Next.js App Router curriculum. Continue building real applications, contributing to open-source, and staying curious!អ្នកបានបញ្ចប់មេរៀន Next.js App Router ទាំងស្រុងហើយ។ បន្តបង្កើត Project ជាក់ស្ដែង និងអភិវឌ្ឍសមត្ថភាពជានិច្ច!
SECTION 29 — FINAL CHALLENGE • SLIDE 75 / 75

Final Message

Closing congratulations and call to action for production builders.

Next.js App Router
COURSE COMPLETE • 75 / 75 SLIDES MASTERED
"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 កម្រិតពិភពលោក។