Routing in NextJs
A guide to routing in Next.js (App Router) covering Catch-All Segments, Dynamic Routes, Nested Routes, and more.
Routing in Next.js
Next.js has a file-system-based routing system. The URLs you can access in your browser are determined by how you organize your files and folders within your project.
Understanding the src/app Directory
In Next.js (when using the App Router), the src/app directory serves as the foundation for your application's structure. Key files inside this directory include:
layout.tsx- Defines the layout for your application, allowing you to persist UI elements across different pages.page.tsx- Represents the content of a particular route.
Scenario 1: Creating a Homepage
Suppose you want to have a homepage accessible at:
To achieve this, ensure that a page.tsx file exists inside the src/app directory. By default, this file is created when you initialize a Next.js project.
// src/app/page.tsx
export default function HomePage() {
return <h1>Welcome to the Homepage</h1>;
}Scenario 2: Creating Additional Pages
Now, let's say you want to create additional pages with different URLs.
Creating an About Page
To create a page accessible at:
Follow the same steps as above:
- Inside
src/app, create a folder namedabout. - Inside
about, create apage.tsxfile. - Add the following code:
// src/app/about/page.tsx
export default function About() {
return <h1>About Us</h1>;
}Folder Structure for the Pages
After adding these pages, your src/app directory will look like this:

page.tsx file supplies the page for that route.A folder gives a route its address. A
page.tsxfile makes that address render a page, and alayout.tsxfile adds a shared frame around its children.
Notice the core principle: the name of each folder corresponds directly to the URL segment, and the page.tsx file inside makes that path publicly accessible.
Nested Routes
Scenario 3: Creating Blog Pages
Suppose you want to handle the following routes:
- http://localhost:3000/blog
- http://localhost:3000/blog/first
- http://localhost:3000/blog/second
In Next.js, nested routes are created by nesting folders inside one another. To implement these routes:
- Create a
blogfolder insidesrc/app. - Inside
blog, create apage.tsxfile for the main blog index (/blog). - Inside
blog, create a subfolder namedfirstwith its ownpage.tsx(/blog/first). - Inside
blog, create another subfolder namedsecondwith its ownpage.tsx(/blog/second).
src/app/ blog/ page.tsx - Main Blog List (/blog) first/ page.tsx - First Blog Post (/blog/first) second/ page.tsx - Second Blog Post (/blog/second)Nested Layouts
One of the biggest strengths of the App Router is that layouts can be nested. If you add a layout.tsx inside the blog folder, it will automatically wrap the blog listing and all nested blog posts without re-mounting when you navigate between them:
// src/app/blog/layout.tsx
export default function BlogLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="blog-wrapper">
<nav className="blog-sidebar">
<h3>Recent Posts</h3>
{/* Shared blog sidebar */}
</nav>
<main>{children}</main>
</div>
);
}Dynamic Routing
What if you have dozens or hundreds of blog posts, or an online shop with thousands of products? Creating a physical folder by hand for every single post or product is neither realistic nor maintainable.
This is where Dynamic Routes come into play. In Next.js, you define a dynamic segment by wrapping a folder name in square brackets: [paramName].
src/app/ blog/ page.tsx - Blog list (/blog) [slug]/ page.tsx - Dynamic blog post (/blog/:slug)Any URL matching /blog/anything will be routed to src/app/blog/[slug]/page.tsx, with the dynamic segment passed directly as a parameter.
Accessing Dynamic Parameters
In Next.js Server Components, page components receive params as an asynchronous promise:
// src/app/blog/[slug]/page.tsx
export default async function BlogPost({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
return (
<article>
<h1>Reading Post: {slug}</h1>
<p>Showing content for article with slug: {slug}</p>
</article>
);
}If a visitor opens /blog/learning-nextjs, slug will be "learning-nextjs". If they open /blog/css-tips, slug will be "css-tips".
Handling Unknown Nested Routes (Catch-All Segments)
Dynamic routes like [slug] handle one dynamic level (e.g. /blog/:slug). But what if you are building documentation, a file explorer, or an e-commerce catalog where the path can have an arbitrary number of sub-levels?
- http://localhost:3000/docs/getting-started
- http://localhost:3000/docs/components/buttons
- http://localhost:3000/docs/installation/macos/m-series/troubleshooting
1. Catch-All Segments: [...slug]
To match all subsequent nested segments, prefix the parameter name inside the brackets with three dots: [...slug].
src/app/ docs/ [...slug]/ page.tsx - Catches all nested subpathsNext.js passes the captured path segments to your page component as an array of strings:
// src/app/docs/[...slug]/page.tsx
export default async function DocsPage({
params,
}: {
params: Promise<{ slug: string[] }>;
}) {
const { slug } = await params;
return (
<div>
<h1>Documentation</h1>
<p>Path segments: {slug.join(" / ")}</p>
</div>
);
}Here is how different URLs map to the slug array:
/docs/intro→slug = ["intro"]/docs/ui/buttons→slug = ["ui", "buttons"]/docs/a/b/c/d→slug = ["a", "b", "c", "d"]
2. Optional Catch-All Segments: [[...slug]]
There is one important detail with [...slug]: it requires at least one segment. Visiting /docs directly would result in a 404 unless a separate src/app/docs/page.tsx exists.
If you want a single file to handle both the base route (/docs) and all nested routes (/docs/*), wrap the parameter in double brackets: [[...slug]].
src/app/ docs/ [[...slug]]/ page.tsx - Handles /docs AND /docs/*When a user visits /docs, slug will be undefined. When they visit /docs/setup, slug will be ["setup"].
Route Groups & Private Folders
Route Groups: (groupName)
Sometimes you want to group related routes together or give different sections of your app different layouts, without modifying the browser URL. Wrapping a folder name in parentheses marks it as a Route Group:
src/app/ (marketing)/ layout.tsx - Public marketing layout (header + footer) about/ page.tsx - Accessible at /about (not /marketing/about) (auth)/ layout.tsx - Centered distraction-free layout login/ page.tsx - Accessible at /login signup/ page.tsx - Accessible at /signupThe parentheses instruct Next.js: use this folder to organize code and scope layouts, but omit this segment from the public URL.
Private Folders: _folderName
By prefixing a folder name with an underscore, you mark it as a private implementation detail. Next.js will completely ignore the folder and all its subfolders from the routing system:
src/app/_components/button.tsx- Safe to store components, not accessible via browser.src/app/_lib/db.ts- Private database helper, never routable.
Special Route Files
The App Router reserves specific file conventions that transform ordinary React components into powerful architectural boundaries:
page.tsx— Makes the route publicly accessible and defines its unique UI.layout.tsx— Wraps child pages, preserves state across transitions, and avoids re-renders.loading.tsx— Automatically wraps the route segment in a React Suspense boundary with a fallback skeleton.error.tsx— A client error boundary that catches runtime errors without crashing the entire app.not-found.tsx— Custom 404 UI rendered when a route does not exist or whennotFound()is invoked.route.ts— Creates a backend HTTP API endpoint handlingGET,POST, etc.
Summary
Next.js file-system routing eliminates the need for complex route configuration files. By combining folder nesting, layouts that persist state, dynamic segments ([slug]), and catch-all routes ([...slug]), you can structure virtually any web application intuitively and maintainably.
Final Words
Routing gets easier when you follow the path the browser takes: folders become URL segments, layouts shape the shared frame, and route files decide what each address returns.
Try building one small route tree yourself, then add a nested page and a dynamic segment. Seeing the URL and file structure line up is the quickest way to make the conventions stick.
“True education combines theoretical knowledge with realization, so what we learn becomes skillful living and freedom from ignorance.”
— Bhagavad Gita