Creating Routes and Layouts
Explore how to create routes and nested layouts in Next.js using the App Router. Understand mapping page files to routes, building persistent UI with layouts, and implementing nested structures to enhance app performance and user experience.
Routing is the core part of any web app and in Next.js, the App Router makes it both powerful and intuitive.
In this lesson, we’ll see how page.js files map directly to routes, and how layout.js organize the UI by wrapping groups of related pages. These patterns lay the groundwork for building well-structured and fast apps.
Creating a basic route
Let’s start by creating a simple route inside the app/ directory. Every page.js file inside the app/ folder or any of its subfolders automatically becomes a new route.
For example, we can define a React component in the app/about/page.js file to serve as the content for the /about route.
// app/about/page.jsexport default function AboutPage() {return <h1>About us</h1>;}
Under the hood, Next.js detects the app/about/page.js file and registers it as the /about route. No configuration or route definitions are needed.
To create a nested route like /about/team, we can place a new page.js file inside a nested folder:
Then we define a component in app/about/team/page.js to handle the /about/team route:
// app/about/team/page.jsexport default function TeamPage() {return <h1>Meet the team</h1>;}
Why layouts matter
Layouts in Next.js let us define parts of the UI that stay visible while navigating between different pages like a header, sidebar, or footer. These parts don’t unmount or reset when the route changes. Think of a layout as the “shell” of an app: a stable frame that wraps ...