0

I'm working with an API that come with a pagination function but doesn't sort data based on the client's requirements. To work around this I'm fetching all data from the API inside getServerSideProps and only returning a portion of the data based on page number.

// getServerSideProps

export const getServerSideProps = (ctx) => {
 ctx.res.setHeader(
    'Cache-Control',
    'public, s-maxage=60, stale-while-revalidate=120'
  )

  const page = ctx.query.page
  const itemsPerPage = 6

  const products = await getDataFromApi() //api sdk method

  const featured = products.filter(isFeatured).sort(alphabetical)
  const notFeatured = products.filter(isNotFeatured).sort(alphabetical)

  const sortedProducts = [...featured, ...notFeatured]

  return {
    props : {
      products : sortedProducts.slice(page - 1 * itemsPerPage, (page * itemsPerPage) + 1)
    }
  }

}

Edit: I used fetch as an example to simplify and make the code generic but irl, I'm actually using the api's sdk. I am also looking for any suggestions for a solution since I have been informed that this data may be in the thousands.

Does the cache control store all the data or only the ones returned after slicing? I want to reduce refetching if possible. The API sorting can only sort 1 field, I need to sort as such that featured products are shown in the first pages while sorted alphabetically within the featured block and non featured block respectively. Looking for a scalable solution as when the amount of data increases I'm concerned about load times and impacts on performance.

Thanks!

I've tried client-side fetching and sorting but I figured it's using the same logic so I moved it to server-side.

I've tried passing and storing all data on client-side in a state but I'm not sure on the load on the client side and performance impacts.

1 Answers1

0

If you are using the fetch api it caches by default everything you tried to fetch. Take a look at the documentation

Ferhat
  • 46
  • 6
  • Thanks for the info. I should have been clearer with the information I provided. I am not using fetch but rather an sdk for the backend and am unable to switch to fetch due to the client's requirements. I have updated my question to reflect this. I am also using the pages router. – muhammadarifftaha Aug 03 '23 at 02:01
  • No problem and thanks for clarifying. Next.js can also cache its response. I think this might help you. There was a [similar question to yours](https://stackoverflow.com/questions/71333002/how-to-enable-cache-for-getserversideprops) which seems to be solved. You can also find the solution it in the [Cache documention](https://stackoverflow.com/questions/71333002/how-to-enable-cache-for-getserversideprops) for Next.js – Ferhat Aug 03 '23 at 06:05