Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
How to redirect user to notFound Page in getServerSideProps whenever an invalid params.id is entered in Next.JS
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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] },
  };
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda