Next.js 14 menjadi standar de‑facto untuk pengembangan web full‑stack modern. Tutorial ini mengajarkan langkah‑langkah instalasi, konfigurasi, contoh kode, serta best practice agar proyek Anda siap produksi dalam hitungan menit.
1. Prasyarat
Pastikan Anda memiliki:
- Node.js v20.10 atau lebih baru (download)
- npm atau Yarn (kami pakai
npmdi contoh) - Git untuk version control
- Editor kode modern, contoh VS Code
2. Membuat Project Next.js 14
npx create-next-app@latest my-next14-app --ts
cd my-next14-app
Opsional: tambahkan --app untuk langsung mengaktifkan App Router (termasuk di template terbaru). Template ini sudah ter‑setup dengan TypeScript, ESLint, dan Prettier.
3. Memeriksa Versi & Mengaktifkan Experimental Features
# Pastikan versi Next.js
npm list next
# Jika masih < 14, upgrade
npm install next@latest
# Tambahkan experimental flags di next.config.js
module.exports = {
experimental: {
appDir: true, // App Router
serverActions: true, // Server Actions (React 19)
serverComponentsExternalPackages: ["@mui/material"] // contoh eksternal UI library
},
images: { remotePatterns: [{ protocol: "https", hostname: "**" }] },
reactStrictMode: true,
};
4. Struktur Direktori App Router
Folder app menggantikan pages. Contoh struktur minimal:
app/
├─ layout.tsx # layout global
├─ page.tsx # homepage
├─ dashboard/
│ ├─ layout.tsx # layout khusus dashboard
│ └─ page.tsx # halaman dashboard
└─ api/
└─ hello/route.ts # API route (Server Component)
5. Membuat Layout Global dengan Server Component
// app/layout.tsx
import './globals.css';
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Next.js 14 Demo',
description: 'Demo App Router & Server Components',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
Karena ini Server Component, tidak ada bundle JavaScript di sisi klien untuk layout ini, sehingga perfomance lebih baik.
6. Menambahkan Server Action (form submit tanpa API route)
// app/contact/page.tsx
'use client'; // Karena akan ada interaksi client side
import { useState, FormEvent } from 'react';
export default function ContactPage() {
const [status, setStatus] = useState('');
async function handleSubmit(e: FormEvent) {
e.preventDefault();
const form = e.target as HTMLFormElement;
const data = new FormData(form);
const res = await fetch('/api/contact', {
method: 'POST',
body: data,
});
const json = await res.json();
setStatus(json.message);
}
return (
);
}
Endpoint server‑side berada di app/api/contact/route.ts:
// app/api/contact/route.ts
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const formData = await request.formData();
const name = formData.get('name');
const message = formData.get('message');
// Simulasi penyimpanan atau panggilan API eksternal
console.log('Contact from', name, ':', message);
return NextResponse.json({ message: 'Terima kasih, kami akan menghubungi Anda!' });
}
7. Mengintegrasikan UI Library (MUI) dengan Server Components
MUI v6 sudah mendukung server components. Instalasi:
npm install @mui/material @emotion/react @emotion/styled
Gunakan di client component:
// app/dashboard/page.tsx
'use client';
import { Button } from '@mui/material';
export default function Dashboard() {
return (
Dashboard
);
}
8. Optimasi Gambar dengan Next Image
Pastikan next.config.js memiliki remote patterns atau domain yang di‑allow. Contoh:
images: { remotePatterns: [{ protocol: 'https', hostname: 'images.unsplash.com' }] }
Lalu di komponen:
import Image from 'next/image';
export function Hero() {
return (
);
}
9. Menyiapkan CI/CD dengan GitHub Actions
# .github/workflows/ci.yml
name: CI & Deploy
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v3
with:
node-version: '20'
- run: npm ci
- run: npm run lint
- run: 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: .
CI memastikan lint, type‑check, dan build berhasil sebelum otomatis deploy ke Vercel (platform rekomendasi untuk Next.js).
10. Best Practice untuk Production
- Static Rendering bila memungkinkan – gunakan
export const runtime = 'edge'atauexport const dynamic = 'force-static'pada page yang tidak membutuhkan data runtime. - Gunakan
next/fontuntuk loading font optimal – contohimport { Inter } from 'next/font/google'; const inter = Inter({ subsets: ['latin'] }); - Cache API route dengan
revalidate– di server component, exportexport const revalidate = 60;untuk ISR. - Audit bundle dengan
next builddannext analyze– pastikan tidak ada paket berlebih. - Enable React Strict Mode & Concurrent Features – sudah default di Next.js 14, tetap pertahankan.
- Security: gunakan
helmetmiddleware (npm install helmet) dan set header CSP dinext.config.js.async headers() { return [{ source: '/(.*)', headers: [{ key: 'Content-Security-Policy', value: "default-src 'self'; img-src https: data:; script-src 'self' 'unsafe-eval';" }] }]; }
11. Testing dengan Jest & React Testing Library
npm install -D jest @testing-library/react @testing-library/jest-dom @types/jest ts-jest
# jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
moduleNameMapper: { '^@/(.*)
Next.js 14 membawa kombinasi App Router, React Server Components, dan edge runtime yang menyederhanakan arsitektur full‑stack. Dengan mengikuti langkah‑langkah di atas—mulai dari setup dasar, integrasi UI, hingga CI/CD otomatis—Anda dapat membangun aplikasi web yang cepat, aman, dan mudah dipelihara. Terapkan best practice yang disebutkan, pantau performa secara kontinu, dan manfaatkan ekosistem Vercel untuk deployment tanpa friction. Selamat coding!
Tutorial langkah demi langkah setup Next.js 14 dengan App Router, Server Components, UI library, CI/CD, dan best practice production untuk web development modern.
Programming,Software Engineering,Web Development,Next.js,React,App Router,Server Components
#Programming #SoftwareEngineering #WebDev #Tech #Coding
: '/$1' },
};
// __tests__/Home.test.tsx
import { render, screen } from '@testing-library/react';
import Home from '@/app/page';
test('renders welcome text', () => {
render( );
expect(screen.getByText(/welcome/i)).toBeInTheDocument();
});
12. Deploy ke Vercel (atau Railway/Netlify)
- Push repository ke GitHub.
- Buka vercel.com, pilih "New Project" → import repo.
- Vercel otomatis mendeteksi Next.js, pilih Node.js 20, dan klik Deploy.
- Set environment variables (mis.
NEXT_PUBLIC_API_KEY) di Settings → Environment Variables.
Deploy selesai dalam hitungan menit, CDN global otomatis meng‑serve static assets dan server‑rendered pages.
13. Monitoring & Observability
Gunakan Vercel Analytics atau integrasi dengan Datadog/New Relic. Tambahkan middleware untuk logging request ID:
// middleware.ts
import { NextResponse } from 'next/server';
import { v4 as uuidv4 } from 'uuid';
export function middleware(request) {
const response = NextResponse.next();
const requestId = uuidv4();
response.headers.set('X-Request-ID', requestId);
console.log(`[${requestId}] ${request.method} ${request.url}`);
return response;
}
14. Ringkasan Langkah
- Instal Node.js & buat project dengan
create-next-app. - Upgrade ke Next.js 14, aktifkan experimental App Router.
- Struktur folder
app, buat layout dan page sebagai Server Components. - Tambahkan Server Action atau API Route untuk interaksi backend.
- Integrasikan UI library (MUI) dan optimasi gambar.
- Siapkan CI/CD dengan GitHub Actions & deploy ke Vercel.
- Ikuti best practice security, caching, dan performance.
- Tambahkan testing, monitoring, dan observability.
Dengan mengikuti tutorial ini, Anda akan memiliki aplikasi Next.js 14 yang modern, scalable, dan siap production.
{{ $json.conclusion }}
{{ $json.seo.meta_description }}
{{ $json.seo.keywords }}
{{ $json.hashtags }}
0 Komentar