Application error : a client-side exception has occurred (see the browser console for more information)

Subhash Chaudhary

Subhash Chaudhary

January 11, 2022

7 min read

Most of the developers are currently having trouble with 'Application error: a client-side exception has occurred (see the browser console for more information) '.

In NextJS application, you can solve this problem by setting fallback to true and showing 404 error message or 404 component if the post doesn’t exist with the provided URL or slug. But how can you implement them in your NextJS application?

Before we try to implement the solution in our application, let's figure out what the error is. How does this happen?

Application error

As the name indicates, an application error occurs on the client-side of the application.

In the case of NextJS application, this error occurs if the application does not receive the correct input to be processed. There could be other reasons too. But this is the common one. This error can occur at any time during the application's life cycle, including during development, testing, and deployment.

How this error occurs?

Many different types of errors can be seen during the development or testing phase. Among them, one is an application error. This error may or may not be visible during the development or testing phases of the application, but it may be visible in deployed versions. But what could be the reasons for this? Why do they appear out of nowhere?

To be honest, there isn't a simple answer to it. It could be caused by faulty hardware, viruses, the application not receiving the correct input, or a coding error in your application.

Note that in the NextJS application, we will try to solve this error only for dynamic paths by using getStaticPaths() with fallback set to true. The dynamic path will be coming from external API or CMS.

This error occurs in the NextJS application due to some coding issues. Actually, I won't call it a coding issue; rather, I'll call it a failure to check all possible conditions in your code.

How to solve this error in NextJS?

To solve this error, let's create a scenario in which this error occurs. I'll only show the source code for the dynamic page because explaining each code block would make the post far too long.

In a NextJS pages folder, let’s analyze our dynamic page [slug].js file.

pages/blog/[slug].js
// import .........
import { useRouter } from "next/router";

function dynamicPage({ post }) {
  const router = useRouter();
  if (router.isFallback) {
    return <div>Loading.....</div>;
  }
  return (
    <div className="......">
      <div>
        <h1>{post.title}</h1>
        <img src={post.img.url} alt={post.title} />
        <p>{post.body}</p>
      </div>
    </div>
  );
}


export default dynamicPage;


export async function getStaticPaths()
{
  const posts = await getPosts(); //Getting post from CMS or an API


  return {
    paths: posts.map(({ node:{ slug } }) =>({ params: { slug } })),
    fallback: true,
  };
}


export async function getStaticProps({ params }) {
  const data = await getPostDetails(params.slug);
  return {
    props: {
      post: data,
    },
    revalidate: 10, // If a page is refreshed, user will get updated data and page will be updated every 10 seconds
  };
}

In the above code, we import the useRouter hook and check for a fallback page before returning it as shown below.

if (router.isFallback) {
  return <div>Loading.....</div>;
}

This works fine until you enter the correct URL into the address bar. However, if you enter a dynamic URL that does not exist, instead of displaying a 404 page, it will simply throw an error.

Application error : a client-side exception has occurred (see the browser console for more information)

Solution

To fix this error, we'll look for the fallback and see if the post is 'null' or not.

// import .........
import { useRouter } from "next/router";


function dynamicPage({ post }) {
  const router = useRouter();
  //modified and added this line
  if (!router.isFallback && !post?.slug) {
    return <div> 404 | page doesn't exist.....</div>;
  }


  return (
    <div className="..........">
      {/* Added this line */}
      {router.isFallback? (
        <div>Loading.....</div>
      ) : (
        <div>
          <h1>{post.title}</h1>
          <img src={post.img.url} alt={post.title} />
          <p>{post.body}</p>
        </div>
      )}
    </div>
  );
}


export default dynamicPage;


export async function getStaticPaths()
{
  const posts = await getPosts(); //Getting post from CMS or an API


  return {
    paths: posts.map(({ node: { slug } }) => ({ params: { slug } })),
    fallback: true,
  };
}


export async function getStaticProps({ params }) {
  const data = await getPostDetails(params.slug);
  return {
    props: {
      post: data,
    },
    revalidate: 10, // If a page is refreshed, user will get updated data and page will be updated every 10 seconds
  };
}

As shown, we checked for the fallback and also whether the post was null or not.

if (!router.isFallback && !post?.slug) {
    return <div> 404 | page doesn't exist.....</div>;
}

The above code simply states that if the post of the given URL or slug does not exist, simply display the message 404 does not exist.

{router.isFallback ? (
	<div>Loading.....</div>
) : (
	<div>
		<h1>{post.title}</h1>
		<img src={post.img.url} alt={post.title} />
		<p>{post.body}</p>
	</div>
)}

And, as the above code demonstrates, if there is no cached page in the static pages of the given URL, simply display the loading text (Loading.....). Show the fetched page and cache it in the static folder as soon as it is fetched.

However, if the user enters the incorrect URL, instead of displaying the error, the page 404 will be displayed.

Example code can be seen in Github.

Conclusion

We can show a 404 page instead of throwing an error by checking for the fallback and the existence of the post for the given URL.

I hope you found this post to be useful. If you believe that more content should be added or that something in the above post is incorrect, please contact us.

Read this also: Reveal image on scroll