Next.js 14 menjadi standar emas untuk pengembangan aplikasi React modern. Tutorial ini memberi langkah demi langkah instalasi, konfigurasi, contoh kode, serta best practice untuk memaksimalkan performa dan keamanan di lingkungan produksi pada Juni 2026.
1. Prasyarat dan Persiapan Lingkungan
Pastikan sistem Anda memiliki:
- Node.js v20.10+ (LTS)
- npm v10+ atau yarn (v2+)
- Git untuk version control
- Editor kode (VS Code direkomendasikan)
Verifikasi instalasi dengan:
node -v
npm -v
2. Membuat Proyek Next.js 14 Baru
Jalankan perintah berikut untuk inisialisasi proyek dengan create-next-app yang sudah terintegrasi App Router secara default.
npx create-next-app@latest my-next14-app --typescript --eslint --tailwind
cd my-next14-app
Opsi --typescript menyiapkan TypeScript, --eslint menambahkan linting, dan --tailwind menginstal Tailwind CSS untuk styling cepat.
3. Struktur Direktori Baru (App Router)
Next.js 14 menggantikan pages dengan app directory. Struktur penting:
app/
layout.tsx // Root layout, shared UI
page.tsx // Halaman utama (/)
dashboard/
layout.tsx // Layout khusus dashboard
page.tsx // /dashboard
loading.tsx // Loading UI pada route segment
api/
hello/route.ts // API Route berbasis server component
4. Instalasi Dependensi Tambahan
Untuk fitur server components, data fetching, dan autentikasi, tambahkan paket berikut:
npm install next-auth @next-auth/prisma-adapter prisma
npm install @tanstack/react-query
npm install zod
Jika menggunakan database, inisialisasi Prisma:
npx prisma init --datasource-provider postgresql
# Edit schema.prisma, lalu jalankan migration
npx prisma migrate dev --name init
5. Konfigurasi next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
experimental: {
appDir: true, // aktifkan App Router
serverComponentsExternalPackages: ["@tanstack/react-query"],
},
images: {
remotePatterns: [{ hostname: "images.unsplash.com" }],
},
i18n: {
locales: ["en", "id"],
defaultLocale: "en",
},
};
module.exports = nextConfig;
6. Membuat Root Layout dengan Tailwind dan Provider
// app/layout.tsx import "./globals.css"; import { ReactNode } from "react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; const queryClient = new QueryClient(); export default function RootLayout({ children }: { children: ReactNode }) { return ({children} ); }
Layout ini menyediakan global CSS, Tailwind, dan React Query yang dapat dipakai di seluruh aplikasi.
7. Menambahkan Server Component untuk Data Fetching
Server Component memungkinkan fetch data langsung di komponen tanpa menambah bundle client.
// app/dashboard/page.tsx
import { Suspense } from "react";
import { getStats } from "@/services/stats";
export default async function DashboardPage() {
const stats = await getStats(); // fetch di server
return (
Dashboard
);
}
function StatCard({ title, value }: { title: string; value: string | number }) {
return (
{title}
{value}
);
}
8. Membuat API Route dengan Server Actions (Next.js 14)
// app/api/hello/route.ts
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Hello from Next.js 14!" });
}
export async function POST(request: Request) {
const { name } = await request.json();
return NextResponse.json({ greeting: `Hi, ${name}` });
}
API ini dapat dipanggil dari client component menggunakan fetch atau React Query.
9. Implementasi Autentikasi dengan NextAuth.js
// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
export const auth = NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
session({ session, user }) {
session.user.id = user.id;
return session;
},
},
});
export const GET = auth.handlers.get;
export const POST = auth.handlers.post;
Jangan lupa menambahkan variabel lingkungan di .env.local.
10. Optimasi Produksi
- Image Optimization: Gunakan
next/imagedengan loader default, atau aktifkan Remote Patterns untuk CDN eksternal. - Incremental Static Regeneration (ISR): Tambahkan
revalidatepada fetch function.export const revalidate = 60; // cache 1 menit - Middleware untuk Security Headers:
// middleware.ts import { NextResponse } from "next/server"; export function middleware(request) { const response = NextResponse.next(); response.headers.set("X-Content-Type-Options", "nosniff"); response.headers.set("X-Frame-Options", "DENY"); response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin"); return response; } - Bundle Analyzer: Tambahkan
next-bundle-analyzeruntuk memeriksa ukuran JavaScript.npm install @next/bundle-analyzer // next.config.js const withBundleAnalyzer = require("@next/bundle-analyzer")({ enabled: process.env.ANALYZE === "true", }); module.exports = withBundleAnalyzer(nextConfig);
11. CI/CD dengan GitHub Actions dan Vercel
File .github/workflows/deploy.yml:
name: Deploy to Vercel
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm run lint && npm run build
- name: Deploy to Vercel
uses: amondnet/vercel-action@v20
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
working-directory: .
alias-domains: my-next14-app.vercel.app
Pastikan token dan ID disimpan di secret repo.
12. Debugging dan Monitoring
- Gunakan
next devdenganLOG_LEVEL=debuguntuk log detail. - Integrasi Sentry:
npm install @sentry/nextjs // sentry.server.config.js & sentry.client.config.js - Performance profiling dengan Chrome DevTools → Performance tab, atau
next build --profile.
13. Best Practice Tambahan
- Folder alias via
jsconfig.jsonuntuk impor bersih. - TypeScript strict mode aktifkan semua flag (noImplicitAny, strictNullChecks).
- Code Splitting dengan dynamic import:
const Chart = dynamic(() => import('@/components/Chart'), { ssr: false }); - Security: Gunakan
helmetmelalui middleware, dan aktifkan CSP di Vercel.
14. Deploy ke Vercel
Setelah CI selesai, Vercel otomatis membuat preview dan production URL. Pastikan variabel environment (DATABASE_URL, NEXTAUTH_SECRET, dll) terisi di dashboard Vercel.
15. Verifikasi Produksi
Gunakan curl -I https://my-next14-app.vercel.app untuk memeriksa header keamanan, dan Lighthouse untuk audit performance, accessibility, dan SEO.
Next.js 14 dengan App Router dan Server Components memberikan fondasi kuat untuk aplikasi React yang cepat, aman, dan mudah di‑scale. Dengan mengikuti langkah‑langkah di atas—mulai dari instalasi, konfigurasi, contoh kode, hingga CI/CD—Anda dapat meluncurkan produk yang siap produksi dalam hitungan menit, sekaligus menjaga standar best practice dalam Programming, Software Engineering, dan Web Development.
Tutorial step-by-step setup Next.js 14 dengan App Router, Server Components, autentikasi NextAuth, CI/CD GitHub Actions, dan best practice production-ready di 2026.
Programming,Software Engineering,Web Development
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar