Next.js 14 telah menjadi standar de‑facto untuk React full‑stack. Tutorial ini mengajarkan cara menginstal, mengkonfigurasi, menulis kode contoh, serta menerapkan best practice security dan performance untuk produksi.

1. Persiapan Lingkungan

Pastikan Anda memiliki Node.js versi 20.12 atau lebih tinggi dan npm atau pnpm terbaru. Versi LTS ini sudah teruji dengan Next.js 14.

node -v
# v20.12.0
npm -v
# 10.5.0

1.1 Instalasi Global Tools

  • Install create-next-app secara global (opsional, karena dapat dipanggil via npx).
  • Install turbo untuk monorepo bila diperlukan.
npm i -g create-next-app turbo

2. Membuat Proyek Baru dengan App Router

Next.js 14 memperkenalkan App Router sebagai default. Gunakan perintah berikut untuk memulai project dengan TypeScript dan ESLint:

npx create-next-app@latest my-next14-app \
  --ts \
  --eslint \
  --use-npm
cd my-next14-app

Folder app akan otomatis dibuat. Struktur dasar:

/app
  /layout.tsx
  /page.tsx
  /api
    /hello
      route.ts

2.1 Menjalankan Development Server

npm run dev
# http://localhost:3000

3. Konfigurasi Dasar Next.js 14

Ubah next.config.js untuk mengaktifkan React Server Components, Image Optimization, dan experimental feature: serverActions:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: {
    serverActions: true,
    appDir: true
  },
  images: {
    remotePatterns: [{
      protocol: 'https',
      hostname: '**.cdn.jsdelivr.net',
      pathname: '/**'
    }]
  }
};
export default nextConfig;

3.1 Environment Variables

Buat file .env.local untuk variabel rahasia (mis. API key). Pastikan menambahkan file ini ke .gitignore:

NEXT_PUBLIC_API_URL=https://api.example.com
SECRET_TOKEN=super-secret

4. Membuat Route dengan Server Action

Server Actions memungkinkan fungsi async dijalankan di server tanpa API route terpisah.

4.1 Definisikan Action di app/contact/page.tsx

"use server";
import { redirect } from 'next/navigation';

export async function sendMessage(formData: FormData) {
  const name = formData.get('name');
  const email = formData.get('email');
  const message = formData.get('message');

  // Simulasi panggilan API internal
  await fetch(process.env.NEXT_PUBLIC_API_URL + '/contact', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, email, message })
  });

  // Setelah berhasil, redirect ke halaman thanks
  redirect('/thanks');
}

export default function ContactPage() {
  return (