- read

Mastering Error and Loading Pages in Next.js 13: Best Practices and Strategies.

Daniel Craciun 29

Mastering Error and Loading Pages in Next.js 13: Best Practices and Strategies.

Daniel Craciun
Level Up Coding
Published in
4 min read12 hours ago

--

In the fast-paced world of web development, user experience is paramount. When it comes to building web applications with Next.js 13, handling errors and optimizing loading pages are crucial for delivering a smooth and engaging user journey.

In this article, we will dive deep into the latest features and best practices in Next.js 13 to ensure your web applications not only function flawlessly but also load quickly, making them a joy to use.

Join me as we explore the world of error handling and page loading in Next.js 13. Let’s make your web development journey even more exciting!

Without further ado, lets get straight into it!

Table of Contents

  • Setup Next.js 13 Project Environment
  • Dependencies Installation
  • Error Page Example
  • Loading Page Example

Setup Next.js 13 Project Environment

To setup a Next.js project, please check out the instructions here. The installation process generally consists of running the following command in the terminal.

npx create-next-app@latest

Dependencies Installation

Open a terminal within your project directory, and execute one of the following commands to get started:

npm install lucide-react
yarn add lucide-react
pnpm add lucide-react

Error Page Example

We will begin by walking through an example of an error page in Next.js 13.

Inside your app/page.tsx file, copy the following code:

const page = async () => {
// switch the value of `error` to simulate an error
// and load an error page.
const error = false;
if (!error) {
return <div>page</div>
} else {
throw new Error()
}
}

export default page

Whenever error is set to true, this will throw a new Error. In this situation, we would like Next.js to render an error page UI rather than rendering a cryptic error message to the user, which improves UX.

To do this, create a file called error.tsx inside the app/ directory at the same hierarchy level as your page.tsx file.

// src: https://nextjs.org/docs/app/building-your-application/routing/error-handling

'use client' // Error components must be Client Components

import { useEffect } from 'react'

export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error)
}, [error])

return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
)
}
  • The error argument passed the the Error component will hold all the details of the error, and can be logged inside a useEffect for debugging purposes.
  • The reset argument is a function that — when called — will attempt to re-render the page.tsx file for which an error has occurred.
  • NOTE: error components must be client components because they automatically wrap a route segment and its nested children in a React Error Boundary, which only exists in a client context.

Loading Page Example

How about defining a loading page?

You guessed it, you will need to create a loading.tsx file alongside your page.tsx file that you need loading state for.

import { Loader2 } from "lucide-react"

const loading = () => {
return (
<div className="mt-4 flex">
<Loader2 className="h-24 w-24 animate-spin" />
</div>
)
}

export default loading

In this case I display a loading spinner in the middle of my screen while my page is loading.

To increase the duration of the loading spinner, copy the following into page.tsx.

import { setTimeout } from "timers/promises"

const page = async () => {
// switch the value of `error` to simulate an error
// and load an error page.
const error = false;

await setTimeout(1000)

if (!error) {
return <div>page</div>
} else {
throw new Error()
}
}

export default page
  • The addition of setTimeout(1000)will mock a 1-second delay. In the real world, this may be due to data fetching or other server-related activities.

Now run your code and you should see a similar output:

Loading spinner example on my website called EMM.
Loading spinner example on my website called EMM.

Conclusion

Congrats! You now have robust loading and error state for all your Next.js pages.

If you enjoyed this article, check out my profile for many more stories like this, and stay tuned for future articles! 👍

Affiliate Links 🏷️🔗

Connect With Me 🌐