Next.js 15 telah menjadi standar de‑facto untuk aplikasi React modern dengan fokus pada server‑side rendering, streaming, dan integrasi AI. Tutorial ini menuntun Anda step‑by‑step mulai dari instalasi, konfigurasi, contoh kode, hingga best practice untuk menjaga performa dan keamanan.
1. Persiapan Lingkungan
Pastikan Anda memiliki Node.js LTS terbaru (v20.10 atau lebih tinggi) dan npm atau pnpm versi 9+. Verifikasi dengan:
node -v
npm -v # atau pnpm -v
Jika belum terpasang, unduh dari nodejs.org.
2. Membuat Project Next.js 15 Baru
Gunakan perintah resmi create-next-app dengan flag --ts untuk TypeScript dan --app untuk mengaktifkan App Router secara default.
npx create-next-app@latest my-next15-app --ts --app
cd my-next15-app
Struktur folder yang dihasilkan akan mencakup app/ (bukan pages/) serta src/ bila Anda memilih opsi itu.
3. Instalasi Dependensi Tambahan
Untuk fitur terbaru, tambahkan paket berikut:
# Manajemen state (optional but recommended)
pm install zustand
# Tailwind CSS untuk styling cepat
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
# React Hook Form untuk form handling yang terintegrasi dengan Server Actions
npm install react-hook-form
# ESLint & Prettier untuk standar kode
npm install -D eslint eslint-config-next prettier
Konfigurasi tailwind.config.js:
module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx}',
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: { extend: {} },
plugins: [],
};
4. Mengaktifkan Server Actions
Next.js 15 memperkenalkan Server Actions yang memungkinkan Anda menulis fungsi server langsung di dalam komponen React tanpa API routes terpisah. Pastikan experimental flag di next.config.js di‑enable:
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverActions: true,
},
};
module.exports = nextConfig;
Setelah itu, Anda dapat menulis aksi seperti berikut di dalam app/contact/page.tsx:
"use server";
import { redirect } from "next/navigation";
export async function sendMessage(formData: FormData) {
// Validasi sederhana
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const message = formData.get("message") as string;
if (!name || !email || !message) {
throw new Error("All fields are required");
}
// Simulasi penyimpanan ke DB (replace dengan Prisma dll.)
await new Promise((res) => setTimeout(res, 500));
// Setelah berhasil, redirect ke halaman terima kasih
redirect("/thank-you");
}
Komponen React yang memanggil aksi ini:
import { useForm } from "react-hook-form";
import { sendMessage } from "./page";
export default function ContactForm() {
const { register, handleSubmit } = useForm();
const onSubmit = async (data: any) => {
const formData = new FormData();
Object.entries(data).forEach(([key, value]) =>
formData.append(key, value as string)
);
await sendMessage(formData);
};
return (
);
}
Catatan: Karena aksi berjalan di server, semua proses berat (validasi, DB, AI call) tetap aman.
5. Konfigurasi TypeScript yang Ketat
Perbarui tsconfig.json untuk mengaktifkan strict mode dan menambahkan alias path:
{
"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",
"baseUrl": ".",
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Ini memaksa penulisan tipe yang jelas, mengurangi bugs runtime.
6. Menambahkan Middleware untuk Keamanan
Next.js 15 mendukung middleware tingkat aplikasi. Buat file middleware.ts di root proyek untuk menolak request berbahaya dan menambahkan CSP.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Content Security Policy yang ketat
response.headers.set(
"Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline';"
);
// Rate limiting sederhana (contoh)
const ip = request.ip ?? "unknown";
// Implementasikan storage Redis atau KV untuk hit count di produksi
return response;
}
export const config = {
matcher: ["/:path*"],
};
Middleware dijalankan sebelum halaman atau API diproses, sehingga keamanan terjaga sejak awal.
7. Deploy dengan Vercel (Edge Runtime)
Vercel tetap menjadi platform utama untuk Next.js. Ikuti langkah berikut:
- Push kode ke GitHub (atau GitLab) dengan branch
main. - Buka Vercel dashboard, pilih repository.
- Pastikan pengaturan Framework Preset terdeteksi sebagai
Next.jsdan pilih Edge Functions untuk Server Actions. - Tambahkan environment variables (misalnya
DATABASE_URL). - Deploy! Vercel otomatis meng‑build dengan
next builddan meng‑optimasi gambar, CSS, dll.
Setelah deploy, periksa /_next/trace untuk memastikan Server Actions berjalan di Edge.
8. Monitoring & Performance
Gunakan Vercel Analytics atau OpenTelemetry untuk tracing. Tambahkan SDK di app/layout.tsx:
import { initOpenTelemetry } from "@opentelemetry/sdk-node";
if (process.env.NODE_ENV === "production") {
initOpenTelemetry({
serviceName: "my-next15-app",
exporterUrl: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
});
}
Dengan ini Anda dapat mengidentifikasi bottleneck pada Server Actions atau streaming SSR.
9. Best Practice Tambahan
- Static Site Generation (SSG) untuk halaman yang tidak berubah (gunakan
generateStaticParams). - Incremental Static Regeneration (ISR) dengan
revalidatepadafetchdi server components. - Gunakan React Server Components untuk rendering data‑intensive UI tanpa mengirim JS ke client.
- Selalu lint kode dengan
npm run lintdan format denganprettier. - Jaga dependencies tetap terbaru; gunakan
npm outdateddannpm auditsecara berkala.
10. Pengujian End‑to‑End dengan Playwright
Instal Playwright dan buat skrip tes dasar untuk form contact:
npm install -D @playwright/test
npx playwright init
// tests/contact.spec.ts
import { test, expect } from "@playwright/test";
test("submit contact form", async ({ page }) => {
await page.goto("/contact");
await page.fill('input[name="name"]', "John Doe");
await page.fill('input[name="email"]', "john@example.com");
await page.fill('textarea[name="message"]', "Testing Server Actions");
await page.click('button[type="submit"]');
await expect(page).toHaveURL(/\/thank-you/);
});
Jalankan npx playwright test untuk memastikan alur Server Action berfungsi pada environment CI.
11. Upgrade ke Next.js 15.2 (Jika Tersedia)
Next.js merilis minor version tiap 2‑3 bulan. Untuk memperbarui:
npm install next@latest
# Pastikan peer dependencies (react, react-dom) juga terbaru
npm install react@latest react-dom@latest
Setelah upgrade, periksa changelog resmi di Next.js Changelog untuk fitur baru seperti Parallel Routing atau AI‑assisted Image Optimization.
12. Integrasi AI (Opsional)
Dengan OpenAI API v2 (2026), Anda dapat menambahkan AI‑generated content pada server actions. Contoh:
"use server";
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function generateBlogOutline(topic: string) {
const response = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: `Buat outline blog tentang ${topic}` }],
max_tokens: 300,
});
return response.choices[0].message.content;
}
Panggil fungsi ini di halaman /app/blog/new/page.tsx dan tampilkan outline secara streaming.
13. Ringkasan Step‑by‑Step
- Pasang Node.js LTS.
- Gunakan
create-next-app@latestdengan--ts --app. - Instal dependensi tambahan (Tailwind, zustand, eslint, dll).
- Aktifkan
serverActionsdinext.config.js. - Buat Server Action
sendMessagedan form React. - Konfigurasi TypeScript
strictdan alias. - Tambahkan middleware keamanan.
- Deploy ke Vercel (Edge Runtime).
- Set up monitoring dengan OpenTelemetry.
- Ikuti best practice SSG/ISR, linting, dan dependencies.
- Uji dengan Playwright.
- Upgrade ke versi terbaru bila rilis.
- (Opsional) Integrasi OpenAI API untuk content AI.
Dengan mengikuti tutorial ini, Anda akan memiliki aplikasi Next.js 15 yang modern, type‑safe, dan siap produksi. Memanfaatkan Server Actions, App Router, dan TypeScript memberi keuntungan performa signifikan, sementara middleware dan monitoring menjaga keamanan serta observabilitas. Selalu periksa changelog Next.js dan update dependencies secara rutin agar tetap selangkah di depan dalam ekosistem React yang terus berkembang.
Tutorial step‑by‑step setup Next.js 15 dengan App Router, Server Actions, TypeScript, dan best practice keamanan serta performance untuk developer modern.
Programming,Software Engineering,Web Development
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar