Tailwind Logo

About Next.js' App Router

Next.js

Published: 2023-08-31

In Next.js, the routing mechanism switched to the new App Router in version 13.4. The previous method is now referred to as Page Routing, which remains available, but the App Router will become the standard. This time, we'll review the new App Router.

Difference point of App Router and Page Router

One major difference is that the idea of paths has changed. The details are covered on the official website page and on other blogs and such, so if you want to know the details, please look them up separately.

The conventional Page Router works as follows.

  • pages/index.tsx -> act as root page
  • pages/blog.tsx -> Works as a /blog page
  • pages/blog/index.tsx -> Works as a /blog page
  • pages/pages/[id].tsx -> Works as pages/id (id is optional)

The point is that the files under the Pages folder were basically the target of the routing. Of course, the above example is written in plain English, but it shows that there are two patterns of what should be done when creating a /blog page.

On the other hand, what happens when it comes to App Router? Not all files are covered, but files with roles are defined.

For example, it could look like this

  • app/page.tsx > / act as a page
  • app/blog/page.tsx > Works as a /blog page
  • app/[id]/page.tsx > Works as a /id/ page

In addition to pages, other files such as errors and layouts can also be used, allowing for flexibility when the scale of the project grows to a certain extent. The routing rules are introduced on the Project Organization and File Colocation page.

Create a new project and check it

We would like to create a new application and check it as soon as possible. Please execute the following command on the command line.

Plain Text
npx create-next-app

The results of the run are as follows

nextjsapprouter01.png

The fourth question, "Do you want to use /src? is set to "No". Do you want to use App Router? Yes" is selected for "Do you want to use App Router?

If you actually open the created project in Visual Studio Code and check the k-layer, you will see something like this.

nextjsapprouter02.png

The page.tsx in the App folder displays the top page. When executed, the following page is displayed.

nextjsapprouter03.png

You can check the code and operation below.

Summary

The App Router differs from the traditional Page Router mechanism, but while it has some advantages, we are still using the Page Router for the XM Cloud sample, for example. In this blog, we will use the App Router to create Next.js samples, but for XM Cloud, we will write the code in accordance with the Headless SXA implementation.

Tags