Panduan Lengkap Setup Next.js 14 dengan App Router dan React Server Components (2026)


Next.js 14 menjadi standar de‑facto untuk pengembangan aplikasi React modern. Tutorial ini membimbing Anda dari instalasi, konfigurasi, hingga contoh kode produksi, lengkap dengan best practice untuk performance dan security.

1. Persiapan Lingkungan

Sebelum memulai, pastikan sistem Anda memiliki:

  • Node.js v20.12 atau lebih baru (unduh di nodejs.org)
  • npm v10 atau Yarn v4 (npm sudah termasuk di Node)
  • Git untuk version control
  • Editor kode modern, contoh VS Code dengan ekstensi “ESLint”, “Prettier”, dan “Tailwind CSS IntelliSense”

1.1 Verifikasi Instalasi

node -v
npm -v
git --version

Jika semua versi tampil, Anda siap.

2. Membuat Proyek Next.js 14

2.1 Inisialisasi dengan create-next-app

npx create-next-app@latest my-next14-app --typescript --eslint --src-dir --app

Parameter yang dipakai:

  • --typescript: menyiapkan TypeScript out‑of‑the‑box.
  • --eslint: menambahkan konfigurasi ESLint standar.
  • --src-dir: memindahkan semua kode ke folder src (praktik bersih).
  • --app: mengaktifkan App Router (fitur baru di Next.js 14).

2.2 Struktur Direktori Setelah Scaffold

my-next14-app/
├─ src/
│  ├─ app/          # App Router (layout.tsx, page.tsx, etc.)
│  ├─ components/   # Reusable UI components
│  ├─ lib/          # Helper functions, API clients
│  ├─ styles/       # Global CSS / Tailwind config
│  └─ types/        # TypeScript type definitions
├─ public/          # Static assets
├─ next.config.mjs  # Next.js config (ESM)
├─ tsconfig.json    # TypeScript config
└─ package.json

3. Konfigurasi Dasar

3.1 next.config.mjs

import { defineConfig } from 'next';

export default defineConfig({
  reactStrictMode: true,
  swcMinify: true,
  images: {
    remotePatterns: [{ hostname: 'images.unsplash.com' }],
  },
  experimental: {
    appDir: true,
    serverActions: true, // baru di v14
  },
});

Pengaturan di atas mengaktifkan React Server Components (RSC) melalui serverActions dan memastikan semua gambar remote dapat dimuat dari Unsplash.

3.2 Tailwind CSS (Opsional tapi direkomendasikan)

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p

Sesuaikan tailwind.config.ts:

import type { Config } from 'tailwindcss';

export default {
  content: [
    './src/**/*.{js,ts,jsx,tsx}',
    './node_modules/@tremor/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
} satisfies Config;

Lalu tambahkan Tailwind directives ke src/styles/globals.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

4. Membuat Halaman dengan App Router & RSC

4.1 Layout Global (src/app/layout.tsx)

import './globals.css';
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Next.js 14 Demo',
  description: 'Demo app dengan App Router & React Server Components',
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    
      
        

Next.js 14 Demo

{children}
© {new Date().getFullYear()} • Powered by Next.js 14
); }

Layout ini akan dibungkus secara otomatis pada setiap halaman di dalam app/.

4.2 Halaman Index (src/app/page.tsx) – Server Component

import Image from 'next/image';
import Link from 'next/link';

export default async function HomePage() {
  // Server‑side fetch – tidak mengirim request ke klien
  const res = await fetch('https://api.github.com/repos/vercel/next.js', {
    next: { revalidate: 3600 }, // ISR 1 jam
  });
  const repo = await res.json();

  return (
    

Selamat datang di Next.js 14

Repository {repo.full_name} memiliki {repo.stargazers_count.toLocaleString()} ⭐.

Coding Lihat Dashboard
); }

Catatan: Karena file ini adalah Server Component secara default (tipe .tsx di folder app/), semua kode di atas dijalankan di server, sehingga tidak menambah bundle JS ke klien.

4.3 Dashboard (src/app/dashboard/page.tsx) – Client Component

'use client';
import { useState, useEffect } from 'react';
import { fetchWeather } from '@/lib/api';

export default function Dashboard() {
  const [weather, setWeather] = useState<null | { temp: number; desc: string }>(null);

  useEffect(() => {
    fetchWeather().then(setWeather);
  }, []);

  if (!weather) return 

Loading weather...

; return (

Weather Today

Temperature: {weather.temp}°C – {weather.desc}

); }

Dengan menambahkan 'use client' di baris pertama, file ini menjadi Client Component, yang memungkinkan penggunaan hook React.

5. Membuat API Route dengan Server Actions

5.1 Endpoint Tambah Todo (src/app/api/todos/route.ts)

import { NextResponse } from 'next/server';
import { todos } from '@/lib/store';

export async function POST(request: Request) {
  const { title } = await request.json();
  if (!title) return NextResponse.json({ error: 'Title required' }, { status: 400 });

  const newTodo = { id: Date.now(), title, completed: false };
  todos.push(newTodo);
  return NextResponse.json(newTodo, { status: 201 });
}

Server Actions memungkinkan pemanggilan fungsi server langsung dari komponen client tanpa menulis fetch manual.

5.2 Menggunakan Server Action di Client Component

'use client';
import { useState, FormEvent } from 'react';
import { addTodo } from '@/app/api/todos/route'; // auto‑import via next/server

export default function TodoForm() {
  const [title, setTitle] = useState('');

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    await addTodo({ title }); // server action call
    setTitle('');
  }

  return (
    
setTitle(e.target.value)} placeholder="Tambah todo" className="flex-1 border rounded px-2 py-1" required />
); }

6. Optimasi Production Build

6.1 Analisis Bundle dengan next-bundle-analyzer

npm install -D @next/bundle-analyzer

# next.config.mjs
import { defineConfig } from 'next';
import withBundleAnalyzer from '@next/bundle-analyzer';

export default withBundleAnalyzer({
  enabled: process.env.ANALYZE === 'true',
})(defineConfig({
  // konfigurasi sebelumnya …
}));

Jalankan ANALYZE=true npm run build untuk menghasilkan laporan visual di .next/analyze.

6.2 Caching & Revalidation

Gunakan fetch(..., { next: { revalidate: 60 } }) untuk ISR. Untuk API route, set header Cache-Control: s‑maxage=600, stale‑while‑revalidate=30 agar CDN cache optimal.

6.3 Security Hardening

  • Aktifkan crossOrigin: 'anonymous' pada Image untuk mencegah informasi referrer.
  • Gunakan Content-Security-Policy di next.config.mjs lewat headers() API.
  • Tambahkan helmet pada custom server (jika menggunakan express).

7. Deploy ke Vercel (Cara Resmi)

  1. Push repository ke GitHub.
  2. Buka vercel.com, klik New Project.
  3. Pilih repository, Vercel otomatis mendeteksi Next.js 14.
  4. Tambahkan environment variable NEXT_PUBLIC_API_URL jika diperlukan.
  5. Deploy! Vercel akan menjalankan npm run build dan menyiapkan Edge Functions untuk API routes.

8. Best Practice Ringkas

  • Folder Structure: gunakan src/app untuk routing, src/components untuk UI terisolasi, src/lib untuk logika bisnis.
  • Type Safety: selalu definisikan tipe di types/, hindari any.
  • Server vs Client: pilih Server Component secara default; hanya konversi ke Client bila diperlukan (state, effects, event handlers).
  • Incremental Static Regeneration (ISR): set revalidate pada fetch atau generateStaticParams untuk data yang tidak berubah tiap detik.
  • Testing: gunakan jest + @testing-library/react untuk unit, playwright untuk end‑to‑end.
  • Linting & Formatting: jalankan npm run lint && npm run format pada pre‑commit hook (husky).

Dengan langkah‑langkah di atas, Anda kini memiliki aplikasi Next.js 14 yang memanfaatkan App Router, React Server Components, dan Server Actions. Struktur modular, ISR, serta best practice keamanan menjadikan proyek siap produksi dan mudah dipelihara. Jangan lupa memantau ukuran bundle, mengaktifkan caching CDN, dan menambahkan tes otomatis untuk menjaga kualitas kode seiring proyek berkembang.
Tutorial lengkap Next.js 14 2026: setup App Router, React Server Components, Server Actions, CI/CD, dan best practice untuk performance serta security.

Programming,Software Engineering,Web Development,Next.js 14,React Server Components,App Router

#Programming #SoftwareEngineering #WebDev #Tech #Coding

Posting Komentar

0 Komentar