Next.js 14 menjadi standar de‑facto untuk aplikasi React modern. Tutorial ini membimbing Anda dari instalasi, konfigurasi, hingga deployment optimal di Vercel, lengkap dengan contoh kode Server Actions dan best practice keamanan serta performa.
1. Prasyarat dan Persiapan Lingkungan
Pastikan Anda memiliki:
- Node.js v20.12.0 atau lebih tinggi (LTS)
- npm 10.5.0 atau Yarn 4
- Git 2.45
- Akun Vercel (opsional untuk deployment)
Verifikasi versi dengan node -v dan 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 --app
cd my-next14-app
Parameter --ts mengaktifkan TypeScript, sedangkan --app menginisialisasi struktur App Router (folder app/).
3. Instalasi Dependensi Tambahan
Kita akan menambahkan beberapa library yang kini menjadi standar di ekosistem Next.js 14:
next-authuntuk otentikasizoduntuk validasi schemareact-query(atau@tanstack/react-query) untuk data fetching
npm i next-auth zod @tanstack/react-query
npm i -D @types/node
4. Konfigurasi next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
experimental: {
serverActions: true, // aktivasi Server Actions (stable sejak v14.1)
appDir: true,
},
images: {
remotePatterns: [{
protocol: 'https',
hostname: 'images.unsplash.com',
}],
},
};
export default nextConfig;
Aktifkan serverActions agar fungsi "use server" dapat dipanggil dari komponen client.
5. Membuat Layout Global dengan Tailwind CSS
Next.js 14 terintegrasi baik dengan Tailwind. Install dan konfigurasikan:
npm i -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Update tailwind.config.js:
module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx}',
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
};
Tambahkan Tailwind directives ke app/globals.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
6. Implementasi Server Action: Formulir Kontak
Server Actions memungkinkan eksekusi kode server langsung dari komponen client tanpa API route terpisah.
6.1. Buat file app/contact/page.tsx
"use client";
import { useState, FormEvent } from 'react';
import { z } from 'zod';
// Definisikan schema validasi
const ContactSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
message: z.string().min(10),
});
export default function ContactPage() {
const [status, setStatus] = useState('idle');
const [error, setError] = useState('');
async function handleSubmit(event: FormEvent) {
event.preventDefault();
setStatus('loading');
const formData = new FormData(event.currentTarget);
const payload = Object.fromEntries(formData);
try {
// Validasi di client dulu (optional)
ContactSchema.parse(payload);
// Panggil Server Action
await sendContact(payload as any);
setStatus('success');
} catch (e: any) {
setError(e.message);
setStatus('error');
}
}
return (
Hubungi Kami
);
}
// ---- Server Action ----
"use server";
import nodemailer from 'nodemailer';
async function sendContact(data: { name: string; email: string; message: string }) {
// Pastikan environment variable sudah terdefinisi
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: true,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
await transporter.sendMail({
from: `"Contact Form" <${process.env.SMTP_USER}>`,
to: process.env.CONTACT_RECEIVER,
subject: `Pesan dari ${data.name}`,
text: `Email: ${data.email}\n\n${data.message}`,
});
}
Catatan:
- Gunakan
.env.localuntuk menyimpanSMTP_*danCONTACT_RECEIVER. - Server Action otomatis dijalankan di server; tidak ada ekspos endpoint publik.
7. Penambahan Middleware untuk Keamanan CSP & Rate Limiting
Buat file middleware.ts di root proyek.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import rateLimit from 'next-rate-limit';
const limiter = rateLimit({
interval: 60 * 1000, // 1 menit
uniqueTokenPerInterval: 500,
});
export async function middleware(request: NextRequest) {
// CSP Header
const response = NextResponse.next();
response.headers.set('Content-Security-Policy', "default-src 'self'; img-src https: data:; script-src 'self' 'unsafe-inline';");
// Rate limiting pada semua API route
if (request.nextUrl.pathname.startsWith('/api')) {
const ip = request.ip ?? 'unknown';
const { remaining, reset, limitExceeded } = await limiter.check(ip);
if (limitExceeded) {
return new NextResponse('Too Many Requests', { status: 429 });
}
response.headers.set('X-RateLimit-Remaining', String(remaining));
response.headers.set('X-RateLimit-Reset', String(reset));
}
return response;
}
export const config = {
matcher: ['/api/:path*'],
};
Middleware ini menambah CSP dan rate limiting, dua best practice penting untuk produksi.
8. Optimasi Build dan Analisis Bundle
Next.js 14 menyertakan next-bundle-analyzer. Install dan konfigurasi:
npm i -D @next/bundle-analyzer
Update next.config.js:
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// konfigurasi sebelumnya ...
});
Jalankan ANALYZE=true npm run build untuk menghasilkan laporan .next/analyze/client.html. Pastikan tidak ada paket berukuran >150 KB tanpa code‑splitting.
9. Deploy ke Vercel dengan Preview Deploy otomatis
- Push repository ke GitHub.
- Login ke Vercel, pilih Import Project, hubungkan repo.
- Vercel otomatis mendeteksi
next.config.jsdan mengaktifkan Serverless Functions untuk Server Actions. - Tambahkan environment variable (
SMTP_HOST,SMTP_PORT, dll) di dashboard Vercel. - Set
Deploy Hookuntuk integrasi CI/CD dengan GitHub Actions (opsional).
Setelah selesai, setiap PR menghasilkan Preview Deploy yang dapat dibagikan ke tim QA.
10. Monitoring & Logging di Produksi
Gunakan Vercel Observability atau integrasi dengan Logtail untuk log server. Tambahkan kode berikut di app/_app.tsx untuk meng‑capture error secara global:
import { useEffect } from 'react';
import * as Sentry from '@sentry/nextjs';
export default function MyApp({ Component, pageProps }: any) {
useEffect(() => {
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
tracesSampleRate: 1.0,
});
}, []);
return ;
}
Sentry memberikan stack trace terperinci untuk Server Actions sekaligus client‑side error.
11. Best Practice Tambahan
- Type‑Safe API: gunakan
zodatauclass‑validatordi Server Actions untuk memvalidasi semua input. - Image Optimization: manfaatkan
next/imagedengan loader default; tambahkan domain CDN dinext.config.js. - Incremental Static Regeneration (ISR): untuk halaman yang berubah tiap beberapa menit, gunakan
revalidatepadafetchataugenerateStaticParams. - Cache-Control Header: atur di API route atau middleware untuk asset statis, contoh
Cache-Control: public, max-age=31536000, immutable. - Security: aktifkan
strictMode, gunakanhelmetdi custom server (jika memakaiexpress).
12. Verifikasi dan Testing
Jalankan unit test dengan jest dan integration test dengan playwright:
npm i -D jest @testing-library/react @testing-library/jest-dom playwright
# contoh script di package.json
"scripts": {
"test": "jest",
"test:e2e": "playwright test"
}
Pastikan semua test lulus sebelum merge ke main.
Dengan mengikuti langkah‑langkah di atas, Anda memiliki aplikasi Next.js 14 yang memanfaatkan App Router, Server Actions, keamanan middleware, dan pipeline CI/CD modern. Kombinasi TypeScript, Zod, dan React Query memberikan kode yang tahan bug, sementara Vercel Preview Deploy dan observability memastikan iterasi cepat dan stabilitas produksi. Terapkan best practice yang tercantum untuk menjaga performa, ukuran bundle, dan keamanan aplikasi Anda dalam jangka panjang.
Tutorial step-by-step setup Next.js 14 dengan App Router, Server Actions, middleware keamanan, dan deployment Vercel. Termasuk contoh kode, best practice, dan optimasi produksi untuk Programming, Software Engineering, dan Web Development.
Programming,Software Engineering,Web Development,Next.js 14,Server Actions,Vercel,React,TypeScript
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar