App Directory & Routing
In Next.js, the App Directory structure and routing system are designed to provide a straightforward way to build and manage your application's pages and layouts. Here’s an overview of how the layout and pages work in Next.js, along with an explanation of routing.
Directory Structure
The App Directory (introduced in Next.js 13) is where you define your application's structure, including pages, layouts, and components. Here’s a typical structure:
task-flow/
└─ src/
└─ app/
├─ layout.jsx
├─ page.jsx
└─ global.css
/timesheets
└─ page.jsx
/team-members
└─ page.jsx
Layouts
Layouts in the App Directory help you define a shared structure for multiple pages, such as headers, footers, or sidebars. They allow you to organize and reuse components efficiently across different sections of your application.
A RootLayout
is required at the top level of your app directory to provide the base structure for your entire application. Defined in app/layout.jsx
, the RootLayout
wraps all pages in your app and includes essential elements like <html>
and <body>
tags to ensure consistent rendering. Without a RootLayout
, your app will not render correctly.
In addition to the RootLayout
, you can create nested layouts for specific sections of your app. For example, while app/layout.jsx
applies to all pages, app/timesheets/layout.jsx
would only affect the /timesheets
section. This allows you to add unique structures or styles to different parts of your application.
Routing
Next.js uses a file-based routing system, where the structure of your files and folders directly corresponds to the routes of your application. In the App Directory, only files named page.jsx
are treated as pages. For instance, app/page.jsx
maps to the root route (/
), while app/timesheets/page.jsx
maps to the /timesheets
route. The convention requires naming these files as page.jsx
. Dynamic routes can be created by using square brackets in the folder name, such as app/[slug]/page.jsx
. For a more detailed explanation, refer to the further reading section.
path | url |
---|---|
app/page.jsx | website.nl |
app/blog/page.jsx | website.nl/blog |
app/blog/my-cat-gifs/page.jsx | website.nl/blog/my-cat-gifs |
<Link>
You can create links between pages using the Next.js's <Link>
feature. This has some merits over using absolute paths, which is still possible.
Absolute Path
<a href="www.google.nl"></a>
Next.js Link
import Link from 'next/link';
function Home() {
return (
<ul>
<li>
<Link href="/">
Home
</Link>
</li>
<li>
<Link href="/about">
About Us
</Link>
</li>
<li>
<Link href="/blog/hello-world">
Blog Post
</Link>
</li>
</ul>
)
};
export default Home;
- We import the
<Link>
component from Next.js. - The
<Link>
component is an extension of an<a>
element, so you don't have to manually add this anymore. Using<Link>
is the preferred and recommended way of navigating in a Next.js app. - The component wraps around the content and passes on its
href
to the underlying<a>
element.