Loading and 404 Pages in Next.js 13

Loading and 404 Pages in Next.js 13

Next.js is known for its developer-friendly features and excellent performance out of the box. With the release of Next.js 13, it has become even more powerful, offering new tools for customizing your application's loading and 404 pages. In this article, we'll explore how to create custom loading and 404 pages in Next.js 13.

🌀 Global Loading Page:

Creating a global loading page in a Next.js application allows you to display a loading indicator or animation whenever your application is fetching data or transitioning between pages. This provides a better user experience by giving users feedback that something is happening in the background.

In your Nextjs App create a ‘loading.tsx’ file in the ‘app’ directory to apply the global loader.

You can add CSS styles to your global loading component to make it visually appealing and match your application's design.

🌀Unique Loading Page:

We can show a loader specific to a certain page by creating another ‘loading.tsx’ file within the desired page folder. For example, let’s create a ‘users’ folder with a unique loader, this time for loading users.

Now whenever you go to the "users" page it will display the users-loading component.

Note: If we add a ‘child’ folder with ‘page.tsx’ inside the ‘users’ folder, the child page will inherit its closest parent’s loader.

🌀Global 404 Page:

We want to display a global 404 not-found page when a user accesses a non-existent page. To achieve this, create a ‘not-found.tsx’ file in the ‘app’ directory. Just like in the previous example.

In this example, our global not-found component will trigger when we try to access a non-existent route, for example: "http://localhost:3000/test".

🌀404 page in dynamic routing:

A dynamic route is a route with a parameter. To create a dynamic segment within our "users' folder, wrap the folder’s name in square brackets: [id]. For example to access a dynamic user's ID : "http://localhost:3000/users/4".

Now to create a unique custom 404 page for dynamic routes we add a ‘not-found.tsx’ file within the users/[id] folder. And customize the appearance the way we desire.

We will implement a condition that restricts the ID to a range between 0 and 10. If an invalid ID of greater than 10 is provided, we’ll use the ‘notFound( ) function from “next/navigation” to trigger the not-found component.

For example, if we try to access a users/11 it will show the custom not-found component:

🌀Conclusion

In Next.js 13, creating custom loading and 404 pages has become more accessible and flexible than ever before, enhancing the user experience of your web applications. These customization options allow you to maintain a consistent look and feel while providing valuable feedback to your users.