Skip to content

Next.js Quick Start

This chapter will guide you through quickly creating your first Next.js application, understanding basic concepts and development workflow.

Creating Your First Next.js Application

Using create-next-app

The simplest way is to use the official scaffolding tool:

bash
# Using npm
npx create-next-app@latest my-next-app

# Using yarn
yarn create next-app my-next-app

# Using pnpm
pnpm create next-app my-next-app

Interactive Creation

After running the command, you'll have interactive options:

bash
 Would you like to use TypeScript? No / Yes
 Would you like to use ESLint? No / Yes
 Would you like to use Tailwind CSS? No / Yes
 Would you like to use `src/` directory? No / Yes
 Would you like to use App Router? (recommended) … No / Yes
 Would you like to customize the default import alias (@/*)? … No / Yes

Starting the Development Server

bash
cd my-next-app
npm run dev

Visit http://localhost:3000 to view your application.

Project Structure Overview

my-next-app/
├── app/                 # App Router (Next.js 13+)
│   ├── globals.css     # Global styles
│   ├── layout.tsx      # Root layout
│   └── page.tsx        # Homepage
├── public/             # Static assets
├── next.config.js      # Next.js configuration
├── package.json        # Project dependencies
└── tailwind.config.js  # Tailwind configuration

Creating Your First Page

Create pages in the app directory:

typescript
// app/about/page.tsx
export default function About() {
  return (
    <div>
      <h1>About Us</h1>
      <p>This is the about page</p>
    </div>
  )
}

Pages Router Method

Create pages in the pages directory:

typescript
// pages/about.tsx
export default function About() {
  return (
    <div>
      <h1>About Us</h1>
      <p>This is the about page</p>
    </div>
  )
}

Adding Styles

Global Styles

css
/* app/globals.css */
body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  margin: 0;
  padding: 20px;
}

h1 {
  color: #333;
}

CSS Modules

css
/* components/Button.module.css */
.button {
  background-color: #0070f3;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.button:hover {
  background-color: #0051cc;
}
typescript
// components/Button.tsx
import styles from './Button.module.css'

export default function Button({ children }: { children: React.ReactNode }) {
  return (
    <button className={styles.button}>
      {children}
    </button>
  )
}

Creating Components

Simple Component

typescript
// components/Header.tsx
export default function Header() {
  return (
    <header>
      <nav>
        <a href="/">Home</a>
        <a href="/about">About</a>
      </nav>
    </header>
  )
}

Using Components

typescript
// app/layout.tsx
import Header from '@/components/Header'
import './globals.css'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        <Header />
        <main>{children}</main>
      </body>
    </html>
  )
}

Adding Navigation

typescript
// components/Navigation.tsx
import Link from 'next/link'

export default function Navigation() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/contact">Contact</Link>
    </nav>
  )
}
css
/* components/Navigation.module.css */
.nav {
  display: flex;
  gap: 20px;
  padding: 20px 0;
}

.link {
  text-decoration: none;
  color: #0070f3;
  font-weight: 500;
}

.link:hover {
  text-decoration: underline;
}

Handling Static Assets

Images

typescript
// app/page.tsx
import Image from 'next/image'

export default function Home() {
  return (
    <div>
      <h1>Welcome to Next.js</h1>
      <Image
        src="/logo.png"
        alt="Logo"
        width={200}
        height={100}
      />
    </div>
  )
}

Public Files

Place files in the public directory:

public/
├── favicon.ico
├── logo.png
└── images/
    └── hero.jpg

Environment Variables

Creating Environment Files

bash
# .env.local
DATABASE_URL=your_database_url
API_KEY=your_api_key
NEXT_PUBLIC_API_URL=https://api.example.com

Using Environment Variables

typescript
// Server-side usage
const dbUrl = process.env.DATABASE_URL

// Client-side usage (requires NEXT_PUBLIC_ prefix)
const apiUrl = process.env.NEXT_PUBLIC_API_URL

Basic Data Fetching

Server Components (App Router)

typescript
// app/posts/page.tsx
async function getPosts() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts')
  return res.json()
}

export default async function Posts() {
  const posts = await getPosts()

  return (
    <div>
      <h1>Post List</h1>
      {posts.map((post: any) => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </article>
      ))}
    </div>
  )
}

Client-Side Data Fetching

typescript
'use client'

import { useState, useEffect } from 'react'

export default function ClientPosts() {
  const [posts, setPosts] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(res => res.json())
      .then(data => {
        setPosts(data)
        setLoading(false)
      })
  }, [])

  if (loading) return <div>Loading...</div>

  return (
    <div>
      <h1>Post List</h1>
      {posts.map((post: any) => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </article>
      ))}
    </div>
  )
}

Deploying to Vercel

1. Push to Git

bash
git init
git add .
git commit -m "Initial commit"
git remote add origin your-repo-url
git push -u origin main

2. Connect Vercel

  1. Visit vercel.com
  2. Import Git repository
  3. Configure project settings
  4. Click deploy

3. Automatic Deployment

Every push to the main branch will automatically deploy.

Common Commands

bash
# Development mode
npm run dev

# Build production version
npm run build

# Start production server
npm run start

# Code linting
npm run lint

# Type checking (TypeScript)
npx tsc --noEmit

Development Tips

1. Hot Reloading

Next.js supports hot reloading, automatically refreshing the page after code modifications.

2. Error Page

typescript
// app/error.tsx
'use client'

export default function Error({
  error,
  reset,
}: {
  error: Error
  reset: () => void
}) {
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  )
}

3. Loading Page

typescript
// app/loading.tsx
export default function Loading() {
  return <div>Loading...</div>
}

4. 404 Page

typescript
// app/not-found.tsx
export default function NotFound() {
  return (
    <div>
      <h2>Page Not Found</h2>
      <p>Please check if the URL is correct</p>
    </div>
  )
}

Next Steps

Now that you've created your first Next.js application! You can continue learning:

Summary

Through this chapter, you should be able to:

  • Create a Next.js project
  • Understand basic project structure
  • Create pages and components
  • Add styles and navigation
  • Handle static assets
  • Perform basic data fetching
  • Deploy applications to Vercel

Next.js provides powerful features and an excellent developer experience, making it an excellent choice for building modern React applications.

Content is for learning and research only.