Me Articles

Generate multiple pages using NextJS getServerSideProps

If you are planning to create multiple pages from an external API, this is your article. I did ran into some challenges myself, but I did manage to solve it, same reason why I write this article. I want to share my solution.

Let me show you a very small example of the API.

[
  {
    title: "First article",
    id: 1,
  },
  {
    title: "Second article",
    id: 2,
  }
]

Super small and simple but clearly, I am trying to generate a page for each article.

My first effort went wrong, let me show you here, how the codes looked and what causes the issue.

/src/pages/articles/[id].js

function Article(props) {
  console.log(props)
  return <div>...</div>
}

export async function getServerSideProps(context) {
  const res = await fetch("https://.../articles");
  const data = await res.json()

  return {
    props: { data }
  }
}

The code above, will correctly generate a page for each article from the API. I made it like this, because it is how it is explained in NextJS own documents. Read example here. But their example, are using an API, that will return data for each unique page
The issue using this examply, with the API I was using, is that the props for the Article component, will be all articles. We only want the props for each specific article of course. Luckily, we can fix this, by adding 2 lines of codes.

function Article(props) {
  console.log(props)
  return <div>...</div>
}

export async function getServerSideProps(context) {
  const res = await fetch("https://.../articles");
  const articles = await res.json();

  const articleId = context.query.id;
  const [article] = articles.filter((article) => article.id === articleId);

  return {
    props: { article }
  }
}

By using context, we can get each subpage generated. In this case, I am using ID for each article. With the ID, I am able to filter the whole feed, and get each unique article and return as prop.

Me Articles Generate multiple pages using NextJS getServerSideProps