export const getServerSideProps = async ({ params }) => {
const res = await fetch(
`https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}`
);
const { hits } = await res.json();
if (!hits) {
return {
notFound: true,
};
}
return {
props: { pic: hits[0] },
notFound: true,
};
};
I keep getting this error whenever a user enter an invalid params.id=====>
Server Error FetchError: invalid json response body at https://pixabay.com/api/?key=*************************************&id=**xzk** reason: Unexpected token E in JSON at position 1
I used "xzk" as the id value which is invalid and instead of redirecting user to notFoundPage, it keeps showing this error, and the error is even revealing my api-keys. Please what am I doing wrong? Ideas is also welcome. Thanks in advance.
I've found a solution to this, which is checking if the response is OK. And if it is not Ok then it should redirect the user to notFound page which was set to true in the if statement.
export const getServerSideProps = async ({ params }) => {
const { id } = params;
const res = await fetch(
`https://pixabay.com/api/?key=${process.env.API_KEY}&id=${id}`
);
if (!res.ok) {
return {
notFound: true,
};
}
const { hits } = await res.json();
return {
props: { pic: hits[0] },
};
};