I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound
boolean to true if the request status is 404. There are a total of 10 users available on the jsonplaceholder.typicode.com
user API that I am utilizing. When I access the first 10 users, the request returns a 200 status and my page renders as expected. However, when attempting to access
https://jsonplaceholder.typicode.com/users/11
, for instance, instead of seeing the built-in 404 page, an unhandled error page is displayed.
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;
Instead of being directed to the standard Next.js 404 page, I encounter an unhandled error: https://i.stack.imgur.com/4CrI4.png
I am unsure about the mistake I am making here. Any guidance or assistance would be greatly appreciated.