How the NextJS app router works
A short guide that explains how the NextJS app router works.
The following post serves as a summary for the documentation found in the links below.
Structure
The structure for Oscar de la Hera Gomez's student archive.
The structure of a NextJS app router is based on two critical elements: pages and layouts.
Root Layout
The layout found at the root of the app folder is known as the root layout.
This layout is required and applies to all routes - meaning, on EVERY page, this layout will get called before the page.
"Children" refers to the content of each page, at each route.
Root Page
A page, which gets rendered as the children of the root layout, represents the UI that is unique to each route.
The page.tsx found at the root of the app folder represents the home page (i.e. "/").
Folders as Routes
Folders within the app root folder, or sub folders within folders, represent routes of the web page.
These folders must contain a page.tsx file and optionally, can contain layout.tsx file.
The naming convention for these folders dictate how the routes work.
Layout
The layout within a sub folder would get called and added to the root layout at the top (i.e. where "Layout UI" is found in the image above).
Page
The page within a folder represents the unique UI of the route.
For more information on static or dynamic routes, read the next two sections.
Folders as Static Paths
If you wish to use a static path, name the folder after the route that you wish to use (i.e. "cohorts" for /cohorts).
Please note each folder or subfolder requires a page.tsx file.
Folders as Dynamic Paths
If you wish to use dynamic paths, use a naming convention such as classes/[slug] or element-[slug]-[id] which would allow for a routes "/classes/[slug]" or "/element-[slug]-[id]" respectively.
These dynamic parameters (i.e. slug and id) will be available within the page and layout of the folder, enabling you to gather content dynamically.
Please note each folder or subfolder requires a page.tsx file.
Looking to add Metadata, a Sitemap, a 404 or Generate Static Websites (SSG)?
Follow our tutorials below to learn how to add metadata to pages, create a sitemap, a 404 or generate static websites.
Looking to learn more about NextJS, ReactJS or web development?
Search our blog to find educational content on NextJS, ReactJS and web development.