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


Next.js 15 menjadi standar baru untuk aplikasi React modern. Artikel ini memberikan tutorial step‑by‑step mulai dari instalasi, konfigurasi, contoh kode, hingga best practice untuk membangun proyek produksi siap Docker dan CI/CD.

1. Persiapan Lingkungan

Pastikan mesin Anda memiliki Node.js 20.x atau lebih baru, npm 10+ serta Docker Desktop. Verifikasi dengan:

node -v
npm -v
docker --version

1.1. Instalasi Yarn (opsional)

Yarn 4 memberikan plug‑in yang lebih cepat untuk monorepo. Instal dengan:

npm i -g yarn

2. Membuat Proyek Next.js 15

Jalankan perintah berikut untuk bootstrap project dengan TypeScript dan App Router aktif:

npx create-next-app@latest my-next15-app \
  --ts \
  --app \
  --eslint \
  --src-dir \
  --import-alias "@/*"
cd my-next15-app

Perintah di atas akan menghasilkan struktur src/ dengan app/ sebagai router utama.

3. Konfigurasi Dasar

3.1. next.config.js

Aktifkan experimental fitur baru seperti serverActions dan imageOptimization:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: {
    serverActions: true,
    appDir: true,
  },
  images: {
    remotePatterns: [{
      protocol: 'https',
      hostname: '**.cdn.jsdelivr.net',
    }],
  },
};
export default nextConfig;

3.2. TypeScript Strict Mode

Perbarui tsconfig.json agar mengikuti best practice:

{
  "compilerOptions": {
    "target": "es2022",
    "module": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": false,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "paths": { "@/*": ["./src/*"] }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

4. Membuat Halaman dengan App Router

4.1. Struktur Direktori

src/
  app/
    layout.tsx          # Root layout
    page.tsx            # Home page
    dashboard/
      layout.tsx
      page.tsx
      loading.tsx
      error.tsx
    api/
      greet/route.ts   # API route contoh

4.2. layout.tsx Global

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

export const metadata: Metadata = {
  title: 'Next.js 15 Demo',
  description: 'Tutorial step‑by‑step Next.js 15 dengan Server Actions',
};

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

4.3. page.tsx Home dengan Server Action

'use server';
import { revalidatePath } from 'next/cache';

export async function addMessage(formData: FormData) {
  // Simulasi penyimpanan ke DB (di contoh gunakan serverless SQLite)
  const message = formData.get('message') as string;
  // TODO: async DB insert
  console.log('Saved:', message);
  // Force re‑validation pada halaman utama
  revalidatePath('/');
}

export default function HomePage() {
  return (
    

Welcome to Next.js 15

); }

Langkah di atas menunjukkan bagaimana server actions menggantikan API route tradisional untuk operasi yang bersifat mutasi.

5. Menambahkan API Route Tradisional (opsional)

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

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get('name') || 'World';
  return NextResponse.json({ message: `Hello, ${name}!` });
}

6. Styling dengan Tailwind CSS 3.4

Instalasi cepat:

yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p

Update tailwind.config.js untuk mendukung app/ folder:

module.exports = {
  content: ['./src/**/*.{js,ts,jsx,tsx}'],
  theme: { extend: {} },
  plugins: [],
};

7. Dockerize Project

7.1. Dockerfile

# syntax=docker/dockerfile:1
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build

FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./
COPY --from=builder /app/yarn.lock ./
RUN yarn install --production --frozen-lockfile && yarn cache clean
EXPOSE 3000
CMD ["node", "server.js"]

7.2. Docker Compose (optional)

version: '3.9'
services:
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NEXT_PUBLIC_API_URL=https://api.example.com
    restart: unless-stopped

8. CI/CD dengan GitHub Actions

name: Deploy to Docker Hub
on:
  push:
    branches: [main]
jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      - name: Install deps
        run: yarn install --frozen-lockfile
      - name: Build
        run: yarn build
      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Build & push image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ secrets.DOCKER_USERNAME }}/next15-demo:latest

9. Best Practice untuk Production

  • Static Rendering: gunakan export const revalidate = 60; pada halaman yang dapat di‑ISR untuk mengurangi beban server.
  • Environment Variables: simpan secret di .env.production dan gunakan process.env.NEXT_PUBLIC_* untuk variabel yang dapat di‑expose ke client.
  • Image Optimization: manfaatkan next/image dengan remote pattern yang sudah didefinisikan di next.config.js.
  • Security Headers: tambahkan middleware untuk CSP, X‑Frame‑Options, dll.
  • Monitoring: integrasikan dengan Vercel Analytics atau solusi open‑source seperti Prometheus + Grafana lewat sidecar container.

10. Testing dengan Playwright

Instalasi dan contoh tes e2e:

yarn add -D @playwright/test
npx playwright install

// tests/home.spec.ts
import { test, expect } from '@playwright/test';

test('home page can submit message', async ({ page }) => {
  await page.goto('/');
  await page.fill('input[name="message"]', 'Hello Next 15');
  await page.click('text=Save');
  await expect(page).toHaveURL('/');
  // Karena server action reloads page, cek console log atau element yang muncul
});

Jalankan dengan yarn playwright test.

11. Deploy ke Vercel atau Cloud Provider

Jika menggunakan Vercel, cukup push ke branch main. Vercel otomatis mendeteksi next.config.js dan menjalankan npm run build. Untuk AWS ECS, gunakan image yang sudah dipush ke Docker Hub dan referensikan di task definition.

12. Ringkasan Langkah

  1. Siapkan Node, Yarn, Docker.
  2. Bootstrap project dengan create-next-app@latest + TypeScript + App Router.
  3. Konfigurasi next.config.js dan tsconfig.json.
  4. Buat layout, halaman, dan server action.
  5. Tambahkan Tailwind CSS untuk styling.
  6. Buat Dockerfile & docker‑compose.
  7. Implementasikan GitHub Actions CI/CD.
  8. Ikuti best practice production (ISR, env, security).
  9. Tambahkan testing dengan Playwright.
  10. Deploy ke Vercel atau platform cloud pilihan.

Dengan mengikuti tutorial ini, Anda akan memiliki aplikasi Next.js 15 modern yang terstruktur, aman, dan siap skala menggunakan Docker serta pipeline CI/CD. Memanfaatkan Server Actions mengurangi boilerplate API, sementara App Router memberikan pengalaman routing yang bersih. Terapkan best practice seperti ISR, variabel lingkungan yang terpisah, dan monitoring untuk menjaga performa dan kehandalan di produksi.
Tutorial lengkap setup Next.js 15 dengan TypeScript, App Router, Server Actions, Docker, dan CI/CD. Langkah demi langkah, contoh kode, dan best practice untuk Web Development modern.

Programming,Software Engineering,Web Development,Next.js 15,TypeScript,Docker,CI/CD

#Programming #SoftwareEngineering #WebDev #Tech #Coding

Posting Komentar

0 Komentar