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:
# 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-appInteractive Creation
After running the command, you'll have interactive options:
✔ 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 / YesStarting the Development Server
cd my-next-app
npm run devVisit 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 configurationCreating Your First Page
App Router Method (Recommended)
Create pages in the app directory:
// 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:
// 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
/* app/globals.css */
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
}CSS Modules
/* 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;
}// 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
// components/Header.tsx
export default function Header() {
return (
<header>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
)
}Using Components
// 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
Using the Link Component
// 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>
)
}Navigation Styles
/* 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
// 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.jpgEnvironment Variables
Creating Environment Files
# .env.local
DATABASE_URL=your_database_url
API_KEY=your_api_key
NEXT_PUBLIC_API_URL=https://api.example.comUsing Environment Variables
// Server-side usage
const dbUrl = process.env.DATABASE_URL
// Client-side usage (requires NEXT_PUBLIC_ prefix)
const apiUrl = process.env.NEXT_PUBLIC_API_URLBasic Data Fetching
Server Components (App Router)
// 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
'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
git init
git add .
git commit -m "Initial commit"
git remote add origin your-repo-url
git push -u origin main2. Connect Vercel
- Visit vercel.com
- Import Git repository
- Configure project settings
- Click deploy
3. Automatic Deployment
Every push to the main branch will automatically deploy.
Common Commands
# 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 --noEmitDevelopment Tips
1. Hot Reloading
Next.js supports hot reloading, automatically refreshing the page after code modifications.
2. Error Page
// 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
// app/loading.tsx
export default function Loading() {
return <div>Loading...</div>
}4. 404 Page
// 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:
- Pages and Routing - Deep dive into the routing system
- Component Development - Create reusable components
- Styling - Various styling solutions
- Data Fetching - Fetching and managing data
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.