Topic 1 of 47
Next.js
Overview
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
// App Router (Next.js 13+ — modern standard)
// File: src/app/page.tsx — maps to /
export default function HomePage() {
return <h1>Welcome to DevNotes</h1>;
}
// File: src/app/blog/[slug]/page.tsx — maps to /blog/:slug
export default function BlogPost({ params }: { params: { slug: string } }) {
return <h1>Post: {params.slug}</h1>;
}
// File: src/app/layout.tsx — wraps all pages
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}Common Pitfalls
- 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.
Real-World Example
A blog homepage that statically generates all posts at build time:
example
tsx
// src/app/blog/page.tsx
import { getAllPosts } from '@/lib/posts';
import PostCard from '@/components/PostCard';
// This is a Server Component (default in App Router)
// Runs on the server — can fetch DB directly!
export default async function BlogPage() {
const posts = await getAllPosts(); // direct DB query, no API needed
return (
<main>
<h1>DevNotes Blog</h1>
<div className="posts-grid">
{posts.map(post => (
<PostCard key={post.slug} post={post} />
))}
</div>
</main>
);
}
export const metadata = {
title: 'Blog | DevNotes',
description: 'Learn web development with practical examples',
};