Next.js Introduction
Welcome to the world of Next.js! In this introduction, we'll explore what Next.js is, why it's valuable, and how to get started with this powerful React framework.
What is Next.js?
Next.js is a React framework created by Vercel that enables functionality such as server-side rendering, static site generation, and API routes. It provides a robust structure for building modern web applications with React while adding many features that make development more efficient and user experiences better.
Think of Next.js as React with superpowers - it takes what's good about React and adds key features that help you build production-ready applications more easily.
Why Use Next.js?
Next.js solves many common challenges in React development:
- Server-Side Rendering (SSR) - Improves SEO and initial page load performance
- Static Site Generation (SSG) - Pre-renders pages at build time for maximum performance
- File-based Routing - Simplifies navigation with an intuitive file system approach
- Built-in API Routes - Create backend API endpoints within your frontend project
- Automatic Code Splitting - Loads only necessary JavaScript for each page
- Built-in CSS and Sass Support - Streamlines styling your application
- Development Environment - Fast refresh and helpful error reporting
Setting Up Your First Next.js Project
Let's create your first Next.js application. You'll need Node.js installed on your computer (version 12.22.0 or later).
Creating a New Project
You can create a new project using the following command:
npx create-next-app my-first-nextjs-app
This command will set up a new Next.js project with the default template. You'll be prompted with several configuration 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 / Yes
For beginners, you can select the default options (often "Yes" for most options).
Project Structure
After setup completes, you'll see a folder structure like this:
my-first-nextjs-app/
├── node_modules/
├── public/
├── app/ (or pages/ depending on your router choice)
├── .eslintrc.json
├── next.config.js
├── package.json
├── README.md
└── package-lock.json
Let's understand the key directories:
public/
- Static files like images, fonts, and other assetsapp/
(orpages/
) - Your application pages and routesnext.config.js
- Configuration file for Next.js
Running Your Application
Navigate to your project directory and start the development server:
cd my-first-nextjs-app
npm run dev
Your application will be running at http://localhost:3000
. Open this URL in your browser to see your new Next.js app!
Understanding Next.js Pages
In Next.js, pages are React components exported from files in the pages
directory (or app
directory if using the App Router).
With Pages Router (Traditional)
Create a file at pages/hello.js
:
export default function Hello() {
return (
<div>
<h1>Hello, Next.js!</h1>
<p>This is my first Next.js page</p>
</div>
);
}
Navigate to http://localhost:3000/hello
to see your new page.
With App Router (Newer Approach)
If you chose the App Router, create a file at app/hello/page.js
:
export default function Hello() {
return (
<div>
<h1>Hello, Next.js!</h1>
<p>This is my first Next.js page using App Router</p>
</div>
);
}
Navigate to http://localhost:3000/hello
to see your new page.
Built-in Features Demo
1. Data Fetching
Next.js provides various ways to fetch data. Here's an example using the Pages Router with getStaticProps
:
// pages/users.js
export default function Users({ users }) {
return (
<div>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
// This runs at build time in production
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await res.json();
return {
props: { users },
};
}
With App Router, the approach is different:
// app/users/page.js
async function getUsers() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
return res.json();
}
export default async function Users() {
const users = await getUsers();
return (
<div>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
2. API Routes
Next.js allows you to create API endpoints within your project:
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js!' });
}
You can access this API at http://localhost:3000/api/hello
.
Real-World Application: Building a Blog
Let's see how Next.js can be used to build something practical like a simple blog homepage:
// pages/index.js (Pages Router)
import Link from 'next/link';
import Head from 'next/head';
export default function Home({ posts }) {
return (
<div className="container">
<Head>
<title>My Next.js Blog</title>
<meta name="description" content="A blog built with Next.js" />
</Head>
<main>
<h1>Welcome to My Blog</h1>
<div className="posts">
{posts.map(post => (
<div key={post.id} className="post-card">
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
<Link href={`/posts/${post.slug}`}>
Read more →
</Link>
</div>
))}
</div>
</main>
<style jsx>{`
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.posts {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
margin-top: 20px;
}
.post-card {
border: 1px solid #eaeaea;
border-radius: 10px;
padding: 20px;
}
`}</style>
</div>
);
}
// This function gets called at build time
export async function getStaticProps() {
// In a real app, you might fetch from an API or database
const posts = [
{
id: 1,
title: "Getting Started with Next.js",
slug: "getting-started-with-nextjs",
excerpt: "Learn the basics of Next.js and how to create your first app."
},
{
id: 2,
title: "Mastering Next.js Routing",
slug: "mastering-nextjs-routing",
excerpt: "Understand the powerful routing capabilities in Next.js."
}
];
return {
props: { posts }
};
}
This example demonstrates several Next.js features:
- Static generation with data using
getStaticProps
- The
Link
component for client-side navigation - The
Head
component for managing document head - CSS-in-JS using
style jsx
Next.js vs. Plain React
To understand why Next.js is valuable, let's compare it with a plain React application:
Feature | Plain React | Next.js |
---|---|---|
Routing | Requires React Router or similar | Built-in file-based routing |
SSR/SSG | Requires complex setup | Built-in, easy configuration |
API routes | Separate backend needed | Built-in API routes |
Code splitting | Manual configuration | Automatic per-page |
Image optimization | Manual implementation | Built-in Image component |
Development experience | Basic hot reloading | Fast refresh, better error handling |
Summary
Next.js extends React with powerful features like server-side rendering, static site generation, API routes, and simplified routing. It provides a well-structured framework that makes building complex React applications more straightforward.
By leveraging Next.js, you can:
- Improve your site's performance and SEO
- Simplify your application's architecture
- Speed up the development process
- Create full-stack applications in a single project
Additional Resources
- Official Next.js Documentation
- Next.js GitHub Repository
- Vercel Platform (created by the same team as Next.js)
Exercises
-
Basic Page Creation: Create a Next.js application with three pages - Home, About, and Contact.
-
Data Fetching: Modify the Users example to fetch data from a different API and display it with styling.
-
Blog Enhancement: Extend the blog example by creating individual blog post pages using dynamic routes.
-
API Practice: Create a Next.js API route that returns the current date and time, then display it on a page.
-
Navigation: Build a navigation bar component that shows which page is currently active.
Now that you've been introduced to Next.js, you're ready to start building modern, efficient web applications. In the following lessons, we'll dive deeper into each feature and explore advanced patterns.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)