Dark mode
Core Concepts
แนวคิดหลัก | คำอธิบาย | ตัวอย่าง |
---|---|---|
Next.js | React-based framework | SSR/API routes, ไฟล์ app/ , โหมด Hybrid rendering |
Vercel | เครื่องมือ build หลัก | Hot Module Replacement, Build เร็ว, Plugin ecosystem |
React Hooks | รูปแบบการเขียน React components | useState() function, useContext() , Custom hooks |
Next.js Routing | การแชร์และการขยาย configuration | Extend 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
- ติดตั้ง Node.js เวอร์ชัน 16.8 ขึ้นไป
- สร้างโปรเจคใหม่:
bash
npx create-next-app@latest
- ติดตั้ง dependencies เพิ่มเติม:
bash
npm install @next/bundle-analyzer next-compose-plugins
- รันโปรเจค:
bash
npm run dev
Configuration
Next.js ใช้ไฟล์ next.config.js
สำหรับการกำหนดค่า ตัวเลือกหลัก:
ตัวเลือก | คำอธิบาย | ตัวอย่าง |
---|---|---|
reactStrictMode | เปิดใช้งาน React Strict Mode | true |
output | โหมดการ export (static/standalone) | 'standalone' |
images | การตั้งค่าการปรับรูปภาพ | { domains: [...] } |
env | ตัวแปรสภาพแวดล้อม | { API_URL: process.env.API_URL } |
experimental | คุณสมบัติทดลอง | { appDir: true } |
compiler | ตัวเลือกคอมไพลเลอร์ | { styledComponents: true } |
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
Method | Description | Example |
---|---|---|
CSS Modules | ใช้กับทั้ง Server และ Client Components | styles.module.css |
Tailwind CSS | ใช้กับ Client Components | className="flex p-4" |
CSS-in-JS | ต้องใช้ 'use client' directive | styled-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
Target | Command | Config | Output Directory |
---|---|---|---|
Vercel | Automatic | None needed | N/A |
Node.js | next build + next start | output: 'standalone' | .next |
Static | next build + next export | output: 'export' | out/ |
Docker | docker build | Dockerfile | Image |
Edge | Automatic | runtime: '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
Environment Variables:
- ใช้
.env.local
สำหรับค่าลับ - ตั้งชื่อตัวแปรด้วย
NEXT_PUBLIC_
สำหรับค่าที่ต้องการ expose ไปยัง client
- ใช้
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' }) // ... }
Authentication:
- ใช้ NextAuth.js หรือ Clerk สำหรับระบบ authentication
- ตรวจสอบสิทธิ์ใน
getServerSideProps
หรือ API Routes
Dependencies:
bashnpm audit # ตรวจสอบ vulnerabilities npm update --depth 9999 # อัปเดต dependencies
Pages and Routing
Next.js สร้างเส้นทางอัตโนมัติจากโครงสร้างไดเรกทอรี pages/
Concept | Description | Example |
---|---|---|
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>
}