Panduan Lengkap Deploy Next.js 14 dengan App Router, Server Actions, dan Edge Runtime


Temukan cara menyiapkan proyek Next.js 14 terbaru, mengkonfigurasi App Router, memanfaatkan Server Actions, serta mengoptimalkan deployment di Vercel dengan best practice untuk performa dan keamanan.

1. Persiapan Lingkungan

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

node -v
npm -v

Jika belum terpasang, unduh dari nodejs.org.

1.1 Instalasi Next.js 14

npx create-next-app@latest my-next14-app --typescript
cd my-next14-app

Perintah di atas menghasilkan proyek Next.js dengan TypeScript, sudah terkonfigurasi untuk app/ directory (App Router).

2. Struktur Proyek dengan App Router

Next.js 14 memperkenalkan app/ folder sebagai default. Berikut contoh struktur minimal:

app/
├─ layout.tsx          # Layout global
├─ page.tsx            # Halaman index
├─ dashboard/
│   ├─ layout.tsx
│   └─ page.tsx
│   └─ actions.ts      # Server Actions
└─ api/
    └─ hello/route.ts # API Route baru

2.1 Membuat Layout Global

"use client";

import './globals.css';
import { Inter } from 'next/font/google';

const inter = Inter({ subsets: ['latin'] });

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

Layout ini dibungkus dengan "use client" karena ada interaksi UI (misalnya tema).

2.2 Membuat Halaman Dashboard

// app/dashboard/page.tsx
export default function DashboardPage() {
  return (
    

Dashboard

Selamat datang di dashboard Next.js 14.

); }

3. Menggunakan Server Actions

Server Actions memungkinkan Anda memanggil fungsi server langsung dari komponen client tanpa membuat API terpisah.

3.1 Membuat File actions.ts

// app/dashboard/actions.ts
"use server";
import { revalidatePath } from 'next/cache';

export async function addTodo(title: string) {
  // Simulasi penyimpanan ke database (mis. Prisma)
  // await prisma.todo.create({ data: { title } });
  console.log('Todo ditambahkan:', title);
  // Memaksa revalidasi halaman
  revalidatePath('/dashboard');
}

3.2 Memanggil Action dari Komponen Client

// app/dashboard/page.tsx
"use client";
import { useState, FormEvent } from 'react';
import { addTodo } from './actions';

export default function DashboardPage() {
  const [title, setTitle] = useState('');
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    await addTodo(title);
    setTitle('');
  };

  return (
    

Dashboard

setTitle(e.target.value)} placeholder="Judul todo" required />
); }

Catatan: Karena addTodo dideklarasikan dengan "use server", kode di atas otomatis dijalankan di serverless edge atau Node runtime.

4. Konfigurasi Edge Runtime

Next.js 14 memungkinkan Anda mengeksekusi halaman atau route pada Edge Runtime untuk latensi ultra‑rendah.

4.1 Mengaktifkan Edge di Route

// app/api/hello/route.ts
export const runtime = 'edge';
export async function GET() {
  return new Response(JSON.stringify({ message: 'Hello from Edge!' }), {
    headers: { 'Content-Type': 'application/json' },
  });
}

Dengan menambahkan export const runtime = 'edge';, fungsi ini akan dijalankan di Vercel Edge Network.

4.2 Menggunakan Middleware Edge

// middleware.ts
import { NextResponse } from 'next/server';

export const config = { matcher: '/dashboard/:path*' };

export function middleware(request) {
  const url = request.nextUrl;
  // Contoh: blokir akses jika tidak ada cookie auth
  if (!request.cookies.has('auth')) {
    url.pathname = '/login';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

5. Optimasi Performa & Best Practice

  • Static Generation (SSG) bila memungkinkan: gunakan export const revalidate = 60; untuk ISR.
  • Image Optimization: ganti next/image dengan next/future/image untuk dukungan AVIF/WebP otomatis.
  • Cache Header: atur Cache-Control di API routes untuk data yang jarang berubah.
  • Security Headers: tambahkan Strict-Transport-Security, X-Content-Type-Options, dan CSP via next.config.js atau middleware.
  • TypeScript Strict Mode: pastikan strict:true di tsconfig.json untuk mengurangi bug runtime.

5.1 Contoh next.config.js dengan Security Headers

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  experimental: { appDir: true },
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          { key: 'X-Frame-Options', value: 'DENY' },
          { key: 'X-Content-Type-Options', value: 'nosniff' },
          { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
          {
            key: 'Content-Security-Policy',
            value: "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' https://api.vercel.com;",
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

6. Deploy ke Vercel (Free Tier)

  1. Login atau buat akun di vercel.com.
  2. Push kode ke GitHub (mis. git push origin main).
  3. Di dashboard Vercel, pilih New Project → import repository.
  4. Vercel otomatis mendeteksi next.config.js dan mengaktifkan next build.
    • Pastikan Framework Preset terpilih “Next.js”.
  5. Atur environment variables jika diperlukan (mis. DATABASE_URL).
  6. Deploy! Vercel akan meng‑build, lalu menyediakan URL https://your-project.vercel.app.

6.1 Verifikasi Edge Runtime

Buka https://your-project.vercel.app/api/hello. Pada response header Anda akan melihat x-vercel-id dengan nilai berakhiran edge, menandakan eksekusi di Edge.

7. Monitoring & Logging

Gunakan Vercel Analytics untuk metric Core Web Vitals. Tambahkan @vercel/analytics untuk tracking custom events:

npm install @vercel/analytics

// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';

export default function RootLayout({ children }) {
  return (
    
      {children}
    
  );
}

Untuk log server, gunakan console.log dalam Server Actions; Vercel Edge menampilkannya di “Functions > Logs”.

8. Penutup

Dengan mengikuti langkah‑langkah di atas, Anda memiliki proyek Next.js 14 yang modern, menggunakan App Router, Server Actions, dan Edge Runtime. Kombinasi ini memberikan UI reaktif, latency rendah, serta keamanan dan skalabilitas yang cocok untuk aplikasi produksi tahun 2026.


Next.js 14 memperkenalkan paradigma baru yang menyederhanakan routing, data fetching, dan eksekusi di edge. Dengan mengadopsi App Router, Server Actions, serta best practice security dan performance, Anda dapat membangun aplikasi web yang cepat, aman, dan siap bersaing di pasar modern. Selamat mencoba, dan jangan lupa memantau performa melalui Vercel Analytics serta terus memperbarui dependensi untuk menjaga keamanan.
Panduan lengkap step-by-step setup Next.js 14 dengan App Router, Server Actions, dan Edge Runtime, termasuk konfigurasi, contoh kode, best practice, dan deployment di Vercel.

Programming,Software Engineering,Web Development

#Programming #SoftwareEngineering #WebDev #Tech #Coding

Posting Komentar

0 Komentar