Photo by Lucas Todeschini on Unsplash
Let's explore routing in Next.js: understanding how to define routes, manage routing, delve into various special files in Next.js, and explore the different types of routes available.
In version 13, Next.js introduced a new App Router built on React Server Components, which supports shared layouts, nested routing, loading states, error handling, and more.
Next.js 13 uses an app-named directory for its App Router and a public directory for static file serving in the project's root directory.
Photo by Domenico Loia on Unsplash
Next.js uses file-system based routing, and in its App Router, each folder that has a page.js file exporting a React Component defines a Route and can be publicly accessible, and the folder name defines the path segment of the Browser URL.
Photo by Domenico Loia on Unsplash
In the App Router, special file names define special meanings, and these are layout.js, page.js, loading.js, not-found.js, error.js, template.js, default.js, and route.js for defining Page, Layout, Loading UI, Not-Found UI, Error UI, Template, Default Page, and Route Handler (API endpoint).
Photo by Florian Olivo on Unsplash
In the App Router, the app directory must have a layout.js (RootLayout) file that must include html and body tags. All Pages (page.js) of the app or nested folders and nested layouts (layout.js) are rendered in RootLayout as children prop.
Photo by Florian Olivo on Unsplash
In the App Router, to define a Route, we need to create a folder that has a page.js file. For example, to create /about and /blogs/blog-title pages, we need to create about and /blogs/blog-title folders in the app directory with a page.js file in each.
Photo by Florian Olivo on Unsplash
In the App Router, we can create Static Routes, Dynamic Routes, Parallel Routes, Intercepting Routes, and Route Groups. You can learn more in detail at Next.js Docs.
Explore Next.js