Panduan komprehensif untuk setup Next.js dengan template, dari download hingga production deployment.
node --version
npm --version
git --version
# Create project baru
npx create-next-app@latest my-nextjs-app
# Pilih opsi saat install:
# ✔ Would you like to use TypeScript? › No / Yes
# ✔ Would you like to use ESLint? › Yes / No
# ✔ Would you like to use Tailwind CSS? › Yes / No
# ✔ Would you like to use `src/` directory? › Yes / No
# ✔ Would you like to use App Router? › Yes / No
# ✔ Would you like to customize the import alias? › No / Yes
# Masuk folder
cd my-nextjs-app
# Jalankan development server
npm run dev
1. Envato Elements / ThemeForest
2. Vercel Templates
**3. Creative Tim Next.js
4. UI Framework Templates
# Extract template
unzip template-nextjs.zip
cd template-nextjs
# Lihat package.json
cat package.json
# Dengan npm
npm install
# Atau dengan yarn
yarn install
# Atau dengan pnpm
pnpm install
Troubleshoot Installation:
# Jika ada conflict
npm install --legacy-peer-deps
# Clear cache jika perlu
npm cache clean --force
rm -rf node_modules package-lock.json
npm install
# Buat .env.local (Next.js file untuk environment variables)
cp .env.example .env.local
# atau
touch .env.local
Contoh .env.local:
NEXT_PUBLIC_API_URL=http://localhost:3000
NEXT_PUBLIC_APP_NAME=My App
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
API_SECRET_KEY=your_secret_key_here
Catatan:
NEXT_PUBLIC_ = accessible di client-sideEdit next.config.js jika diperlukan:
/** @type {import('next').NextConfig} */
const nextConfig = {
// Image optimization
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
},
],
},
// Redirect & Rewrite
async redirects() {
return [
{
source: '/about-us',
destination: '/about',
permanent: true,
},
]
},
// Headers
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Origin', value: '*' },
],
},
]
},
}
module.exports = nextConfig
app/
├── layout.jsx # Root layout
├── page.jsx # Home page (/)
├── globals.css # Global styles
├── api/
│ ├── route.js # API endpoint
│ └── products/
│ └── route.js # GET /api/products
├── dashboard/
│ ├── layout.jsx # Dashboard layout
│ └── page.jsx # /dashboard page
├── blog/
│ ├── [slug]/
│ │ └── page.jsx # Dynamic route /blog/[slug]
│ └── page.jsx # /blog
└── (auth)/
├── login/
│ └── page.jsx
└── register/
└── page.jsx
public/
├── logo.png
└── images/
components/
├── Header.jsx
├── Footer.jsx
├── Navigation.jsx
└── common/
└── Button.jsx
lib/
├── db.js
├── auth.js
└── utils.js
styles/
├── globals.css
└── variables.css
.env.local # Local environment variables
.env.production # Production environment
next.config.js # Next.js configuration
tsconfig.json # TypeScript config (jika TS)
package.json
npm run dev
# Aplikasi berjalan di http://localhost:3000
# Build for production
npm run build
# Start production server
npm run start
# Check lint
npm run lint
# Format code
npm run format
npm install @prisma/client
npm install -D prisma
# Initialize Prisma
npx prisma init
Edit prisma/schema.prisma:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
author User @relation(fields: [authorId], references: [id])
authorId Int
}
# Push schema ke database
npx prisma migrate dev --name init
npm install next-auth
npx auth secret
app/api/auth/[...nextauth]/route.js:
import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
export const authOptions = {
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
}
export const handler = NextAuth(authOptions)
export { handler as GET, handler as POST }
import Image from 'next/image'
export default function Home() {
return (
<Image
src="/hero.jpg"
alt="Hero"
width={1200}
height={600}
priority
/>
)
}
app/api/posts/route.js:
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ posts: [] })
}
export async function POST(request) {
const data = await request.json()
// Handle POST
return NextResponse.json({ created: true }, { status: 201 })
}
'use server'
export async function addPost(formData) {
const title = formData.get('title')
const content = formData.get('content')
// Save to database
return { success: true }
}
// next.config.js
images: {
formats: ['image/avif', 'image/webp'],
minimumCacheTTL: 60,
}
import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(
() => import('./HeavyComponent'),
{ loading: () => <p>Loading...</p> }
)
export const metadata = {
title: 'Home Page',
description: 'Welcome to my Next.js app',
openGraph: {
title: 'Home Page',
description: 'Welcome to my Next.js app',
url: 'https://example.com',
type: 'website',
},
}
export default function Home() {
return <h1>Welcome</h1>
}
# Install Vercel CLI
npm i -g vercel
# Deploy
vercel
# Set environment variables
vercel env add DATABASE_URL
vercel env add API_SECRET_KEY
npm run build
# Upload folder `.next` dan `public` ke Netlify
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
# Build
npm run build
# Upload dengan SCP atau Git
scp -r .next/ username@server:/var/www/nextjs/
# Di server, run dengan PM2
pm2 start "npm start" --name nextjs-app
rm -rf .next node_modules
npm install
npm run build
# Ganti port
PORT=3001 npm run dev
# Jika menggunakan TypeScript
npm install -D typescript @types/node @types/react
# Generate tsconfig
npx tsc --init
# Verify connection string di .env.local
DATABASE_URL="postgresql://user:password@localhost:5432/dbname"
# Test connection
npx prisma db push
✅ Gunakan:
❌ Hindari:
.env.local file sudah setupnpm run build berjalan suksesDokumentasi Resmi: nextjs.org