Next.js 14 terus mendominasi ekosistem React dengan App Router, Server Actions, dan streaming SSR. Tutorial ini memberi langkah demi langkah instalasi, konfigurasi, contoh kode, serta best practice untuk membangun aplikasi web modern yang siap produksi.
1. Prasyarat
Pastikan Anda memiliki:
- Node.js v20.10 atau lebih baru (
node -v) - npm v10 atau Yarn v4
- Git untuk version control
- Akun GitHub (untuk deployment ke Vercel atau Railway)
2. Membuat Proyek Next.js 14 Baru
npx create-next-app@latest my-next14-app --tsx --eslint --app
cd my-next14-app
Perintah di atas membuat proyek dengan:
- TypeScript (
--tsx) - Linting ESLint standar
- Struktur
app/(App Router) otomatis
3. Instalasi Dependensi Tambahan
# Styling (Tailwind CSS 3.4 terbaru)
npm i -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p
# Prisma ORM untuk database (PostgreSQL)
npm i prisma@5.12 @prisma/client@5.12
npx prisma init --datasource-provider postgresql
# UI component library (shadcn/ui) – kompatibel dengan Server Actions
npx shadcn-ui@latest init
Konfigurasikan tailwind.config.js agar mendukung app/:
module.exports = {
content: [
"./src/**/*.{js,ts,jsx,tsx}",
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
};
4. Konfigurasi Database dengan Prisma
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())
}
Set environment variable di .env:
DATABASE_URL="postgresql://user:password@localhost:5432/next14_demo"
Run migration:
npx prisma migrate dev --name init
5. Membuat Server Action untuk Menyimpan Post
Server Actions memungkinkan fungsi async dijalankan di server langsung dari komponen React tanpa API route terpisah.
// app/actions.ts
import { prisma } from "@/lib/prisma";
export async function createPost(title: string, content?: string) {
"use server"; // tells Next.js this runs on server
return await prisma.post.create({
data: { title, content },
});
}
Import di komponen:
// app/create-post/page.tsx
"use client";
import { useState, FormEvent } from "react";
import { createPost } from "../actions";
export default function CreatePost() {
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setLoading(true);
try {
await createPost(title, content);
alert("Post berhasil disimpan!");
} catch (err) {
console.error(err);
alert("Gagal menyimpan post.");
} finally {
setLoading(false);
}
}
return (
);
}
Catatan: "use client" diperlukan pada komponen UI, sedangkan "use server" pada aksi.
6. Implementasi Streaming SSR dengan fetch di Server Component
// app/posts/page.tsx
import { prisma } from "@/lib/prisma";
export const revalidate = 60; // ISR setiap 60 detik
export default async function PostsPage() {
const posts = await prisma.post.findMany({
orderBy: { createdAt: "desc" },
take: 10,
});
return (
Latest Posts
{posts.map((p) => (
{p.title}
{p.content && {p.content}
}
))}
);
}
Karena file berada di app/, komponen ini secara otomatis menjadi Server Component yang di‑stream ke browser, memberi First‑Contentful Paint yang lebih cepat.
7. Pengaturan Linting & Prettier (Best Practice)
# .eslintrc.json
{
"extends": ["next/core-web-vitals", "plugin:prettier/recommended"],
"rules": {
"@next/next/no-img-element": "off",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}
# .prettierrc
{
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 100
}
Tambahkan script di package.json:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint && prettier --check .",
"format": "prettier --write ."
}
8. CI/CD dengan GitHub Actions & Vercel
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
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
- run: npm run test # jika ada Jest
- run: npm run build
- 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 }}
working-directory: .
Pastikan secret Vercel sudah di‑set di repo Settings → Secrets.
9. Optimasi Produksi
- Image Optimization: Gunakan
<Image>darinext/imagedengan loader default Vercel. - Cache Header: Tambahkan
Cache-Controldinext.config.jsuntuk static assets.module.exports = { compress: true, images: { remotePatterns: [{ hostname: "images.unsplash.com" }], }, headers: async () => [{ source: "/:all*(js|css|png|jpg|svg)", headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }], }]], }; - Security: Aktifkan
Content-Security-Policy,Strict-Transport-Security, dan disableX-Powered-Bymelaluiheadersdi Next.js.
10. Deploy ke Vercel (Langkah Akhir)
- Login ke Vercel, klik New Project.
- Hubungkan repository GitHub.
- Pastikan
Framework Presetterdeteksi sebagai Next.js. - Tambah environment variable
DATABASE_URLdi Settings → Environment Variables. - Deploy! Vercel akan otomatis menjalankan
npm run builddan menyiapkan preview URL.
Setelah deploy, Anda dapat memanfaatkan fitur Edge Functions untuk menambahkan middleware custom, misalnya logging request ID.
11. Studi Kasus: Blog Multi‑Author dengan Incremental Static Regeneration
Dengan ISR, setiap artikel ditulis oleh author berbeda dapat di‑generate secara statis pada permintaan pertama, lalu di‑revalidate tiap 5 menit. Implementasinya hanya menambahkan export const revalidate = 300; pada page app/posts/[id]/page.tsx. Hasilnya: latency < 100 ms pada first load, SEO‑friendly HTML, dan beban server minimal.
12. Troubleshooting Umum
- "use server" tidak dikenali: Pastikan Anda memakai Next.js 14.x dan file berada di
app/. - Prisma migration gagal: Periksa
DATABASE_URL, pastikan PostgreSQL versi 15+ berjalan. - CSS tidak ter‑apply: Pastikan
tailwind.config.jsmencakupapp/**/*.{js,ts,jsx,tsx}. - Vercel build timeout: Optimalkan ukuran
.nextdengannext-purgecssatau setoutput: 'standalone'untuk Docker builds.
13. Ringkasan Langkah
- Install Next.js 14 dengan
create-next-app(App Router). - Tambahkan Tailwind, Prisma, dan shadcn/ui.
- Konfigurasi database PostgreSQL melalui Prisma.
- Buat Server Action
createPostdan UI client. - Gunakan Server Component untuk streaming SSR.
- Atur linting, formatting, dan CI/CD GitHub Actions.
- Optimasi produksi (image, cache, security).
- Deploy ke Vercel dengan environment variables.
Next.js 14 menawarkan kombinasi App Router, Server Actions, dan streaming SSR yang menyederhanakan arsitektur full‑stack JavaScript. Dengan mengikuti tutorial ini—mulai dari setup lokal, integrasi Prisma, hingga CI/CD otomatis—Anda dapat mengirimkan aplikasi web modern yang cepat, aman, dan mudah dikelola. Terapkan best practice linting, caching, dan keamanan untuk memastikan kode tetap bersih dan siap skala di lingkungan produksi.
Tutorial lengkap Next.js 14 tahun 2026: setup App Router, Server Actions, TypeScript, Prisma, Tailwind, CI/CD, dan deployment ke Vercel. Panduan step‑by‑step dengan contoh kode dan best practice.
Programming,Software Engineering,Web Development,Next.js,React,Server Actions,TypeScript,Prisma,CI/CD
#Programming #SoftwareEngineering #WebDev #Tech #Coding
0 Komentar