Pages in NextJS
📄 Pages in Next.js
In Next.js, pages are React components stored inside the pages/ directory. Each file in pages/ automatically becomes a route, making routing file-based and automatic.
📌 1. Creating Pages in Next.js
Next.js uses the pages/ directory to create routes automatically.
🔹 Example: Basic Page
<h1>About Page<h1>Welcome to Next.js!<h1>Page Not Found<h1>Blog Post: {id}</h1>;}
✅ Accessible at /blog/1, /blog/my-post
📌 4. Nested Pages (Folders as Routes)
Next.js allows nested routes using folders.
pages/│── index.js → `/`│── about.js → `/about`│── blog/│ ├── index.js → `/blog`│ ├── [id].js → `/blog/:id`
✅ Each folder acts as a route segment
📌 5. API Pages (pages/api/)
Next.js supports backend functionality with API routes.
// pages/api/hello.jsexport default function handler(req, res) { res.status(200).json({ message: "Hello API" });}
✅ Accessible at /api/hello
📌 6. Special Pages in app/ Directory (Next.js 13+)
For Next.js App Router, use page.js inside folders:
app/│── page.js → `/`│── about/│ ├── page.js → `/about`│── blog/│ ├── [id]/│ ├── page.js → `/blog/:id`
✅ Each page.js acts as a page component
📌 7. Best Practices for Pages in Next.js
✔️ Use folders for nested pages
✔️ Use [param].js for dynamic routes
✔️ Create 404.js for custom error pages
✔️ Use api/ for backend routes