1

using getServerSideProps to do fetch internal API data, the TTFb time is really high, my page run slow.
So I'm searching for other fetching strategies, my MongoDB data is not large (DATABASE SIZE: 33.84KB), and data does not change often, the best way I think is the State generation page, the total should only 25 pages being generated, but the problem is getStateProps() method can't fetch internal API (development works, production not).
I try:

  1. useEffect : slower than getServerProps
  2. export the MongoDB file to data.js and put it into the project as a fake API: it can work with getStaticProp but the date I still want to storge in the database.
  3. Host API to other domains as external: getStateProps works, approach weird
  4. hard code every 25 page (X)

Question:

  1. the method to improve the code and TTFB
  2. Why getStateProps can't fetch internal API, why design like that.
Balius
  • 39
  • 11
  • _"problem is getStateProps() method can't fetch internal API "_ - There are workarounds to solve that, you just need to use your API route logic directly. See [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/a/65760948/1870780). – juliomalves Dec 03 '21 at 20:00

1 Answers1

0

I saw an article on MongoDB, here is the link, just don't use internal API and then fetch data direct to MongoDB in getStaticProps, here in my code.

BEFORE

export async function getServerSideProps() {
 
  const response = await fetch(`${server}/api/gallery`);
  const data = await response.json();

  if (!data) {
    return {
      notFound: true,
    };
  }

  return {
    props: { data },
  };
}
    

AFTER

export async function getStaticProps() {
  await dbConnect()
  //connect to mongodb
  const gallery = await art.find()
//i use mongoose model to fetch data


    return {
      props:{
        data:JSON.parse(JSON.stringify(gallery))
      }
    }

}
Balius
  • 39
  • 11