Next.js 14 menjadi standar de‑facto untuk pengembangan aplikasi React modern. Tutorial ini mengajarkan cara menginstal, mengonfigurasi, menulis kode, dan menerapkan best practice agar aplikasi siap produksi di 2026.
1. Prasyarat & Persiapan Lingkungan
Sebelum memulai, pastikan Anda memiliki:
- Node.js v20.10 atau lebih baru (unduh di nodejs.org)
- npm v10 atau Yarn v4 (pilih salah satu)
- Git untuk version control
- Editor kode modern, misalnya VS Code dengan ekstensi ESLint dan Prettier
Jika menggunakan Docker, pastikan Docker Desktop versi 4.30+ ter‑install.
2. Membuat Project Next.js 14 Baru
npx create-next-app@latest my-next14-app --example "https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss" --typescript
cd my-next14-app
Perintah di atas membuat aplikasi starter dengan TypeScript, Tailwind CSS, dan konfigurasi linting standar.
3. Mengaktifkan App Router
Next.js 14 mempromosikan App Router sebagai default. Pastikan struktur folder app/ ada di root proyek. Jika masih ada pages/, Anda dapat menonaktifkannya dengan menambah file next.config.js berikut:
module.exports = {
// Memaksa penggunaan app router
experimental: { appDir: true },
reactStrictMode: true,
images: { remotePatterns: [{ protocol: 'https', hostname: '**' }] },
};
Setelah itu, hapus atau rename folder pages menjadi pages_old untuk menghindari konflik.
4. Menyiapkan Server Actions (Beta Stabil)
Server Actions memungkinkan Anda menulis fungsi yang dijalankan di server langsung dari komponen React, tanpa API route terpisah.
// app/api/actions.ts
'use server';
import { prisma } from '@/lib/prisma';
export async function createPost(data: { title: string; content: string }) {
'use server';
const post = await prisma.post.create({ data });
return post;
}
Import fungsi ini di komponen client:
// app/dashboard/page.tsx
'use client';
import { useState } from 'react';
import { createPost } from '@/app/api/actions';
export default function Dashboard() {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const post = await createPost({ title, content });
alert(`Post created: ${post.id}`);
};
return (
);
}
Catatan: Server Actions memanfaatkan Edge Runtime bila Anda men-deploy ke Vercel/Netlify dengan konfigurasi runtime: 'edge'.
5. Konfigurasi Prisma (ORM) untuk PostgreSQL
# Install dependencies
npm install prisma @prisma/client
# Initialise prisma schema
npx prisma init --datasource-provider postgresql
Ubah prisma/schema.prisma:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Post {
id Int @id @default(autoincrement())
title String
content String
createdAt DateTime @default(now())
}
Jalankan migrasi:
npx prisma migrate dev --name init
Pastikan variabel DATABASE_URL di .env.local terisi, contohnya:
DATABASE_URL="postgresql://user:password@localhost:5432/next14_demo"
6. Menambahkan Middleware untuk Security
Gunakan middleware Next.js untuk menambahkan HTTP security headers dan proteksi CSRF.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Content Security Policy (CSP) yang aman untuk SPA
response.headers.set('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com");
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;
}
export const config = {
matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)',
};
7. Optimasi Gambar & Font dengan Next/Image dan Next/Font
Next.js 14 menambahkan next/font yang otomatis mengoptimasi loading font.
// app/layout.tsx
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' });
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
Untuk gambar, gunakan next/image dengan ukuran responsif dan lazy‑loading:
import Image from 'next/image';
8. Menyiapkan CI/CD dengan GitHub Actions & Docker
Berikut contoh workflow yang membangun image Docker, menjalankan lint, test, dan deploy ke Vercel.
# .github/workflows/ci.yml
name: CI & CD
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Lint & TypeCheck
run: npm run lint && npm run type-check
- name: Run tests
run: npm test -- --coverage
- name: Build Docker image
run: |
docker build -t ghcr.io/${{ github.repository }}:${{ github.sha }} .
echo ${{ secrets.GITHUB_TOKEN }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin
docker push ghcr.io/${{ github.repository }}:${{ github.sha }}
- name: Deploy to Vercel
if: github.ref == 'refs/heads/main'
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 }}
github-token: ${{ secrets.GITHUB_TOKEN }}
Workflow ini memastikan setiap commit ter‑uji, dibangun, dan otomatis ter‑deploy bila berada di branch main.
9. Monitoring & Error Tracking
Integrasikan Sentry untuk capture error runtime:
# Install SDK
npm install @sentry/nextjs
# Initialise (sentry.server.config.ts & sentry.client.config.ts)
import * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
tracesSampleRate: 0.2,
});
Set environment variable di Vercel dashboard.
10. Best Practice untuk Produksi
- Static Generation (SSG) vs Server‑Side Rendering (SSR): Gunakan
generateStaticParamsbila data tidak berubah tiap request. - Cache-Control: Manfaatkan
revalidatepadafetchuntuk ISR (Incremental Static Regeneration). - Code Splitting: Biarkan Next melakukan automatic chunking, tetapi hindari import modul berat di komponen client.
- Environment Isolation: Simpan secret di
.env.productiondan gunakanvercel envuntuk manajemen. - Performance Audits: Jalankan
next build && next export && lighthouseuntuk mengidentifikasi bottleneck.
11. Deploy ke Vercel (One‑Click)
- Push repository ke GitHub.
- Buka vercel.com, klik New Project dan pilih repo.
- Pastikan framework terdeteksi sebagai
Next.jsdan variabelDATABASE_URLsertaNEXT_PUBLIC_SENTRY_DSNditambahkan. - Deploy! Vercel otomatis membuat preview URL untuk setiap PR.
12. Testing End‑to‑End dengan Playwright
# Install Playwright
npm i -D @playwright/test
# contoh test
import { test, expect } from '@playwright/test';
test('homepage renders hero image', async ({ page }) => {
await page.goto('/');
const hero = page.locator('img[alt="Hero"]');
await expect(hero).toBeVisible();
});
Tambahkan script "test:e2e": "playwright test" ke package.json dan jalankan di CI.
13. Scaling dengan Edge Runtime & Vercel Edge Functions
Jika aplikasi memerlukan latensi ultra‑rendah, pindahkan fungsi berat ke edge:
// app/api/edge/hello/route.ts
export const runtime = 'edge';
export async function GET() {
return new Response('Hello from Edge!', { status: 200 });
}
Edge runtime otomatis ter‑scale di jaringan Vercel Edge Network.
14. Ringkasan Step‑by‑Step
- Instal Node.js & buat project dengan
create-next-app. - Aktifkan App Router lewat
next.config.js. - Implementasikan Server Actions untuk operasi CRUD.
- Konfigurasi Prisma + PostgreSQL, jalankan migrasi.
- Tambahkan middleware security headers.
- Optimasi font & gambar menggunakan
next/fontdannext/image. - Siapkan CI/CD dengan GitHub Actions + Docker.
- Integrasikan Sentry untuk error tracking.
- Ikuti best practice produksi (ISR, caching, code splitting).
- Deploy ke Vercel, gunakan preview builds.
- Uji dengan Playwright dan pantau performa lewat Lighthouse.
- Jika diperlukan, migrasikan fungsi ke Edge Runtime.
Dengan mengikuti tutorial ini, Anda akan memiliki aplikasi Next.js 14 yang memanfaatkan App Router, Server Actions, dan Prisma di backend, sekaligus dilengkapi dengan keamanan, CI/CD otomatis, monitoring, dan kemampuan skala edge. Kombinasi ini menjawab tantangan modern dalam Programming, Software Engineering, dan Web Development pada tahun 2026, memberikan fondasi kuat untuk proyek komersial atau produk SaaS yang siap performa tinggi.
Tutorial step‑by‑step Next.js 14 dengan App Router, Server Actions, Prisma, CI/CD, dan best practice untuk produksi modern. Cocok untuk Programming, Software Engineering, dan Web Development 2026.
Programming,Software Engineering,Web Development,Next.js 14,App Router,Server Actions,CI/CD,Docker,Prisma
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar