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:
Not sure what I'm doing wrong here. Any help is appreciated.