Next.js has become a powerhouse in the React ecosystem, and understanding its file conventions is key to getting the most out of it. In this blog post, we'll break down the 9 special routing files in the App Router, which replaces the older pages directory approach. We'll look at each file type and answer four main questions:
- What is it?
- Why should you care?
- How do you use it?
- What are the key considerations?
Let’s start with a brief intro about the App Router itself.
The Next.js App Router, introduced in Next.js 13, represents a shift from the previous pages directory approach. It uses folders in the app directory to define routes.
This new system supports layouts, loading states, and error handling at the route level. It also allows seamless mixing of client and server components, offering improved performance and a more flexible development experience from the first load onwards.
Now, let's dive into each of these special files, starting with the fundamental building block of Next.js routing.
page.tsx contains the UI components that are unique to a route.
This file is crucial because it works hand-in-hand with Next.js's folder structure to create your routing system. It means you can define the content for each page in your application.
- Create a
page.tsxfile in any folder within yourappdirectory. - The file's location corresponds directly to the URL path.
- Export a default React component that defines the page content.
- You can nest folders inside other folders to create nested routes.
Example:
// app/blog/page.tsx
export default function BlogPage() {
return <h1>Welcome to my blog</h1>
}- Export type: Always use
export defaultfor your page component, not a named export. - Directory structure: Avoid mixing
pages/andapp/directories in the same project to prevent routing conflicts. - Data fetching: Use the
fetchAPI withasync/awaitdirectly in your components. - Component type:
page.tsxcomponents are Server Components by default. Add the'use client'directive at the top of your file if you need client-side interactivity for client components.
layout.tsx creates a shared layout that wraps around your page content.
This way you can create reusable layouts, reducing redundant code and ensuring a cohesive user experience across your site. Layouts are also performance-optimized, as they don't re-render when navigating between pages.
- Create a
layout.tsxfile in theappfolder for a root layout, or in any subfolder for more specific layouts. - Export a default React component that accepts a
childrenprop.
Example: