Next.js 15 follows the App Router (app/
directory), introduced in Next.js 13, which provides a file-based routing system with React Server Components, Server Actions, and Middleware.
Next.js uses file-based routing, meaning the folder structure determines the URL.
Each file inside app/
corresponds to a route.
app/├── page.tsx → "/" (Home page)├── about/│ ├── page.tsx → "/about"├── dashboard/│ ├── page.tsx → "/dashboard"├── blog/│ ├── [id]/page.tsx → "/blog/:id" (Dynamic Route)
Example: A simple about
page (app/about/page.tsx
)
export default function AboutPage() {return <h1>About Us</h1>;}
[param]
)Used for paths that change dynamically, like /blog/:id
.
// app/blog/[id]/page.tsx → "/blog/:id"export default function BlogPost({ params }: { params: { id: string } }) {return <h1>Blog Post {params.id}</h1>;}
📌 params.id
gets the dynamic value from the URL.
layout.tsx
)Layouts wrap multiple pages with shared UI (e.g., headers, footers).
// app/layout.tsx (applies to all pages)export default function RootLayout({ children }: { children: React.ReactNode }) {return (<html lang="en"><body><header>My Site Header</header>{children} {/* Pages will be rendered here */}<footer>Footer Content</footer></body></html>);}
Layouts can be defined per route, like a dashboard
layout:
// app/dashboard/layout.tsxexport default function DashboardLayout({ children }: { children: React.ReactNode }) {return (<div><nav>Dashboard Sidebar</nav><main>{children}</main></div>);}
💡 Now, all pages inside /dashboard/
use this layout.
Next.js provides error.tsx
files for per-route error handling.
// app/dashboard/error.tsx"use client"; // Required for error componentsimport { useEffect } from "react";export default function Error({ error, reset }: { error: Error; reset: () => void }) {useEffect(() => {console.error(error);}, [error]);return (<div><h1>Something went wrong! 😢</h1><button onClick={() => reset()}>Try Again</button></div>);}
📌 reset()
reloads the page when an error occurs.
For site-wide error handling, add an app/global-error.tsx
file.
// app/global-error.tsx"use client";export default function GlobalError({ error }: { error: Error }) {return (<html><body><h1>Global Error: {error.message}</h1></body></html>);}
Next.js supports automatic loading UI with loading.tsx
files.
// app/dashboard/loading.tsxexport default function Loading() {return <p>Loading Dashboard...</p>;}
📌 The loading.tsx
file automatically renders when a page or component is fetching data.