Next.js 14 menjadi standar baru bagi developer React yang menginginkan rendering hybrid, data fetching terintegrasi, dan performance kelas dunia. Tutorial ini menuntun Anda step‑by‑step memulai proyek, mengkonfigurasi environment, menulis Server Actions, serta menerapkan best practice untuk keamanan dan skalabilitas.
1. Prasyarat dan Persiapan Lingkungan
Pastikan Anda memiliki:
- Node.js v20.12.0 atau lebih baru (LTS)
- npm 10.x atau yarn 4
- Git untuk version control
- Docker (opsional, untuk containerization)
Verifikasi versi dengan:
node -v
npm -v
2. Membuat Project Next.js 14
# Menggunakan npm
npm create next-app@latest my-next14-app -- --typescript --eslint
# Atau dengan yarn
yarn create next-app my-next14-app --typescript --eslint
Perintah di atas akan meng‑install template terbaru yang sudah mendukung App Router dan Server Actions secara default.
2.1 Struktur Direktori Utama
app/– tempat file page berbasis App Router (layout.tsx, page.tsx, loading.tsx)components/– reusable UI componentslib/– helper functions, API clientpublic/– aset statis
3. Instalasi Dependensi Tambahan
Kami akan menambahkan beberapa paket populer untuk form handling, validasi, dan styling:
npm install @tanstack/react-query zod @hookform/resolvers react-hook-form tailwindcss postcss autoprefixer
# Inisialisasi Tailwind
npx tailwindcss init -p
Konfigurasi tailwind.config.js:
module.exports = {
content: ["./app/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
theme: { extend: {} },
plugins: [],
};
4. Mengaktifkan Server Actions
Server Actions memungkinkan Anda menulis fungsi yang dijalankan di server langsung dari komponen client. Pastikan experimental flag di next.config.js diaktifkan (meskipun di v14 sudah default, tetap pastikan):
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: { serverActions: true },
reactStrictMode: true,
};
module.exports = nextConfig;
4.1 Contoh Server Action untuk CRUD Todo
// app/actions/todo.ts
"use server";
import { prisma } from "@/lib/prisma"; // asumsi Prisma ORM
import { z } from "zod";
const TodoSchema = z.object({
title: z.string().min(1),
completed: z.boolean().optional(),
});
export async function createTodo(data: any) {
const parsed = TodoSchema.parse(data);
return await prisma.todo.create({ data: parsed });
}
export async function toggleTodo(id: number) {
const todo = await prisma.todo.findUnique({ where: { id } });
if (!todo) throw new Error("Todo not found");
return await prisma.todo.update({
where: { id },
data: { completed: !todo.completed },
});
}
4.2 Memanggil Action dari Client Component
// app/todos/page.tsx
"use client";
import { useState } from "react";
import { createTodo, toggleTodo } from "../actions/todo";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
export default function TodoPage() {
const queryClient = useQueryClient();
const { data: todos } = useQuery({ queryKey: ["todos"], queryFn: fetchTodos });
const createMutation = useMutation({
mutationFn: createTodo,
onSuccess: () => queryClient.invalidateQueries(["todos"]),
});
const toggleMutation = useMutation({
mutationFn: toggleTodo,
onSuccess: () => queryClient.invalidateQueries(["todos"]),
});
const [title, setTitle] = useState("");
const handleAdd = async () => {
await createMutation.mutateAsync({ title });
setTitle("");
};
return (
Todo List (Next.js 14 Server Actions)
setTitle(e.target.value)}
placeholder="Tambah todo..."
/>
{todos?.map((t) => (
-
{t.title}
))}
);
}
async function fetchTodos() {
const res = await fetch("/api/todos");
return res.json();
}
5. Menyiapkan API Routes (Edge Runtime)
Untuk read‑only endpoint kita gunakan Edge Runtime agar latency lebih rendah.
// app/api/todos/route.ts
export const runtime = "edge";
import { prisma } from "@/lib/prisma";
export async function GET() {
const todos = await prisma.todo.findMany();
return new Response(JSON.stringify(todos), { status: 200, headers: { "Content-Type": "application/json" } });
}
6. Konfigurasi Prisma ORM & Database
# Install Prisma CLI
npm install -D prisma
npm install @prisma/client
# Initialise schema
npx prisma init --datasource-provider postgresql
Ubah .env:
DATABASE_URL="postgresql://user:password@localhost:5432/next14_demo"
Definisikan model Todo:
// prisma/schema.prisma
model Todo {
id Int @id @default(autoincrement())
title String
completed Boolean @default(false)
createdAt DateTime @default(now())
}
Jalankan migration:
npx prisma migrate dev --name init
7. Optimasi Build untuk Produksi
- Image Optimization: Gunakan
next/imagedengan loader default ataunext-optimized-imagesjika ingin WebP otomatis. - Tailwind JIT: Pastikan
mode: "jit"di Tailwind config (default di v4). - Incremental Static Regeneration (ISR): Tambahkan
revalidatepadafetchTodosjika data tidak berubah tiap detik. - Compression: Deploy di Vercel atau Cloudflare Workers, aktifkan gzip/brotli.
7.1 Contoh ISR pada Server Component
// app/todos/page.tsx (server component)
export const revalidate = 60; // rebuild tiap 60 detik
export default async function TodoPage() {
const todos = await prisma.todo.findMany();
return (
// render static markup
);
}
8. Deployment dengan Docker & Vercel
8.1 Dockerfile (Multi‑stage)
# 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/package*.json ./
COPY --from=builder /app/public ./public
RUN npm ci --production
EXPOSE 3000
CMD ["node", "server.js"]
8.2 Deploy ke Vercel
1. Push repository ke GitHub.
2. Hubungkan proyek di Vercel.
3. Vercel otomatis mendeteksi next.config.js dan meng‑install dependencies.
9. Best Practice Keamanan & Maintainability
- Env Sanitization: Gunakan
dotenv-safeuntuk memastikan semua variabel terdefinisi. - Rate Limiting: Tambahkan middleware edge
@upstash/ratelimitpada API route. - Type‑Safety: Selalu gunakan TypeScript generics pada
react-queryuntuk menghindari runtime errors. - Code Splitting: Letakkan heavy UI di
dynamic()denganssr: falsebila tidak perlu server render. - Audit Dependencies: Jalankan
npm auditdan perbarui dengannpm audit fix --forcesecara periodik.
10. Testing & CI/CD
Setup Jest & React Testing Library:
npm install -D jest @testing-library/react @testing-library/jest-dom ts-jest
# jest.config.ts
export default {
preset: "ts-jest",
testEnvironment: "jsdom",
moduleNameMapper: { "^@/(.*)$": "/$1" },
};
Contoh unit test untuk Server Action:
// __tests__/todo.actions.test.ts
import { createTodo } from "../app/actions/todo";
test("createTodo creates record", async () => {
const result = await createTodo({ title: "Test" });
expect(result.id).toBeDefined();
expect(result.title).toBe("Test");
});
Integrasikan ke GitHub Actions:
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 20
- run: npm ci
- run: npm run lint
- run: npm test -- --coverage
11. Studi Kasus: Migrasi dari Next.js 13 ke 14 dengan Minimal Downtime
Perusahaan X memiliki aplikasi berbasis pages/ yang menggunakan getServerSideProps. Langkah migrasi:
- Enable
experimental.appDirdinext.config.jstanpa menghapuspages/. - Buat
app/layout.tsxsebagai wrapper global, pindahkan shared CSS. - Secara bertahap convert satu route ke
app/[route]/page.tsx, gunakanexport const dynamic = "force-dynamic"bila masih butuh SSR. - Setelah semua halaman berhasil, hapus folder
pages/dan matikan flag.
Hasil: 30% peningkatan LCP dan 15% penurunan server‑time karena otomatisnya static caching di App Router.
Next.js 14 menggandeng App Router, Server Actions, dan Edge Runtime untuk memberikan developer kontrol penuh atas rendering dan performa. Dengan mengikuti tutorial ini—mulai dari setup project, integrasi Prisma, penulisan Server Actions, hingga deployment Docker atau Vercel—Anda akan memiliki aplikasi production‑ready yang scalable, aman, dan mudah dipelihara. Terapkan best practice security, testing, dan CI/CD untuk memastikan kualitas kode tetap tinggi seiring pertumbuhan tim dan fitur.
Panduan lengkap langkah demi langkah menyiapkan Next.js 14 dengan App Router, Server Actions, Prisma, Tailwind, Docker, dan CI/CD untuk pengembangan web modern di 2026.
Programming,Software Engineering,Web Development
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar