Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to 404 page if data is invalid in getStaticProps?

In my Next.js app I will fetch Author's all article. I'm getting author Id from request params. I pre-generated some of my authors with getStaticPaths.

In getStaticPaths I set fallback to true. If author Id is provided correctly it works fine but if you write wrong text to request params it returns an error.

[authorId].js page

export async function getStaticPaths() {
  const fetchAuthors = await axios.get(
    "http://localhost:3000/api/articles/authors"
  );

  return {
    paths: [
      ...fetchAuthors.data.map((item) => {
        return { params: { authorId: item.author._id } };
      }),
    ],
    fallback: true,
  };
}
export async function getStaticProps(context) {
  const {
    params: { authorId },
  } = context;

  const fetchArticles = await axios.get(
    `http://localhost:3000/api/articles/${authorId}/1`
  );

  const fetchAuthor = await axios.get(
    `http://localhost:3000/api/articles/authors/${authorId}`
  );

  return {
    props: {
      Articles: fetchArticles.data,
      Author: fetchAuthor.data,
    },
    revalidate: 60,
  };
}
const AuthorProfilePage = ({ Articles, Author }) => {
    return <>
             <div className={styles.authorImgContainerBig}>
             <Image
               src={Author.author.photo.url}
               className={styles.authorImgBig}
               layout="fill"
               objectFit="cover"
               quality={100}
               alt=""
              />
              </div>
           </>
}

If Author Id exists in database it works fine. But if you pass for example 'asljnsaf' as Author Id it returns error.

Error message

Server Error
TypeError: Cannot read property 'author' of undefined

<Image
  55 |   src={
> 56 |     Author.author.photo.url ||
     |           ^
  57 |     "https://res.cloudinary.com/bizimsehir-gazetesi/image/upload/v1624802793/blank-profile-picture-973460_1280_duksmn.png"
  58 |   }
  59 |   className={styles.authorImgBig}

How can I redirect to 404 page if author does not exist?

like image 985
Bob Stone Avatar asked Aug 31 '25 10:08

Bob Stone


1 Answers

You can return a 404 page directly from the getStaticProps function if the author data doesn't exist.

export async function getStaticProps(context) {
    const { params: { authorId } } = context;

    const fetchArticles = await axios.get(`http://localhost:3000/api/articles/${authorId}/1`);
    const fetchAuthor = await axios.get(`http://localhost:3000/api/articles/authors/${authorId}`);
    
    // Handle `undefined` author data
    if (!fetchAuthor.data) {
        return {
            notFound: true
        };
    }

    return {
        props: {
            Articles: fetchArticles.data,
            Author: fetchAuthor.data
        },
        revalidate: 60
    };
}
like image 56
juliomalves Avatar answered Sep 03 '25 03:09

juliomalves