Next.js 15 hadir dengan fitur-fitur modern seperti App Router versi 2, Server Actions, dan integrasi Edge Runtime yang lebih kuat. Tutorial ini menuntun Anda langkah demi langkah menginstal, mengonfigurasi, dan mengoptimalkan proyek Next.js 15 untuk produksi.
1. Prasyarat
Sebelum memulai, pastikan Anda memiliki:
- Node.js v20.10 atau lebih baru (unduh di nodejs.org)
- Git
- Editor kode, rekomendasi VS Code dengan ekstensi Next.js dan Tailwind CSS
2. Membuat Project Next.js 15
npx create-next-app@latest my-next15-app --experimental-app-router
Parameter --experimental-app-router mengaktifkan App Router v2 yang kini menjadi default pada Next.js 15. Pilih TypeScript saat diminta untuk mendapatkan tipe yang kuat.
3. Instalasi Dependensi Tambahan
Kami akan menambahkan Tailwind CSS untuk styling, dan next-auth untuk otentikasi berbasis JWT.
cd my-next15-app
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p
npm install next-auth@latest
Konfigurasi tailwind.config.js:
module.exports = {
content: ["./app/**/*.{js,ts,jsx,tsx}", "./pages/**/*.{js,ts,jsx,tsx}"],
theme: { extend: {} },
plugins: [],
};
Tambahkan import Tailwind di app/globals.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
4. Menyiapkan App Router (v2)
Struktur folder app/ menggantikan pages/. Buat layout dasar:
mkdir -p app/(main)/layout.tsx
Isi app/(main)/layout.tsx:
import './globals.css';
import type { ReactNode } from 'react';
export const metadata = {
title: 'Next.js 15 Demo',
description: 'Demo proyek dengan App Router v2',
};
export default function RootLayout({ children }: { children: ReactNode }) {
return (
{children}
);
}
Tambahkan halaman beranda:
mkdir -p app/(main)/page.tsx
export default function HomePage() {
return (
Welcome to Next.js 15
App Router v2 + Server Actions = 🚀
);
}
5. Memanfaatkan Server Actions
Server Actions memungkinkan Anda menulis fungsi server langsung di komponen UI tanpa API route terpisah. Pastikan "serverActions": true ada di next.config.js (default pada v15).
// next.config.js
module.exports = {
experimental: {
serverActions: true,
},
};
Contoh: Form komentar yang disimpan ke database (supabase digunakan pada contoh).
npm install @supabase/supabase-js
File app/(main)/components/CommentForm.tsx:
'use client';
import { useState, FormEvent } from 'react';
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
export default function CommentForm() {
const [text, setText] = useState('');
const [status, setStatus] = useState('idle');
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setStatus('loading');
// @ts-ignore – Server Action call
await addComment({ content: text });
setText('');
setStatus('success');
};
return (
);
}
// Server Action – hanya dijalankan di server
export async function addComment(data: { content: string }) {
'use server';
const { error } = await supabase.from('comments').insert({ content: data.content });
if (error) throw new Error(error.message);
}
Catatan: Pastikan variabel lingkungan NEXT_PUBLIC_SUPABASE_* didefinisikan di .env.local.
6. Konfigurasi Edge Runtime
Next.js 15 memungkinkan men-deploy fungsi API ke Edge Runtime untuk latency ultra‑rendah. Tambahkan file app/api/hello/route.ts:
export const runtime = 'edge'; // menandakan fungsi berjalan di Edge
export async function GET() {
return new Response(JSON.stringify({ message: 'Hello from Edge!' }), {
headers: { 'Content-Type': 'application/json' },
});
}
Uji secara lokal dengan npm run dev. Edge runtime tersedia di Vercel, Netlify Edge Functions, atau Cloudflare Workers (dengan adaptor).
7. Otentikasi dengan Next‑Auth (JWT + Edge)
Buat file app/api/auth/[...nextauth]/route.ts:
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export const runtime = 'edge';
const handler = NextAuth({
providers: [GoogleProvider({ clientId: process.env.GOOGLE_ID!, clientSecret: process.env.GOOGLE_SECRET! })],
session: { strategy: 'jwt' },
callbacks: {
async jwt({ token, account }) {
if (account) token.accessToken = account.access_token;
return token;
},
async session({ session, token }) {
session.accessToken = token.accessToken as string;
return session;
},
},
});
export { handler as GET, handler as POST };
Jangan lupa menambahkan GOOGLE_ID dan GOOGLE_SECRET di .env.local. Gunakan hook useSession di komponen client untuk menampilkan status login.
8. Optimasi Build & Deploy
- Incremental Static Regeneration (ISR): Tambahkan
revalidate: 60padafetchdi server components untuk refresh tiap menit. - Image Optimization: Gunakan
next/imagedenganloader: 'custom'jika CDN internal. - Bundle Analyzer:
npm install @next/bundle-analyzerlalu aktifkan dinext.config.jsuntuk memeriksa ukuran modul.
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// konfigurasi lain
});
Deploy ke Vercel (rekomendasi resmi) cukup dengan push ke repository GitHub. Vercel otomatis mendeteksi next.config.js dan menjalankan build dengan Edge Runtime.
9. Best Practice untuk Proyek Next.js 15
- Gunakan TypeScript secara konsisten – menghindari runtime errors.
- Isolasi Server / Client – tambahkan directive
'use client'hanya pada komponen yang memang membutuhkan browser API. - Cache Strategi – manfaatkan
Cache-Controlheader pada API Edge untuk data yang jarang berubah. - Security – aktifkan
Content‑Security‑Policymelaluinext-secure-headers, dan selalu gunakanhttpOnlycookies untuk JWT. - Testing – gunakan Jest + React Testing Library untuk unit, dan Playwright untuk end‑to‑end.
10. Menjalankan Proyek Secara Lokal
# Instal dependensi
npm install
# Jalankan server development
npm run dev
# Build untuk produksi
npm run build
# Preview build
npm start
Setelah build berhasil, buka http://localhost:3000 dan eksplorasi fitur App Router, Server Actions, serta endpoint Edge yang telah Anda buat.
Dengan mengikuti langkah‑langkah di atas, Anda kini memiliki proyek Next.js 15 yang modern, scalable, dan siap diproduksi. Memanfaatkan App Router v2, Server Actions, serta Edge Runtime memberikan kecepatan respons yang luar biasa, sementara integrasi Next‑Auth dan Supabase menjadikan aplikasi penuh fitur dengan effort minimal. Terapkan best practice yang disebutkan untuk menjaga kualitas kode, keamanan, dan performa dalam jangka panjang.
Tutorial lengkap setup Next.js 15 dengan App Router v2, Server Actions, Edge Runtime, dan Next‑Auth. Langkah demi langkah, contoh kode, dan best practice untuk pengembangan web modern.
Programming,Software Engineering,Web Development,Next.js 15,App Router,Server Actions,Edge Runtime
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar