Next.js 14 menjadi standar de‑facto untuk aplikasi React modern. Tutorial ini mengajak Anda menginstal, mengkonfigurasi, menulis kode, dan mengoptimalkan proyek Next.js 14 dengan App Router, Server Actions, TypeScript, dan deployment ke Vercel, lengkap dengan best‑practice terkini.
1. Prasyarat dan Persiapan Lingkungan
Sebelum memulai, pastikan Anda memiliki:
- Node.js v20.14 atau lebih baru (
node -v) - Git
- Editor kode (VS Code direkomendasikan) dengan ekstensi
ESLint,Prettier, danTailwind CSS IntelliSense - Akun Vercel untuk deployment gratis
Instalasi Node.js & npm
# Debian/Ubuntu
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# macOS dengan Homebrew
brew install node
2. Membuat Proyek Next.js 14 Baru
# Buat folder proyek
mkdir nextjs14-demo && cd $_
# Inisialisasi dengan npm init dan pilih "yes" untuk semua default
npm init -y
# Instal Next.js, React, dan TypeScript sekaligus
npm install next@14 react@19 react-dom@19
npm install -D typescript @types/react @types/node
# Jalankan command init Next.js yang menyiapkan file konfigurasi
npx next telemetry disable
npx next build
Perintah di atas menghasilkan next.config.mjs, tsconfig.json, dan folder app (App Router) secara otomatis.
3. Struktur Folder Utama (App Router)
my-app/
├─ app/
│ ├─ layout.tsx # Root layout
│ ├─ page.tsx # Home page
│ ├─ (dashboard)/ # Route Group untuk dashboard
│ │ ├─ layout.tsx
│ │ └─ page.tsx
│ └─ api/
│ └─ hello/route.ts # Server Action contoh API
├─ public/
├─ styles/
├─ next.config.mjs
└─ package.json
4. Konfigurasi Dasar Next.js 14
next.config.mjs
import { defineConfig } from 'next';
export default defineConfig({
reactStrictMode: true,
swcMinify: true,
// Aktifkan Edge Runtime untuk Server Actions
experimental: { appDir: true },
images: { remotePatterns: [{ hostname: 'images.unsplash.com' }] },
});
tsconfig.json (Opsional, tapi disarankan)
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "node",
"jsx": "preserve",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"incremental": true,
"baseUrl": ".",
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
5. Menambahkan Tailwind CSS (Opsional, tapi populer)
# Instalasi
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
# tailwind.config.cjs
module.exports = {
content: ["./app/**/*.{js,ts,jsx,tsx}", "./pages/**/*.{js,ts,jsx,tsx}"],
theme: { extend: {} },
plugins: [],
};
# styles/globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;
6. Membuat Layout Root dengan Metadata
// app/layout.tsx
import './globals.css';
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Next.js 14 Demo',
description: 'Demo modern Next.js dengan App Router & Server Actions',
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
7. Membuat Halaman Home dengan Server Action
Server Actions memungkinkan Anda menulis fungsi yang dijalankan di server langsung dari komponen UI tanpa membuat API terpisah.
// app/page.tsx
'use client'; // Karena mengandung interaktivitas di client
import { useState, FormEvent } from 'react';
// Server Action (akan dipanggil lewat fetch ke /api/hello)
async function submitName(data: FormData) {
'use server';
const name = data.get('name') as string;
// Simulasi penyimpanan atau proses berat
await new Promise((r) => setTimeout(r, 500));
console.log('Nama disimpan di server:', name);
return { success: true, name };
}
export default function Home() {
const [greeting, setGreeting] = useState('');
async function handleSubmit(e: FormEvent) {
e.preventDefault();
const form = e.currentTarget;
const result = await submitName(new FormData(form));
if (result.success) setGreeting(`Hai, ${result.name}!`);
}
return (
Selamat Datang di Next.js 14
{greeting && {greeting}
}
);
}
8. Membuat API Route dengan Server Action (Edge)
// app/api/hello/route.ts
export async function GET(request: Request) {
return new Response(JSON.stringify({ message: 'Hello from Edge Runtime' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
9. Pengujian Lokal
# Jalankan development server
npm run dev
# Buka browser di http://localhost:3000
# Cek console server untuk log "Nama disimpan di server"
10. Optimasi Produksi
Static Generation vs Server‑Side Rendering
Gunakan export const runtime = 'edge'; pada file yang hanya butuh statik, atau export const dynamic = 'force-dynamic'; bila data selalu berubah. Contoh pada halaman dashboard:
// app/(dashboard)/page.tsx
export const runtime = 'edge'; // Membuat halaman statik di Edge
export default function Dashboard() {
// fetch data secara statik pada build
const stats = await fetch('https://api.example.com/stats').then(r => r.json());
return ( ... );
}
Image Optimization
Manfaatkan next/image untuk gambar otomatis di‑resize, webp, dan lazy‑load.
import Image from 'next/image';
Cache Header & Incremental Static Regeneration (ISR)
// app/blog/[slug]/page.tsx
export const revalidate = 60; // rebuild tiap 60 detik
Linting & Formatting
# Instal ESLint & Prettier bersama plugin Next.js
npm install -D eslint prettier eslint-plugin-next eslint-config-prettier
# .eslintrc.json
{
"extends": ["next/core-web-vitals", "prettier"],
"rules": {"react/react-in-jsx-scope": "off"}
}
11. Deploy ke Vercel
- Commit semua perubahan ke repository Git (GitHub, GitLab, atau Bitbucket).
- Buka Vercel New Project, hubungkan repository.
- Pilih framework Next.js otomatis terdeteksi.
- Biarkan variabel lingkungan default; Vercel akan menjalankan
npm install && npm run buildsecara otomatis. - Setelah selesai, URL
https://langsung dapat diakses..vercel.app
Verifikasi Production Build
# Di Vercel dashboard, pilih "Deployments" → "View Build Logs"
# Pastikan tidak ada warning terkait next/image atau server actions.
12. Best Practice Tambahan (2026)
- Type‑Safe API: Gunakan
zodatauValibotuntuk validasi schema pada Server Actions. - Edge Middleware: Implementasikan middleware untuk auth JWT pada
middleware.tsagar dijalankan di Edge. - Observability: Integrasikan dengan Vercel Analytics atau OpenTelemetry untuk tracing request.
- Security: Aktifkan
Content‑Security‑Policyvianext‑secure‑headersdan gunakanhelmetdi API routes. - Testing: Pakai
jest+@testing-library/reactuntuk unit test, sertaplaywrightuntuk end‑to‑end.
13. Kesimpulan
Dengan mengikuti langkah‑langkah di atas, Anda memiliki aplikasi Next.js 14 yang modern, memanfaatkan App Router, Server Actions, TypeScript, dan siap di‑deploy ke Vercel dengan performa optimal. Selalu perhatikan update resmi Next.js (biasanya dirilis tiap kuartal) dan jangan lupa menambahkan test serta monitoring untuk menjaga kualitas produksi.
Next.js 14 membuka era pengembangan React yang lebih simpel dan cepat, menggabungkan routing berbasis file, Server Actions tanpa boilerplate API, serta kemampuan Edge Runtime. Menguasai setup lengkap dari instalasi, konfigurasi, penulisan kode, hingga deployment ke Vercel memberi Anda fondasi kuat untuk membangun aplikasi web skala besar yang aman, performa tinggi, dan mudah dipelihara. Ikuti best practice terbaru, tetap update dengan changelog resmi, dan terus eksplorasi integrasi AI atau observability untuk tetap berada di depan dalam dunia Software Engineering.
Panduan step‑by‑step setup Next.js 14 dengan App Router, Server Actions, TypeScript, Tailwind, dan deployment ke Vercel. Termasuk konfigurasi, contoh kode, dan best practice 2026 untuk Programming, Software Engineering, dan Web Development.
Programming,Software Engineering,Web Development,Next.js 14,App Router,Server Actions,Vercel,TypeScript,Tailwind CSS
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar