Panduan Lengkap Setup Next.js 14 dengan App Router, Server Actions, dan Optimasi Performansi (Mei 2026)


Tutorial step‑by‑step ini membahas cara menginstal, mengkonfigurasi, dan mengembangkan aplikasi web modern menggunakan Next.js 14, fitur App Router, Server Actions, dan best practice untuk keamanan serta performa di era 2026.

1. Persiapan Lingkungan Development

Pastikan Anda memiliki versi Node.js LTS terbaru (v20.x) dan npm (v10.x) atau Yarn (v4.x). Verifikasi dengan:

node -v
npm -v   # atau yarn -v

Jika belum terpasang, unduh dari nodejs.org. Untuk manajemen versi, gunakan nvm:

nvm install 20
nvm use 20

2. Membuat Proyek Next.js 14 Baru

Gunakan create‑next‑app dengan flag --experimental-app (sudah default pada v14) dan template tailwind untuk styling cepat.

npx create-next-app@latest my-next14-app \
  --ts \
  --eslint \
  --src-dir \
  --app-dir \
  --tailwind

Masuk ke direktori proyek:

cd my-next14-app

3. Struktur Direktori App Router

Next.js 14 menggantikan pages dengan app. Berikut contoh struktur minimal:

app/
├─ layout.tsx          # Root layout
├─ page.tsx            # Home page
├─ (auth)/
│  ├─ layout.tsx
│  └─ login/page.tsx
└─ dashboard/
   ├─ layout.tsx
   └─ page.tsx

Setiap folder dapat memiliki layout.tsx dan page.tsx. Folder dalam kurung (...) adalah route segment yang dapat di‑parallelize atau di‑conditional render.

4. Instalasi Dependensi Penting

npm install @next/font@latest \
  @tanstack/react-query@latest \
  zod@latest \
  react-hook-form@latest \
  axios@latest
# atau dengan yarn
yarn add @next/font @tanstack/react-query zod react-hook-form axios

Penjelasan singkat:

  • @next/font: Optimasi font otomatis.
  • @tanstack/react-query: Data fetching yang ter‑cache.
  • zod: Validasi schema TypeScript‑first.
  • react-hook-form: Form handling ringan.
  • axios: HTTP client modern.

5. Konfigurasi TypeScript & ESLint

Next.js 14 sudah menyediakan tsconfig.json yang kompatibel. Tambahkan path alias untuk kemudahan impor:

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/components/*": ["app/components/*"],
      "@/lib/*": ["app/lib/*"]
    }
  }
}

Perbarui .eslintrc.json agar mengenali alias:

{
  "settings": {
    "import/resolver": {
      "node": {
        "paths": ["src"]
      },
      "typescript": {}
    }
  }
}

6. Membuat Server Action untuk CRUD

Server Actions memungkinkan eksekusi kode server langsung dari komponen UI tanpa API route terpisah. Buat file app/dashboard/actions.ts:

"use server";
import { prisma } from '@/lib/prisma';
import { z } from 'zod';

const TodoSchema = z.object({
  title: z.string().min(1),
  completed: z.boolean().optional()
});

export async function createTodo(formData: FormData) {
  const data = Object.fromEntries(formData.entries());
  const parsed = TodoSchema.safeParse(data);
  if (!parsed.success) {
    throw new Error('Invalid input');
  }
  return await prisma.todo.create({ data: parsed.data });
}

export async function toggleTodo(id: string) {
  const todo = await prisma.todo.findUnique({ where: { id } });
  if (!todo) throw new Error('Todo not found');
  return await prisma.todo.update({
    where: { id },
    data: { completed: !todo.completed }
  });
}

Catatan: "use server" menandai file sebagai server‑only, sehingga tidak ter‑bundle ke klien.

7. Menggunakan Server Action di UI

Contoh komponen di app/dashboard/page.tsx:

import { createTodo, toggleTodo } from './actions';
import { useState, useTransition } from 'react';

export default function Dashboard() {
  const [isPending, startTransition] = useTransition();
  const [todos, setTodos] = useState([]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    const newTodo = await createTodo(formData);
    setTodos(prev => [...prev, newTodo]);
  }

  async function handleToggle(id: string) {
    startTransition(async () => {
      const updated = await toggleTodo(id);
      setTodos(prev => prev.map(t => t.id === id ? updated : t));
    });
  }

  return (
    <section>
      <h1 className="text-2xl font-bold mb-4">Dashboard</h1>
      <form onSubmit={handleSubmit} className="flex gap-2 mb-4">
        <input name="title" required placeholder="Todo title" className="input" />
        <button type="submit" disabled={isPending} className="btn-primary">
          {isPending ? 'Saving…' : 'Add'}
        </button>
      </form>
      <ul>
        {todos.map(todo => (
          <li key={todo.id} className="flex items-center gap-2">
            <input type="checkbox" checked={todo.completed} onChange={() => handleToggle(todo.id)} />
            <span className={todo.completed ? 'line-through' : ''}>{todo.title}</span>
          </li>
        ))}
      </ul>
    </section>
  );
}

8. Optimasi Performansi dengan Edge Runtime

Next.js 14 memungkinkan menjalankan route pada Edge Runtime untuk latency rendah. Tambahkan file middleware.ts di root:

import { NextResponse } from 'next/server';
export const config = { matcher: '/dashboard/:path*' };

export function middleware(request) {
  // Contoh simple auth check via JWT dalam cookie
  const token = request.cookies.get('auth');
  if (!token) return NextResponse.redirect(new URL('/login', request.url));
  return NextResponse.next();
}

Pastikan runtime: 'edge' pada layout atau page yang membutuhkan:

export const runtime = 'edge';

9. Implementasi Security Best Practices

  • Content Security Policy (CSP): Tambahkan header di next.config.js.
    module.exports = {
      async headers() {
        return [{
          source: '/(.*)',
          headers: [{
            key: 'Content-Security-Policy',
            value: "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"
          }]
        }];
      }
    };
  • Rate Limiting dengan next-rate-limit pada API routes.
  • Input Validation menggunakan zod pada semua Server Actions (lihat contoh di langkah 6).
  • HTTP Only Cookies untuk token, set di api/auth/login dengan secure dan sameSite='strict'.

10. Deploy ke Vercel dengan Preview Channels

1. Push kode ke repository GitHub. 2. Hubungkan repo ke Vercel dashboard. 3. Aktifkan Preview Deployments sehingga setiap Pull Request menghasilkan URL unik. 4. Pastikan environment variables (DATABASE_URL, NEXT_PUBLIC_API_URL) di‑set di Vercel Settings. 5. Setelah CI lulus, Vercel otomatis melakukan static optimization dan edge caching untuk route yang ditandai runtime: 'edge'.

11. Monitoring & Observability

Gunakan Vercel Analytics bersama @sentry/nextjs untuk error tracking:

npm install @sentry/nextjs
# .sentryclirc dan sentry.server.config.js sudah disediakan oleh CLI

Integrasikan dengan react-query devtools untuk melihat cache state.

12. CI/CD dengan GitHub Actions

name: Deploy Next.js 14
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npm run lint && npm run build
      - name: Deploy to Vercel
        uses: amondnet/vercel-action@v25
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          working-directory: .
          github-token: ${{ secrets.GITHUB_TOKEN }}

13. Testing Otomatis

Gunakan jest + @testing-library/react untuk unit test, dan playwright untuk end‑to‑end.

npm install -D jest @testing-library/react @testing-library/jest-dom playwright
# contoh test komponen
import { render, screen } from '@testing-library/react';
import Dashboard from '@/app/dashboard/page';

test('renders dashboard heading', () => {
  render();
  expect(screen.getByRole('heading', { name: /dashboard/i })).toBeInTheDocument();
});

14. Tips & Trik Tambahan

  • Manfaatkan next/font untuk loading font tanpa FOIT.
  • Gunakan next/image dengan loader: 'custom' bila memakai CDN gambar internal.
  • Cache API responses di edge-middleware dengan Cache-Control: s-maxage=60.
  • Set experimental.optimizePackageImports di next.config.js untuk tree‑shaking modul pihak ketiga.

Dengan mengikuti langkah‑langkah di atas, Anda dapat membangun aplikasi Next.js 14 yang modern, cepat, dan aman. Memanfaatkan App Router, Server Actions, dan Edge Runtime memberi Anda kontrol penuh atas arsitektur full‑stack tanpa menulis API terpisah, sementara integrasi CI/CD, testing, dan observability memastikan kualitas production‑grade. Selamat coding, dan terus eksplorasi fitur terbaru yang terus dirilis oleh tim Vercel!
Tutorial lengkap setup Next.js 14 dengan App Router, Server Actions, Edge Runtime, keamanan, CI/CD, dan best practice untuk performa optimal tahun 2026.

Programming,Software Engineering,Web Development,Next.js,React,Server Actions

#Programming #SoftwareEngineering #WebDev #Tech #Coding

Posting Komentar

0 Komentar