In Next.js, the App Router provides a new way to handle routing. It uses the filesystem to define routes and supports features like nested routes, layouts, and API routes directly in the app directory.

File naming conventions

The page.js file is used to define the main component for a particular route. This file dictates what is rendered when the route corresponding to its directory is accessed.

The layout.js file plays a crucial role in defining the layout structure for your application. It allows you to specify components that will wrap around your page content, such as headers, footers, or sidebars.

The route.js file is used to define API routes. These files handle HTTP requests and provide server-side functionality such as data fetching, form submission handling, etc.

A simple structure

Each folder within the app directory represents a route segment. Files inside these folders represent the components rendered for those routes.

Here’s an example file structure:

my-app/
├── app/
│   ├── page.js
│   ├── layout.js
│   ├── about/
│   │   └── page.js
│   ├── blog/
│   │   ├── [id]/
│   │   │   └── page.js
│   │   └── page.js
│   ├── api/
│   │   └── users/
│   │       └── route.js
│   └── contact/
│       └── page.js
├── next.config.js
├── package.json
└── ...

In order to navigate to our about page through the browser, we need to type the following address:

<http://localhost:3000/about/>

As you can see, the blog route includes a subfolder using the square brackets [] notation. This allows us to dynamically add a variable to our path and to also have access to it inside our page.js file. To navigate to a specific blog post for example, we would type:

<http://localhost:3000/blog/298590/>

The api route is also important. We use this folder to create backend API routes for our application. For example, to get all my users data i can make a GET HTTP request at:

<http://localhost:3000/api/users/>