Temukan langkah demi langkah cara menginstal, mengonfigurasi, dan mengoptimalkan proyek Next.js 14 terbaru, lengkap dengan contoh kode, best practice, serta integrasi Server Actions untuk meningkatkan produktivitas dan keamanan aplikasi web modern.
1. Prasyarat dan Persiapan Lingkungan
Pastikan mesin Anda memenuhi persyaratan berikut:
- Node.js v20.10+ (LTS terbaru pada Juli 2026).
- npm v10.5+ atau yarn 4+.
- Git untuk version control.
- Editor kode pilihan (VS Code disarankan) dengan ekstensi Next.js dan ESLint.
2. Instalasi Next.js 14 – Project Baru
npx create-next-app@latest my-next14-app --ts
cd my-next14-app
Perintah di atas membuat proyek berbasis TypeScript dengan struktur standar. Tambahkan flag --experimental-app bila Anda ingin mengaktifkan App Router secara eksplisit (meskipun di v14 sudah default).
3. Mengaktifkan App Router
Next.js 14 memperkenalkan App Router yang menggantikan pages/. Pastikan folder app/ ada di root proyek. Jika tidak, buat secara manual:
mkdir app
Contoh struktur minimal:
app/
├─ layout.tsx
├─ page.tsx
└─ (dashboard)/
├─ layout.tsx
└─ page.tsx
3.1. layout.tsx
import './globals.css';
export const metadata = {
title: 'Next.js 14 – App Router Demo',
description: 'Demo aplikasi dengan App Router dan Server Actions',
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
3.2. page.tsx (beranda)
export default function HomePage() {
return (
Selamat Datang di Next.js 14
Ini contoh halaman utama menggunakan App Router.
);
}
4. Memanfaatkan Server Actions (Beta di v14)
Server Actions memungkinkan Anda menulis fungsi async yang dieksekusi di server tanpa API route terpisah. Berikut contoh pembuatan form kontak.
4.1. Membuat file action.ts
"use server";
import { revalidatePath } from 'next/cache';
export async function submitContact(formData: FormData) {
const name = formData.get('name')?.toString() ?? '';
const email = formData.get('email')?.toString() ?? '';
const message = formData.get('message')?.toString() ?? '';
// Simulasi penyimpanan ke DB (misalnya Prisma)
// await prisma.contact.create({ data: { name, email, message } });
console.log('Contact submitted:', { name, email, message });
// Optional: revalidate path untuk ISR
revalidatePath('/contact/thanks');
return { success: true };
}
4.2. Form di page.tsx
import { submitContact } from './action';
export default function ContactPage() {
return (
);
}
Setelah submit, fungsi submitContact dijalankan di server, menghindari ekspos token API atau koneksi DB ke client.
5. Konfigurasi ESLint, Prettier, dan TypeScript Strict Mode
Pastikan kualitas kode dengan menambahkan file konfigurasi berikut.
5.1. .eslintrc.json
{
"extends": [
"next/core-web-vitals",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"react-hooks/exhaustive-deps": "warn"
}
}
5.2. .prettierrc
{
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 100
}
5.3. tsconfig.json (strict)
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"strict": true,
"noImplicitAny": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
6. Optimasi Performance – Image, Font, dan Caching
- next/image: gunakan
<Image>denganfilldanpriorityuntuk gambar hero. - next/font: impor Google Font secara dinamis untuk mengurangi FOUT.
- Cache-Control: di
next.config.jstambahkanheadersuntuk static assets.
6.1. next.config.js contoh
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
remotePatterns: [{ protocol: 'https', hostname: 'images.unsplash.com' }],
},
async headers() {
return [
{
source: '/:all*(svg|jpg|png)',
headers: [{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }],
},
];
},
};
export default nextConfig;
7. Deploy ke Vercel (Zero‑Config) atau Docker
7.1. Deploy Vercel
- Push repository ke GitHub.
- Buka vercel.com, pilih New Project.
- Hubungkan repository, biarkan Vercel mendeteksi
next.config.js. Klik Deploy.
Vercel otomatis mengaktifkan Edge Functions untuk Server Actions, memastikan latensi rendah.
7.2. Deploy dengan Docker (untuk cloud lain)
# Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package*.json ./
EXPOSE 3000
ENV NODE_ENV production
CMD ["npm", "start"]
Build & run:
docker build -t next14-app .
docker run -p 3000:3000 next14-app
8. Best Practice untuk Proyek Production
- Folder Structure: pisahkan
app/(UI) danlib/(business logic) untuk Clean Architecture. - Environment Variables: gunakan
.env.localuntuk dev,.env.productionuntuk prod, dan akses viaprocess.env.NEXT_PUBLIC_*hanya untuk data yang boleh di‑expose. - Security: enable
Content‑Security‑Policyheader dinext.config.js, sertahelmetjika Anda menambahkan custom server. - Testing: gunakan
jest+@testing-library/reactuntuk unit & integration, danplaywrightuntuk e2e. - Monitoring: integrasikan dengan Vercel Analytics atau OpenTelemetry untuk tracing Server Actions.
9. Studi Kasus: Migrasi Aplikasi Legacy React ke Next.js 14
Perusahaan X memiliki aplikasi SPA ber‑basis Create‑React‑App (CRA) dengan 200 ribu baris kode. Tantangan: SEO, performa, dan biaya server. Tim migrasi mengikuti langkah berikut:
- Membuat monorepo dengan
npm workspaces, menambahkanapp/baru. - Memindahkan route ke folder
(dashboard)/di App Router, menggantikanreact‑router. - Mengubah fetch data dari
axiosclient‑side menjadifetchdalam Server Components, mengurangi bundle size 30%. - Mengaktifkan Server Actions untuk form pendaftaran, mengeliminasi kebutuhan endpoint terpisah.
- Deploy ke Vercel, mengamankan statis dengan edge caching, menghasilkan LCP < 1.2s dan skor Lighthouse > 95.
Hasil: peningkatan konversi 12% karena SEO yang lebih baik, serta penurunan biaya hosting 40%.
Dengan mengikuti panduan langkah demi langkah ini, Anda dapat membangun aplikasi Next.js 14 yang modern, aman, dan teroptimasi untuk performa tinggi. Manfaatkan App Router untuk struktur UI yang bersih, Server Actions untuk logika backend tanpa API terpisah, serta praktik terbaik linting, TypeScript strict mode, dan caching. Setelah selesai, deploy dengan Vercel untuk skalabilitas otomatis atau Docker untuk kontrol penuh pada penyedia cloud pilihan Anda. Selamat coding!
Panduan lengkap setup Next.js 14 dengan App Router, Server Actions, optimasi performance, dan best practice. Termasuk contoh kode, Docker, dan studi kasus migrasi.
Programming,Software Engineering,Web Development
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar