Lewati ke konten
Kembali ke Blog

Cara Setup Next.js Project dari Awal

Β· Β· 2 menit baca

Next.js adalah React framework populer untuk building full-stack web applications. Berikut panduan setup dari awal.

Prerequisites

Requirements

Needed:
- Node.js 18.17+
- npm/yarn/pnpm
- Code editor (VS Code)
- Terminal

Creating New Project

Using create-next-app

# Create new Next.js app
npx create-next-app@latest my-app

npx create-next-app@latest my-app --typescript --tailwind --eslint --app

Setup Prompts

Options yang ditanyakan:
βœ” Would you like to use TypeScript? Yes
βœ” Would you like to use ESLint? Yes
βœ” Would you like to use Tailwind CSS? Yes
βœ” Would you like to use `src/` directory? Yes
βœ” Would you like to use App Router? Yes
βœ” Would you like to customize the default import alias? No

Project Structure

App Router Structure

my-app/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ layout.tsx
β”‚   β”‚   β”œβ”€β”€ page.tsx
β”‚   β”‚   β”œβ”€β”€ globals.css
β”‚   β”‚   └── api/
β”‚   └── components/
β”œβ”€β”€ public/
β”œβ”€β”€ next.config.js
β”œβ”€β”€ package.json
β”œβ”€β”€ tailwind.config.js
└── tsconfig.json

Running Development Server

Start Dev Server

# Navigate to project
cd my-app

Run development server

npm run dev

Open http://localhost:3000

Creating Pages

Basic Page

// src/app/about/page.tsx
export default function AboutPage() {
  return (
    <main>
      <h1>About Us</h1>
      <p>Welcome to our website</p>
    </main>
  );
}

Dynamic Routes

// src/app/blog/[slug]/page.tsx
export default function BlogPost({ params }: { params: { slug: string } }) {
  return <h1>Post: {params.slug}</h1>;
}

Layout System

Root Layout

// src/app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="id">
      <body>{children}</body>
    </html>
  );
}

API Routes

Creating API Endpoint

// src/app/api/hello/route.ts
import { NextResponse } from "next/server";

export async function GET() { return NextResponse.json({ message: "Hello World" }); }

Building for Production

Build Command

# Build production version
npm run build

Start production server

npm start

Kesimpulan

Next.js menyediakan developer experience yang excellent dengan fitur seperti file-based routing, API routes, dan optimizations built-in.

Ditulis oleh

Hendra Wijaya

Tinggalkan Komentar

Email tidak akan ditampilkan.