Panduan Lengkap Setup Next.js 14 dengan App Router, Server Actions, dan TypeScript di 2026


Next.js 14 menjadi standar de‑facto untuk aplikasi React modern. Tutorial ini mengajarkan langkah demi langkah cara menginstal, mengonfigurasi, dan menulis kode dengan App Router, Server Actions, dan TypeScript, lengkap dengan best practice untuk performa dan keamanan.

1. Prasyarat dan Persiapan Lingkungan

Sebelum memulai, pastikan Anda memiliki:

  • Node.js v20.10+ (unduh di nodejs.org)
  • npm atau pnpm versi terbaru
  • Git untuk version control
  • VS Code dengan ekstensi ESLint dan Prettier

2. Membuat Project Next.js 14 Baru

npx create-next-app@latest my-next14-app \
  --typescript \
  --app-dir \
  --eslint \
  --tailwind
cd my-next14-app
git init && git add . && git commit -m "Initial commit"

Perintah di atas menghasilkan struktur folder dengan app/ (App Router) dan dukungan TypeScript serta Tailwind CSS.

3. Instalasi Dependensi Tambahan

Kita tambahkan beberapa paket yang menjadi standard di 2026:

# Manajer paket pilihan (npm, pnpm atau yarn)
pnpm add @vercel/og @next/bundle-analyzer
pnpm add -D @types/node

@vercel/og untuk generate Open Graph images secara dinamis, dan @next/bundle-analyzer untuk memantau ukuran bundle.

4. Konfigurasi next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: {
    appDir: true,
    serverActions: true, // enable Server Actions (stable in v14)
  },
  images: {
    remotePatterns: [{ hostname: 'images.unsplash.com' }],
  },
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.resolve.fallback = { fs: false, path: false };
    }
    return config;
  },
  // Bundle analyzer dapat dijalankan dengan `ANALYZE=true pnpm run build`
  ...(process.env.ANALYZE && {
    webpack(config) {
      const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
      config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' }));
      return config;
    },
  }),
};
module.exports = nextConfig;

Konfigurasi ini mengaktifkan Server Actions, mengoptimalkan gambar, dan menyiapkan analisis bundle.

5. Struktur Dasar App Router

Folder app/ berisi layout dan page. Contoh struktur minimal:

app/
├─ layout.tsx          # Root layout dengan provider global
├─ page.tsx            # Halaman utama
├─ api/
│   └─ route.ts        # API Route dengan Server Action
└─ components/
    └─ Counter.tsx    # Contoh komponen client‑side

5.1. app/layout.tsx

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

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

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

5.2. app/page.tsx

import Link from 'next/link';
import Counter from './components/Counter';

export default function HomePage() {
  return (
    

👋 Selamat Datang di Next.js 14

Tutorial ini menampilkan App Router, Server Actions, dan TypeScript.

Coba API Route dengan Server Action
); }

5.3. app/components/Counter.tsx (Client Component)

'use client';
import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    
{count}
); }

6. Membuat Server Action di API Route

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

// app/api/hello/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const { name } = await request.json();
  // Simulasi logika bisnis berat
  const greeting = `Hello, ${name}! 🎉`;
  return NextResponse.json({ greeting });
}

// optional: eksport server action untuk dipanggil dari client component
export const helloAction = async (name: string) => {
  const res = await fetch('/api/hello', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name }),
  });
  const data = await res.json();
  return data.greeting;
};

6.1. Memanggil Server Action dari Client Component

'use client';
import { useState } from 'react';
import { helloAction } from '@/app/api/hello/route';

export default function GreetForm() {
  const [name, setName] = useState('');
  const [msg, setMsg] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const greeting = await helloAction(name);
    setMsg(greeting);
  };

  return (
    
setName(e.target.value)} className="border p-2 mr-2" required /> {msg &&

{msg}

}
); }

7. Optimasi Performansi dan Best Practice

  • Edge Runtime: pindahkan API yang tidak membutuhkan akses ke filesystem ke runtime: 'edge' untuk latensi ultra‑rendah.
  • Incremental Static Regeneration (ISR): gunakan revalidate di generateStaticParams bila konten berubah tiap beberapa menit.
  • Streaming & Suspense: bagi halaman besar menjadi React.lazy + await di server component untuk streaming HTML.
  • Security: aktifkan CSP di next.config.js, sanitasi input pada server actions, dan gunakan helmet di custom server jika diperlukan.
  • Code Splitting: manfaatkan dynamic import (`await import('./HeavyComponent')`) untuk komponen yang jarang dipakai.

8. Deploy ke Vercel (Free Tier)

  1. Push repository ke GitHub.
  2. Buka vercel.com dan pilih **New Project**.
  3. Hubungkan repositori, pastikan **Framework Preset** terdeteksi sebagai *Next.js*.
  4. Tambahkan environment variable NODE_ENV=production (otomatis).
  5. Deploy! Vercel secara otomatis mengaktifkan edge functions untuk API routes.

Setelah deploy, kunjungi URL yang diberikan, dan periksa Performance > Lighthouse di Chrome DevTools untuk memastikan skor di atas 90.

9. Monitoring & Observability

Integrasikan dengan Vercel Analytics atau gunakan OpenTelemetry SDK (@opentelemetry/api) untuk melacak latency server actions.

10. Penutup

Dengan mengikuti langkah‑langkah di atas, Anda memiliki aplikasi Next.js 14 modern yang menggabungkan App Router, Server Actions, TypeScript, dan best practice terbaru. Eksperimen dengan app/api yang dijalankan di Edge, tambahkan caching strategi, atau integrasikan LLM via OpenAI API untuk meningkatkan interaktivitas.


Next.js 14 memperkenalkan paradigma baru yang menyederhanakan data fetching dan interaksi server‑client. Menguasai App Router, Server Actions, dan TypeScript kini menjadi kompetensi inti bagi developer Web Development pada 2026. Ikuti tutorial ini, kustomisasi sesuai kebutuhan proyek, dan manfaatkan Vercel atau platform cloud lain untuk scaling tanpa friction.
Panduan lengkap step-by-step setup Next.js 14 dengan App Router, Server Actions, dan TypeScript. Termasuk instalasi, konfigurasi, contoh kode, best practice, dan deployment ke Vercel.

Programming,Software Engineering,Web Development

#Programming #SoftwareEngineering #WebDev #Tech #Coding

Posting Komentar

0 Komentar