Next.
js Notes
📌 What is Next.js?
A React framework for building server-side rendered (SSR) or
static websites.
Built on top of React with many powerful features for
production-grade apps.
🚀 Key Features:
✅ Server-side Rendering (SSR)
✅ Static Site Generation (SSG)
✅ File-based routing
✅ API routes
✅ Image optimization
✅ Built-in CSS & Sass support
✅ Fast Refresh for development
📁 File Structure Basics:
swift
CopyEdit
/pages → All routes (each .js or .tsx is a route)
/public → Static assets (images, fonts)
/styles → CSS/Sass files
🧭 Routing in Next.js:
Every file in /pages = a route.
Example:
pages/index.js → /
pages/about.js → /about
Dynamic Routing:
js
CopyEdit
// pages/product/[id].js
import { useRouter } from 'next/router'
const Product = () => {
const router = useRouter();
const { id } = router.query;
return <h1>Product ID: {id}</h1>;
};
export default Product;
⚙️Data Fetching Methods:
1. getStaticProps – Fetch data at build time (SSG).
2. getServerSideProps – Fetch data on each request (SSR).
3. getStaticPaths – Used with dynamic routes during SSG.
4. API Routes – Build your backend in /pages/api/.
js
CopyEdit
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from API!' });
🎨 Styling in Next.js:
CSS Modules (scoped CSS)
Global CSS (in _app.js)
Tailwind CSS (easy to set up)
Sass support
Deployment:
Vercel is the official Next.js deployment platform.
Supports CI/CD, custom domains, and edge functions.
✅ Best Practices:
Use Image from next/image for optimized images.
Use Link from next/link for client-side navigation.
Use environment variables with .env.local.