Skip to content

Core Concepts

แนวคิดหลักคำอธิบายตัวอย่าง
Next.jsReact-based frameworkSSR/API routes, ไฟล์ app/, โหมด Hybrid rendering
Vercelเครื่องมือ build หลักHot Module Replacement, Build เร็ว, Plugin ecosystem
React Hooksรูปแบบการเขียน React componentsuseState() function, useContext(), Custom hooks
Next.js Routingการแชร์และการขยาย configurationExtend projects, Share components, Unified config
Automatic Importsการนำเข้าอัตโนมัติComponents, Hooks, React APIs
File-based Routingระบบ routing จากโครงสร้างไฟล์app/ directory, Dynamic routes, Route middleware

Key Features

คุณสมบัติรายละเอียดตัวอย่าง
File-based Routingสร้างเส้นทางอัตโนมัติจากโครงสร้างไฟล์app/about/page.tsx/about
Server-side Renderingการแสดงผลฝั่งเซิร์ฟเวอร์ใช้ fetch() สำหรับดึงข้อมูลใน SSR
Static Site Generationการสร้างเว็บไซต์แบบสแตติกคำสั่ง next build และ next export
Automatic Importsนำเข้า components/hooks อัตโนมัติใช้ useRouter() โดยไม่ต้อง import
App Directoryระบบโมดูลสำหรับเพิ่มความสามารถapp/, pages/, components/
Hybrid Renderingผสมผสาน SSR, SSG และ CSR ในแอปเดียวexport const dynamic = 'force-static'
DevToolsเครื่องมือพัฒนาที่มีในตัวReact Developer Tools
API Routesสร้าง API endpoints ฝั่งเซิร์ฟเวอร์ไฟล์ใน app/api/ จะกลายเป็นเส้นทาง API
Middlewareการจัดการความปลอดภัยของเส้นทางไฟล์ middleware.ts ใน root directory
State ManagementการจัดการสถานะuseState, useReducer, หรือ libraries ภายนอก

Getting Started

  1. ติดตั้ง Node.js เวอร์ชัน 16.8 ขึ้นไป
  2. สร้างโปรเจคใหม่:
bash
npx create-next-app@latest
  1. ติดตั้ง dependencies เพิ่มเติม:
bash
npm install @next/bundle-analyzer next-compose-plugins
  1. รันโปรเจค:
bash
npm run dev

Configuration

Next.js ใช้ไฟล์ next.config.js สำหรับการกำหนดค่า ตัวเลือกหลัก:

ตัวเลือกคำอธิบายตัวอย่าง
reactStrictModeเปิดใช้งาน React Strict Modetrue
outputโหมดการ export (static/standalone)'standalone'
imagesการตั้งค่าการปรับรูปภาพ{ domains: [...] }
envตัวแปรสภาพแวดล้อม{ API_URL: process.env.API_URL }
experimentalคุณสมบัติทดลอง{ appDir: true }
compilerตัวเลือกคอมไพลเลอร์{ styledComponents: true }
next.config.js
js
// next.config.js
module.exports = {
  reactStrictMode: true,
  output: 'standalone',
  images: {
    domains: ['example.com'],
  },
  env: {
    API_URL: process.env.API_URL,
  },
  experimental: {
    appDir: true,
  },
  compiler: {
    styledComponents: true,
  },
}

TypeScript Support

For TypeScript, create a next-env.d.ts file:

ts
/// <reference types="next" />
/// <reference types="next/image-types/global" />

Directory Structure

โฟลเดอร์/ไฟล์คำอธิบาย
app/เก็บไฟล์หน้าเว็บและ layout
public/เก็บไฟล์ static เช่น รูปภาพ, fonts
components/เก็บ React components ที่ใช้ซ้ำ
lib/เก็บ utility functions
next.config.jsไฟล์กำหนดค่า Next.js
sh
my-next-app/
├── app/         # App Router (layouts/pages)
   ├── layout.tsx
   ├── page.tsx
   └── (other routes)
├── public/      # Static files
├── components/  # UI components
└── next.config.js

Routing

สร้างเส้นทางอัตโนมัติจากโครงสร้างไฟล์ app/ directory:

ts
// app/page.tsx
export default function Page() {
  return <div>Page Content</div>
}

Data Fetching

วิธีคำอธิบาย
Server Componentsดึงข้อมูลใน Server Components โดยตรง
Route Handlersสร้าง API endpoints ใน app/api/ directory
ts
// app/page.tsx
export default async function Page() {
  const data = await fetch('https://api.example.com/data').then(res => res.json())
  
  return <div>{data}</div>
}

API Routes

สร้าง API endpoints ใน app/api/ directory:

ts
// app/api/hello/route.ts
export async function GET() {
  return new Response(JSON.stringify({ message: 'Hello from API!' }), {
    headers: { 'Content-Type': 'application/json' }
  })
}

Authentication

ใช้ Middleware สำหรับตรวจสอบสิทธิ์:

ts
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  const token = request.cookies.get('token')?.value
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url))
  }
  return NextResponse.next()
}

State Management

วิธีการคำอธิบาย
Server Componentsเก็บ state ฝั่งเซิร์ฟเวอร์
Client Componentsใช้ React hooks สำหรับ state ฝั่งไคลเอนต์
URL Search Paramsเก็บ state ใน URL
tsx
// app/counter/page.tsx
'use client' // Mark as Client Component

export default function Counter() {
  const [count, setCount] = useState(0)
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  )
}

Layout

tsx
// app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        <Header />
        {children}
        <Footer />
      </body>
    </html>
  )
}

Styling

MethodDescriptionExample
CSS Modulesใช้กับทั้ง Server และ Client Componentsstyles.module.css
Tailwind CSSใช้กับ Client ComponentsclassName="flex p-4"
CSS-in-JSต้องใช้ 'use client' directivestyled-components
tsx
// app/page.tsx
import styles from './page.module.css'

export default function Home() {
  return <main className={styles.main}>Content</main>
}

Deployment

Deployment Targets

TargetCommandConfigOutput Directory
VercelAutomaticNone neededN/A
Node.jsnext build + next startoutput: 'standalone'.next
Staticnext build + next exportoutput: 'export'out/
Dockerdocker buildDockerfileImage
EdgeAutomaticruntime: 'edge'N/A
bash
# Just push to connected Git repository
# Automatic deployments configured in Vercel
bash
npm run build
npm run export
# Outputs to out/ directory
dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM node:18-alpine AS runner
WORKDIR /app
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

EXPOSE 3000
CMD ["npm", "start"]
js
// pages/api/hello.js
export const config = {
  runtime: 'edge'
}

export default function handler(request) {
  return new Response('Hello from edge!')
}

Development

Development Workflow

คำสั่งคำอธิบาย
npm run devเริ่ม development server
npm run buildสร้าง production build
npm run startเริ่ม production server
npm run lintตรวจสอบ code ด้วย ESLint
npm run formatจัดรูปแบบ code ด้วย Prettier

Hot Reloading

Next.js รองรับ Hot Module Replacement (HMR) ที่ช่วยให้เห็นการเปลี่ยนแปลงโดยไม่ต้องรีเฟรชหน้า

Debugging

เครื่องมือคำอธิบาย
React Developer Toolsตรวจสอบ component tree และ props
Next.js DevToolsตรวจสอบ performance และ routes
Browser DevToolsตรวจสอบ network requests และ console logs

Testing

วิธีการคำอธิบาย
Unit Testsใช้ Vitest หรือ Jest
Integration Testsใช้ Playwright หรือ Cypress
E2E Testsใช้ Playwright หรือ Cypress
bash
# ตัวอย่างการรัน tests
npm run test

Security

Built-in Security Features

คุณสมบัติคำอธิบายวิธีใช้งาน
Automatic HTTPSใช้งานได้เมื่อ deploy บน Vercelใช้งานอัตโนมัติเมื่อ deploy
Content Security Policyกำหนดผ่าน next.config.jsใช้ headers config
Secure Headersกำหนดผ่าน next.config.jsใช้ headers config
CSRF Protectionใช้งานได้ผ่าน API Routesใช้ getServerSideProps หรือ middleware

Best Practices

  1. Environment Variables:

    • ใช้ .env.local สำหรับค่าลับ
    • ตั้งชื่อตัวแปรด้วย NEXT_PUBLIC_ สำหรับค่าที่ต้องการ expose ไปยัง client
  2. API Security:

    ts
    // pages/api/secret.ts
    import { getToken } from 'next-auth/jwt'
    
    export default async function handler(request) {
      const token = await getToken({ request })
      if (!token) return res.status(401).json({ error: 'Unauthorized' })
      // ...
    }
  3. Authentication:

    • ใช้ NextAuth.js หรือ Clerk สำหรับระบบ authentication
    • ตรวจสอบสิทธิ์ใน getServerSideProps หรือ API Routes
  4. Dependencies:

    bash
    npm audit # ตรวจสอบ vulnerabilities
    npm update --depth 9999 # อัปเดต dependencies

Pages and Routing

Next.js สร้างเส้นทางอัตโนมัติจากโครงสร้างไดเรกทอรี pages/

ConceptDescriptionExample
Basic Routeเส้นทางพื้นฐานจากไฟล์pages/index.tsx/
Dynamic Routeเส้นทางแบบไดนามิกด้วยพารามิเตอร์pages/users/[id].tsx/users/123
Nested Routeเส้นทางแบบซ้อนจากโฟลเดอร์pages/products/index.tsx/products
tsx
// pages/index.tsx
export default function Home() {
  return <div>Welcome to Home Page</div>
}
tsx
// pages/users/[id].tsx
export default function UserProfile({ id }) {
  return <div>User ID: {id}</div>
}
tsx
// pages/products/index.tsx
export default function Products() {
  return <div>Products List</div>
}

Last updated: