Next.js 14 menjadi standar baru untuk aplikasi React full‑stack. Tutorial ini menuntun Anda dari instalasi hingga deployment production, lengkap dengan contoh kode, konfigurasi, dan best practice terkini (2026).
1. Persiapan Lingkungan
Pastikan Anda memiliki Node.js 20.x+ dan npm 10+ atau pnpm 9+. Versi LTS terbaru memberikan dukungan built‑in fetch, edge runtime, dan mempercepat instalasi paket.
node -v
npm -v # atau pnpm -v
Jika belum terpasang, unduh dari nodejs.org atau gunakan manager seperti nvm:
nvm install 20
nvm use 20
2. Membuat Proyek Next.js 14
Gunakan create-next-app dengan flag --experimental-app (meski di 14 fitur App Router sudah stabil, flag memastikan struktur terbaru).
npx create-next-app@latest my-next14-app --ts --eslint --src-dir --app-dir
Perintah di atas menghasilkan:
- Folder
src/appsebagai root App Router. - TypeScript dan ESLint pre‑configured.
- Struktur
src/pagestidak lagi dipakai, menghindari konflik.
3. Menjalankan Development Server
cd my-next14-app
npm run dev # atau pnpm dev
Akses http://localhost:3000. Anda akan melihat halaman starter yang sudah menggunakan app/layout.tsx dan app/page.tsx.
4. Konfigurasi Dasar
4.1 next.config.js
Buka next.config.mjs (atau .js) dan tambahkan opsi penting untuk produksi 2026:
import { defineConfig } from 'next';
export default defineConfig({
reactStrictMode: true,
swcMinify: true,
experimental: {
serverActions: true, // enable Server Actions API
serverComponentsExternalPackages: ['@prisma/client']
},
images: {
remotePatterns: [{ protocol: 'https', hostname: '**' }]
},
i18n: {
locales: ['en', 'id'],
defaultLocale: 'en'
}
});
4.2 .env.local
Tambahkan variabel rahasia, contohnya koneksi Prisma ke PostgreSQL:
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
Gunakan next/config untuk mengaksesnya secara server‑only.
5. Membuat Server Action untuk CRUD
Server Actions memungkinkan Anda menulis fungsi asynchronous yang dijalankan di server tanpa API route terpisah.
5.1 Buat Model Prisma
// prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
title String
content String?
createdAt DateTime @default(now())
}
Jalankan migrasi:
npx prisma migrate dev --name init
5.2 Implementasi Server Action
Buat file src/app/posts/create-action.ts:
"use server";
import { prisma } from '@/lib/prisma';
export async function createPost(formData: FormData) {
const title = formData.get('title')?.toString() ?? '';
const content = formData.get('content')?.toString() ?? '';
if (!title) throw new Error('Title is required');
await prisma.post.create({ data: { title, content } });
// Next.js 14 will automatically revalidate the page if you use
// `revalidatePath` from "next/cache" (optional)
}
5.3 Form di Client Component
Di src/app/posts/page.tsx (Client Component karena ada interaksi UI):
"use client";
import { useState } from 'react';
import { createPost } from './create-action';
export default function PostsPage() {
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
try {
await createPost(formData);
// optional: refresh UI with mutate or revalidatePath
} catch (err: any) {
setError(err.message);
}
};
return (
Create Post
{error && {error}
}
);
}
Catatan: "use server" menandai modul hanya dapat dieksekusi di server, menghilangkan kebutuhan endpoint terpisah.
6. Optimasi Performance
6.1 Image Optimization
Gunakan next/image dengan layout responsive. Dengan Next.js 14, image loader otomatis berintegrasi CDN edge.
import Image from 'next/image';
export function Hero() {
return (
);
}
6.2 Edge Middleware untuk Caching
Buat middleware.ts di root untuk cache static assets selama 1 hari:
import { NextResponse } from 'next/server';
export const config = { matcher: '/:path*' };
export function middleware(request) {
const response = NextResponse.next();
response.headers.set('Cache-Control', 'public, max-age=86400, stale-while-revalidate=86400');
return response;
}
6.3 Analisis Bundle
Jalankan next build lalu next analyze (built‑in) untuk melihat chunk yang paling berat. Pertimbangkan dynamic import untuk komponen berat.
7. Testing & Linting
- Jest + React Testing Library untuk unit test.
- Playwright untuk end‑to‑end.
- ESLint dengan plugin
@next/nextdaneslint-plugin-react-hooks.
# contoh script di package.json
"scripts": {
"test": "jest",
"test:e2e": "playwright test",
"lint": "next lint"
}
8. CI/CD dengan GitHub Actions
File .github/workflows/ci.yml:
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm run lint
- run: npm run test
- run: npm run build
deploy:
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci && npm run build
- name: Deploy to Vercel
uses: amondnet/vercel-action@v20
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
working-directory: .
Vercel tetap menjadi platform rekomendasi karena integrasi serverless edge dan preview URLs otomatis.
9. Deploy ke Production
Jika menggunakan Vercel, cukup push ke main. Untuk self‑hosted, gunakan Docker:
# Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json .
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next .next
COPY --from=builder /app/public public
COPY --from=builder /app/package*.json ./
RUN npm ci --omit=dev
EXPOSE 3000
CMD ["node", "server.js"]
Bangun dan jalankan:
docker build -t next14-app .
docker run -p 3000:3000 next14-app
10. Best Practice Tambahan
- Type‑safe API: gunakan
Zoduntuk validasi schema pada Server Actions. - Incremental static regeneration (ISR): pada halaman list posts, tambahkan
revalidate = 60untuk update tiap menit. - Security: aktifkan
Content‑Security‑Policylewatnext‑strict‑cspmiddleware. - Observability: integrasikan
next‑monitordengan OpenTelemetry untuk tracing pada edge functions.
Dengan mengikuti langkah‑langkah di atas, Anda akan memiliki aplikasi Next.js 14 yang modern, scalable, dan siap produksi pada tahun 2026.
Next.js 14 menandai evolusi signifikan dalam pengembangan React full‑stack. Menggabungkan App Router, Server Actions, dan fitur edge native membuat workflow lebih simpel dan performa lebih tinggi. Ikuti tutorial ini, terapkan best practice, dan manfaatkan CI/CD otomatis untuk mengirimkan aplikasi yang stabil ke pengguna akhir.
Panduan lengkap setup Next.js 14 dengan App Router, Server Actions, Docker, dan CI/CD. Tutorial step-by-step, contoh kode, konfigurasi, serta best practice untuk produksi pada 2026.
Programming,Software Engineering,Web Development
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar