Working with the Next.js 13 App Router

Getting started

To begin, create and run a new Next.js project using the following commands in the terminal:

npx create-next-app@latest routing-app
cd routing-app
npm run dev

Next.js is well known for its file system-based routing. With the addition of the App Router, however, Next.js 13 has changed the way developers must perform many tasks.

While it still supports file system-based routing, which uses the Pages Router, the new App Router introduces the concepts of layouts, error components, and loading components.

New features in Next.js 13

Before we start working on our project, we’ll review the new features and concepts introduced in Next.js 13.

Pages Router vs. App Router

If you’ve worked with previous versions of Next.js, you might already be familiar with the Pages Router. Any file created inside the pages directory would act as a route in the UI. For example, pages/home.jsx would take care of the /home route:

The new App Router works alongside the Pages Router to support incremental adoption and provide other new features like server-side rendering and static site generation.

Routing with the App Router

Just like files in the pages directory, routing with the App Router is controlled via folders inside the app directory. The UI for a particular route is defined by a page.jsx file inside of the folder.

See the details of following files:

loading.tsx

error.tsx

layout.tsx

template.tsx

loading.tsx is an optional file that you can create within any directory inside of the app directory. It automatically wraps the page inside a React Suspense boundary. The component will be shown immediately on the first load as well as when you’re navigating between the sibling routes.

error.tsx is an optional file that isolates the error to the smallest possible subsection of the app. Creating the error.tsx file automatically wraps the page inside a React error boundary. Whenever any error occurs inside the folder where this file is placed, the component will be replaced with the contents of the error.tsx file

You can use the layout.tsx file to define a UI that is shared across multiple pages. A layout can render another layout or a page inside of it. Whenever a route changes to any component that is within the layout, its state is preserved because the layout component is not unmounted.

template.tsx is similar to the layout.tsx file, but upon navigation, a new instance of the component is mounted and the state is not preserved.

Using layouts and templates allows us to take advantage of a concept known as partial rendering. While moving between routes inside of the same folder, only the layouts and pages inside of that folder are fetched and rendered:

Lets start with Next.js 13

Let’s run the bootstrapped code as is:

npm run dev

3 thoughts on “Working with the Next.js 13 App Router

Comments are closed.