Next.js 14 menjadi pilihan utama untuk membangun aplikasi React modern dengan rendering hybrid, server actions, dan integrasi edge runtime. Tutorial ini mengajak Anda menginstal, mengkonfigurasi, dan mengoptimasi proyek Next.js 14 secara step‑by‑step, lengkap dengan contoh kode, best practice, serta tips debugging yang relevan pada Mei 2026.
1. Persiapan Lingkungan Pengembangan
Pastikan sistem Anda memenuhi persyaratan berikut:
- Node.js v20.12.x atau lebih baru (LTS)
- npm 10.x atau yarn 4.x
- Git untuk version control
- Docker (opsional, untuk containerization)
Verifikasi instalasi dengan perintah:
node -v
npm -v
2. Membuat Proyek Next.js 14 Baru
Gunakan template resmi yang sudah termasuk app/ router dan TypeScript.
npx create-next-app@latest my-next14-app \
--ts \
--experimental-app-router
cd my-next14-app
Perintah di atas menghasilkan struktur folder berikut:
my-next14-app/
├─ app/
│ ├─ layout.tsx
│ ├─ page.tsx
│ └─ ...
├─ public/
├─ src/
│ └─ ...
├─ next.config.mjs
├─ tsconfig.json
└─ package.json
3. Konfigurasi Dasar next.config.mjs
Aktifkan fitur terbaru dan atur edge runtime untuk API routes.
import { defineConfig } from 'next';
export default defineConfig({
reactStrictMode: true,
experimental: {
appDir: true,
serverActions: true,
typedRoutes: true,
},
images: {
remotePatterns: [{ hostname: 'images.unsplash.com' }],
},
// Enable edge runtime for API routes
runtime: 'edge',
});
4. Menyiapkan TypeScript Strict Mode
Update tsconfig.json untuk meningkatkan keamanan tipe.
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
5. Membuat Layout Global dengan Server Components
File app/layout.tsx menjadi kerangka aplikasi.
import './globals.css';
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Next.js 14 Demo',
description: 'Contoh aplikasi dengan App Router & Server Actions',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
6. Membuat Halaman Utama dengan Server Actions
Halaman app/page.tsx menampilkan formulir yang memanggil server action untuk menyimpan data ke mock API.
"use server";
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
async function submitMessage(formData: FormData) {
const name = formData.get('name') as string;
const message = formData.get('message') as string;
// Simulasi POST ke endpoint internal
await fetch('https://dummyjson.com/comments/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: message, userId: 1, postId: 1, name }),
});
// Revalidate cache agar UI menampilkan data terbaru
revalidatePath('/messages');
redirect('/messages');
}
export default function HomePage() {
return (
Kirim Pesan
);
}
Catatan: "use server" menandakan bahwa fungsi ini hanya dijalankan di server, memanfaatkan Server Actions yang muncul di Next.js 14.
7. Menampilkan Data dengan Incremental Static Regeneration (ISR)
Buat route app/messages/page.tsx yang mengambil data dan men‑set revalidate 60 detik.
import type { Metadata } from 'next';
export const revalidate = 60; // seconds
export const metadata: Metadata = {
title: 'Daftar Pesan',
};
async function fetchMessages() {
const res = await fetch('https://dummyjson.com/comments', { cache: 'no-store' });
if (!res.ok) throw new Error('Failed to fetch messages');
return res.json();
}
export default async function MessagesPage() {
const data = await fetchMessages();
return (
Pesan Terbaru
{data.comments.map((c: any) => (
-
{c.user.username}: {c.body}
))}
);
}
8. Menambahkan Styling dengan Tailwind CSS v4
Instalasi Tailwind terbaru (v4) yang sudah terintegrasi dengan JIT pada Next.js 14.
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p
Ubah tailwind.config.js:
module.exports = {
content: ["./app/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
};
Tambahkan direktif ke globals.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
9. Menggunakan Edge Runtime untuk API Route Ringkas
Buat file app/api/health/route.ts yang berjalan di edge.
export const runtime = 'edge';
export async function GET(request: Request) {
return new Response(JSON.stringify({ status: 'ok', timestamp: Date.now() }), {
headers: { 'Content-Type': 'application/json' },
});
}
10. Dockerisasi Proyek
Berikut Dockerfile multi‑stage yang menghasilkan image ringan (node:20‑alpine).
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
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 ["npm", "start"]
11. CI/CD Ringkas dengan GitHub Actions
Workflow .github/workflows/ci.yml otomatis build, test, dan push Docker image ke GitHub Container Registry.
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: '20.x'
- run: npm ci
- run: npm run lint && npm run test
- name: Build Docker image
run: |
docker build -t ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:sha-${{ github.sha }} .
- name: Push to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- run: |
docker push ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:sha-${{ github.sha }}
12. Best Practice & Security Checklist
- Env variables: Simpan rahasia di
.env.localdan gunakannext.config.mjsuntuk whitelist ("NEXT_PUBLIC_*"). - Header security: Tambahkan
helmetlewat middleware:export const middleware = (req) => NextResponse.next({ headers: { 'X‑Content‑Type‑Options': 'nosniff', 'Referrer-Policy': 'strict-origin' } }). - Image optimization: Gunakan
next/imagedengan remote patterns untuk CDN. - Code splitting: Manfaatkan dynamic import pada komponen berat:
const Chart = dynamic(() => import('@/components/Chart'), { ssr: false }). - Testing: Jest + React Testing Library untuk unit, Playwright untuk e2e.
13. Debugging Tips
- Gunakan
next devdengan--inspectuntuk attach debugger. - Log server actions melalui
console.logdi dalam fungsi"use server"—output akan muncul di terminal Next.js. - Periksa cache ISR dengan men‑add query
?skipCache=1ke URL, yang memaksa fetch fresh data.
14. Deploy ke Vercel (Edge Runtime)
Vercel otomatis mendeteksi app/ router. Pastikan Anda men‑set environment variables di dashboard Vercel dan pilih Edge Functions pada setting API routes untuk latency minimal.
15. Monitoring & Observability
Integrasikan dengan OpenTelemetry (OTel) dan Sentry untuk tracing server actions.
npm install @opentelemetry/api @opentelemetry/sdk-node @sentry/nextjs
// src/lib/otel.ts
import { trace } from '@opentelemetry/api';
export const tracer = trace.getTracer('nextjs-app');
Wrap server actions:
"use server";
import { tracer } from '@/lib/otel';
async function submitMessage(formData: FormData) {
const span = tracer.startSpan('submitMessage');
try {
// ...logic
} finally {
span.end();
}
}
Dengan langkah‑langkah di atas, Anda memiliki proyek Next.js 14 yang modern, aman, dan siap produksi pada tahun 2026.
Next.js 14 memperkenalkan App Router generasi berikutnya, Server Actions, dan dukungan native edge runtime yang memungkinkan developer membangun aplikasi web yang cepat, aman, dan skalabel. Dengan mengikuti tutorial ini—mulai dari instalasi, konfigurasi TypeScript, pembuatan halaman dinamis, hingga Dockerisasi, CI/CD, dan observability—Anda memperoleh fondasi yang solid untuk proyek produksi serta kemampuan beradaptasi dengan praktik terbaik terbaru dalam ekosistem React. Jangan lupa terus memantau pembaruan resmi Next.js dan komunitas untuk tetap berada di garis depan inovasi web di 2026.
Tutorial step-by-step Next.js 14 dengan App Router, Server Actions, Tailwind CSS, Docker, dan CI/CD. Panduan lengkap 2026 untuk web development, performance, dan security.
Programming,Software Engineering,Web Development,Next.js 14,React,Server Actions,Docker
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar