Next.js Complete Guide Part 1: Introduction and Setup - Learn from Scratch
Complete beginner's guide to Next.js - Learn what Next.js is, why it's popular, and how to set up your first Next.js project from scratch with step-by-step instructions.
Welcome to the most comprehensive Next.js learning series! Whether you're a complete beginner or coming from other frameworks, this series will take you from zero to hero in Next.js development.
What is Next.js?
Next.js is a powerful React framework that makes building web applications easier and more efficient. Created by Vercel, it's become the go-to choice for developers who want to build fast, SEO-friendly, and scalable web applications.
Why Next.js is So Popular
1. Server-Side Rendering (SSR)
- Pages are rendered on the server before being sent to the browser
- Improves SEO and initial page load times
- Better performance for users with slower devices
2. Static Site Generation (SSG)
- Pre-builds pages at build time
- Lightning-fast loading speeds
- Perfect for blogs, marketing sites, and documentation
3. Built-in Optimizations
- Automatic code splitting
- Image optimization
- Font optimization
- Bundle analysis
4. Developer Experience
- Hot reloading during development
- TypeScript support out of the box
- Built-in CSS and Sass support
- API routes for backend functionality
5. Production Ready
- Automatic performance optimizations
- Built-in security features
- Easy deployment options
Next.js vs Other Frameworks
Next.js vs Create React App (CRA)
| Feature | Next.js | Create React App | |---------|---------|------------------| | Rendering | SSR, SSG, CSR | Client-side only | | Routing | File-based | React Router needed | | API Routes | Built-in | Separate backend needed | | SEO | Excellent | Limited | | Performance | Optimized | Manual optimization | | Bundle Size | Smaller | Larger |
Next.js vs Gatsby
| Feature | Next.js | Gatsby | |---------|---------|--------| | Rendering | SSR + SSG | SSG only | | Data Fetching | Flexible | GraphQL focused | | Learning Curve | Moderate | Steeper | | Build Times | Faster | Slower for large sites | | Dynamic Content | Excellent | Limited |
Prerequisites
Before we start, you should have basic knowledge of:
- HTML/CSS: Understanding of web markup and styling
- JavaScript ES6+: Arrow functions, destructuring, modules
- React Basics: Components, props, state, hooks
Don't worry if you're not an expert - we'll explain concepts as we go!
Setting Up Your Development Environment
Step 1: Install Node.js
Next.js requires Node.js version 14.6.0 or higher.
Check if you have Node.js:
node --version
npm --version
If you don't have Node.js:
- Visit nodejs.org
- Download the LTS version
- Follow the installation instructions for your operating system
Step 2: Choose Your Code Editor
Recommended: Visual Studio Code
- Free and powerful
- Excellent Next.js/React support
- Great extension ecosystem
Useful VS Code Extensions:
- ES7+ React/Redux/React-Native snippets
- Auto Rename Tag
- Bracket Pair Colorizer
- Prettier - Code formatter
- GitLens
Step 3: Create Your First Next.js Project
Method 1: Using create-next-app (Recommended)
# Create a new Next.js project
npx create-next-app@latest my-nextjs-app
# Navigate to the project directory
cd my-nextjs-app
# Start the development server
npm run dev
Method 2: With TypeScript
# Create with TypeScript support
npx create-next-app@latest my-nextjs-app --typescript
# Or with additional options
npx create-next-app@latest my-nextjs-app --typescript --tailwind --eslint
Method 3: Manual Setup (For Learning)
# Create project directory
mkdir my-nextjs-app
cd my-nextjs-app
# Initialize package.json
npm init -y
# Install Next.js, React, and React DOM
npm install next react react-dom
# Install TypeScript (optional)
npm install --save-dev typescript @types/react @types/node
Step 4: Understanding the Project Structure
After creating your project, you'll see this structure:
my-nextjs-app/
├── pages/
│ ├── api/
│ │ └── hello.js
│ ├── _app.js
│ └── index.js
├── public/
│ ├── favicon.ico
│ └── vercel.svg
├── styles/
│ ├── globals.css
│ └── Home.module.css
├── next.config.js
├── package.json
└── README.md
Key Directories Explained:
pages/ - The heart of Next.js
- Each file becomes a route automatically
index.js= homepage (/)about.js= about page (/about)api/= API endpoints
public/ - Static assets
- Images, icons, fonts
- Accessible at root URL (
/favicon.ico)
styles/ - CSS files
- Global styles and component-specific styles
Step 5: Understanding package.json Scripts
{
"scripts": {
"dev": "next dev", // Development server
"build": "next build", // Production build
"start": "next start", // Production server
"lint": "next lint" // Code linting
}
}
Script Usage:
npm run dev # Start development server (http://localhost:3000)
npm run build # Build for production
npm run start # Start production server
npm run lint # Check code quality
Your First Next.js Page
Let's examine the default homepage (pages/index.js):
import Head from 'next/head'
import styles from '../styles/Home.module.css'
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<p className={styles.description}>
Get started by editing{' '}
<code className={styles.code}>pages/index.js</code>
</p>
</main>
</div>
)
}
Key Concepts:
- Default Export: Every page must have a default export
- Head Component: For managing document head (title, meta tags)
- CSS Modules: Scoped CSS with
.module.cssfiles - JSX: Write HTML-like syntax in JavaScript
Creating Your First Custom Page
Let's create an "About" page:
Create pages/about.js:
import Head from 'next/head'
export default function About() {
return (
<div>
<Head>
<title>About Us - My Next.js App</title>
<meta name="description" content="Learn about our company" />
</Head>
<main>
<h1>About Us</h1>
<p>Welcome to our amazing Next.js application!</p>
<p>This page was automatically routed because it's in the pages directory.</p>
</main>
</div>
)
}
Access your page:
- Start dev server:
npm run dev - Visit:
http://localhost:3000/about
Development Server Features
When you run npm run dev, you get:
1. Hot Reloading
- Changes appear instantly without page refresh
- State is preserved during updates
2. Error Overlay
- Detailed error messages in the browser
- Stack traces and helpful suggestions
3. Fast Refresh
- Preserves component state during edits
- Only re-renders changed components
Next.js Configuration
The next.config.js file allows customization:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
images: {
domains: ['example.com'],
},
env: {
CUSTOM_KEY: 'my-value',
},
}
module.exports = nextConfig
Common Configuration Options:
reactStrictMode: Enables React's strict modeswcMinify: Uses SWC for faster minificationimages: Configure image optimizationenv: Environment variables
Common Beginner Mistakes to Avoid
1. Wrong File Placement
# ❌ Wrong - won't create a route
src/pages/about.js
# ✅ Correct - creates /about route
pages/about.js
2. Missing Default Export
// ❌ Wrong - no default export
export function About() {
return <div>About</div>
}
// ✅ Correct - default export
export default function About() {
return <div>About</div>
}
3. Incorrect Import Paths
// ❌ Wrong - relative path issues
import Component from '../../components/Component'
// ✅ Better - absolute imports (configure in jsconfig.json)
import Component from '@/components/Component'
What's Next?
Congratulations! You've successfully:
- ✅ Understood what Next.js is and why it's popular
- ✅ Set up your development environment
- ✅ Created your first Next.js project
- ✅ Learned about the project structure
- ✅ Created your first custom page
- ✅ Understood basic routing
In Part 2, we'll dive deep into:
- File-based routing system
- Dynamic routes with parameters
- Nested routes and layouts
- Navigation between pages
- Route groups and parallel routes
Practice Exercises
Before moving to Part 2, try these exercises:
-
Create a Contact Page
- Create
pages/contact.js - Add a contact form (just HTML for now)
- Include proper meta tags
- Create
-
Create a Services Page
- Create
pages/services.js - List some services with descriptions
- Style it with CSS modules
- Create
-
Experiment with Head Component
- Add different titles to each page
- Include meta descriptions
- Add Open Graph tags
-
Explore the Development Server
- Make changes and watch hot reloading
- Introduce an error and see the error overlay
- Check the browser's network tab
Helpful Resources
Need Help?
If you get stuck:
- Check the browser console for errors
- Read error messages carefully
- Restart the development server
- Clear browser cache
- Check file paths and naming
Ready for Part 2? In the next article, we'll explore Next.js routing in detail and build a multi-page application with navigation. The journey to Next.js mastery continues!
This is Part 1 of our comprehensive Next.js learning series. Follow along as we build real-world applications and master every aspect of Next.js development.