3

I'm using Axios to access a simple API. I want to redirect the user to the built-in Next.js 404 page if the request fails with a 404 error. I'm using the notFound boolean set to true in the event the request status is 404. There are 10 users on the jsonplaceholder.typicode.com user API I'm using. If I access the first 10 users the request returns 200 and my page is rendered as intended. If I access https://jsonplaceholder.typicode.com/users/11, for example, I get the unhandled error page instead of the built-in 404 page.

import Link from 'next/link';
import axios from 'axios';

export async function getServerSideProps(ctx) {
  const { id } = ctx.query;
  const userReq = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);
  if (userReq.status === 404) {
    return {
      notFound: true,
    };
  }
  return {
    props: {
      user: userReq.data,
    },
  };
}

function UserPage({ user }) {
  return (
   <div>
     <div>
       <Link href="/" passHref>
        Back to home
       </Link>
     </div>
     <hr />
     <div style={{ display: 'flex' }}>
      <div>
       <div>
         <b>Username:</b> {user.username}
       </div>
       <div>
         <b>Full name:</b>
         {user.name}
       </div>
       <div>
         <b>Email:</b> {user.email}
       </div>
       <div>
         <b>Company:</b> {user.company.name}
       </div>
       <div>
         <b>Phone:</b> {user.phone}
       </div>
      </div>
    </div>
  </div>
 );
}

export default UserPage;

But instead of getting the built-in Next.js 404 page, I get a unhandled error: enter image description here

Not sure what I'm doing wrong here. Any help is appreciated.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Robbyo
  • 51
  • 3

1 Answers1

2

Axios requests that return a non-2xx response will throw an error. The failed request is throwing an error before getServerSideProps has the chance to return and display the 404 page.

You have to add a try/catch around the axios call and return the 404 page from the catch block instead.

export async function getServerSideProps(ctx) {
    const { id } = ctx.query;

    try {
        const userReq = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);

        return {
            props: {
                user: userReq.data
            }
        };
    } catch(err) {
        console.error(err);

        return { 
            notFound: true 
        };
    }
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146