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


Next.js 14 menjadi standar de‑facto untuk aplikasi React modern. Tutorial ini menuntun Anda langkah demi langkah menginstal, mengkonfigurasi, dan memanfaatkan fitur App Router serta Server Actions, lengkap dengan contoh kode, best practice, dan tips performa untuk produksi.

1. Persiapan Lingkungan

Pastikan Anda menggunakan Node.js LTS 20.x atau lebih tinggi dan npm versi 10.x. Verifikasi dengan:

node -v
npm -v

Jika belum terpasang, unduh dari nodejs.org.

2. Membuat Project Next.js 14 Baru

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

Opsi --ts mengaktifkan TypeScript secara default, yang kini menjadi best practice dalam Software Engineering.

3. Mengaktifkan App Router

Next.js 14 menggantikan pages/ dengan app/. Jika tidak otomatis dibuat, lakukan:

mkdir app
mv pages/index.tsx app/page.tsx
mv pages/_app.tsx app/layout.tsx

File layout.tsx menjadi root layout dan otomatis menyertakan <html> serta <body> tag.

4. Menambahkan Server Actions

Server Actions memungkinkan Anda menulis fungsi server side langsung di komponen React tanpa API routes terpisah.

// app/actions.ts
'use server'
export async function addTodo(data: {title: string}) {
  // Simulasi DB (mis. Prisma atau MongoDB)
  // await db.todo.create({data});
  console.log('Todo ditambahkan:', data.title);
  return {success: true};
}

Panggil di komponen client:

// app/page.tsx
'use client'
import {addTodo} from './actions'
import {useState} from 'react'

export default function Home() {
  const [title, setTitle] = useState('')
  const handleSubmit = async (e) => {
    e.preventDefault()
    const res = await addTodo({title})
    if (res.success) setTitle('')
  }
  return (
    
setTitle(e.target.value)} placeholder="Todo title" />
) }

Catatan: Server Actions hanya dapat dipanggil dari komponen yang ditandai 'use client' karena mereka beroperasi di sisi klien.

5. Konfigurasi TypeScript & ESLint

Next.js 14 sudah menyertakan konfigurasi dasar, namun tambahkan aturan strict untuk meningkatkan kualitas kode:

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "target": "es2022",
    "module": "esnext",
    "jsx": "preserve"
  }
}

// .eslintrc.json
{
  "extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
  "rules": {
    "@typescript-eslint/no-explicit-any": "warn",
    "react/react-in-jsx-scope": "off"
  }
}

6. Menyiapkan Database dengan Prisma

Prisma tetap menjadi ORM terpopuler untuk Web Development. Instal dan inisialisasi:

npm install prisma @prisma/client
npx prisma init

Edit prisma/schema.prisma:

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Todo {
  id        Int      @id @default(autoincrement())
  title     String
  completed Boolean  @default(false)
  createdAt DateTime @default(now())
}

Jalankan migrasi:

npx prisma migrate dev --name init

Integrasikan ke Server Action:

// app/actions.ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

export async function addTodo(data: {title: string}) {
  await prisma.todo.create({data})
  return {success: true}
}

7. Optimasi Performansi

  • Image Optimization: gunakan next/image dengan loader: 'custom' bila memakai CDN.
  • Incremental Static Regeneration (ISR): tambahkan revalidate pada fetch di server components.
  • Middleware Caching: cache route dengan Cache-Control di middleware.ts.
// app/todos/page.tsx (Server Component)
import { prisma } from '@/lib/prisma'
export const revalidate = 60 // seconds
export default async function TodosPage() {
  const todos = await prisma.todo.findMany()
  return (
    
    {todos.map(t=>
  • {t.title}
  • )}
) }

8. Deployment ke Vercel (atau Platform Lain)

  1. Push repo ke GitHub.
  2. Buka vercel.com, pilih "New Project" dan hubungkan repository.
  3. Set environment variable DATABASE_URL pada dashboard Vercel.
  4. Vercel otomatis menjalankan npm run build yang menghasilkan .next statik + serverless functions.

Jika menggunakan Docker/Kubernetes, buat Dockerfile berikut:

FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json .
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/public ./public
EXPOSE 3000
CMD ["npm","run","start"]

9. Best Practice untuk Keamanan

  • Gunakan Content‑Security‑Policy di next.config.js.
  • Validasi semua input server side; gunakan library zod untuk skema.
  • Hindari menaruh rahasia di client bundle; gunakan process.env.NEXT_PUBLIC_… hanya untuk data non‑sensitif.

10. Debugging & Monitoring

Pasang @sentry/nextjs untuk error tracking produksi:

npm install @sentry/nextjs
npx @sentry/wizard -i nextjs

Gunakan next dev dengan --inspect untuk debugging Node.

11. Ringkasan Workflow CI/CD dengan GitHub Actions

name: CI
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npm run lint
      - run: npm run test
      - run: npm run build
      - name: Deploy to Vercel
        uses: amondnet/vercel-action@v20
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          production: true

Workflow ini memastikan setiap commit melewati linting, testing, dan build sebelum otomatis dipublish.


Dengan mengikuti tutorial ini, Anda akan memiliki aplikasi Next.js 14 yang memanfaatkan App Router, Server Actions, dan Prisma, sekaligus menerapkan praktik keamanan, performa, dan CI/CD modern. Kombinasi ini memberikan fondasi kuat bagi tim Programming yang mengutamakan Software Engineering berkelanjutan dan Web Development skala produksi.
Panduan lengkap step‑by‑step setup Next.js 14 dengan App Router, Server Actions, Prisma, dan deployment ke Vercel atau Docker. Termasuk best practice keamanan, performance, dan CI/CD.

Programming,Software Engineering,Web Development,Next.js 14,Server Actions,App Router,Prisma,CI/CD

#Programming #SoftwareEngineering #WebDev #Tech #Coding

Posting Komentar

0 Komentar