Topic01 / 47
Introduction to Next.js
What & Why
Next.js is a React framework that adds server-side rendering (SSR), static site generation (SSG), file-based routing, API routes, and image optimization out of the box. It turns React into a full-stack framework — the industry standard for production React apps.
Syntax
tsx
1// App Router (Next.js 13+ — modern standard)
2// File: src/app/page.tsx — maps to /
3export default function HomePage() {
4 return <h1>Welcome to DevNotes</h1>;
5}
6
7// File: src/app/blog/[slug]/page.tsx — maps to /blog/:slug
8export default function BlogPost({ params }: { params: { slug: string } }) {
9 return <h1>Post: {params.slug}</h1>;
10}
11
12// File: src/app/layout.tsx — wraps all pages
13export default function RootLayout({ children }) {
14 return (
15 <html lang="en">
16 <body>{children}</body>
17 </html>
18 );
19}Real-World Example
A blog homepage that statically generates all posts at build time:
example.ts
tsx
1// src/app/blog/page.tsx
2import { getAllPosts } from '@/lib/posts';
3import PostCard from '@/components/PostCard';
4
5// This is a Server Component (default in App Router)
6// Runs on the server — can fetch DB directly!
7export default async function BlogPage() {
8 const posts = await getAllPosts(); // direct DB query, no API needed
9
10 return (
11 <main>
12 <h1>DevNotes Blog</h1>
13 <div className="posts-grid">
14 {posts.map(post => (
15 <PostCard key={post.slug} post={post} />
16 ))}
17 </div>
18 </main>
19 );
20}
21
22export const metadata = {
23 title: 'Blog | DevNotes',
24 description: 'Learn web development with practical examples',
25};Pitfalls & Interview Tips
- ⚠️In App Router, all components are Server Components by default — they run on the server. Add 'use client' for browser APIs or hooks.
- ⚠️Pages Router and App Router have different conventions — mixing them causes confusion.
- 💡Interview tip: Next.js = React + routing + SSR/SSG + API routes + Image optimization + Font optimization. It's a complete solution.