Skip to main content

GetServerSideProps Inefficient internal api call - example & alternative

 GetServerSideProps at request time fetches data from api endpoints and renders a content on the page,  a pretty neat feature. 

We directly make the api call within the getServerSideProps function block which gets executed at the server side (not the client side aka browser). External api endpoints are on different sever and the way to interact & get data from them is by making api call .

But what if it is an internal api endpoint? Like the "localhost:3000/api/hello" api endpoint is being called in page path "localhost:3000/blog/is-there-a-better-way" . As you can see both things reside on "localhost:3000"

Nextjs documentation calls this inefficient and instead actually execute the all required operations from the getServerSideProps code block https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props#getserversideprops-or-api-routes


 
// path path -> src/pages/blog/alternative

export default function InternalApiTest({ data }) {
  //log to browser console
  console.log(data);

  return (
    <>
      <h1>{data.oof}</h1>
    </>
  );
}

const oofObject = { oof: "hello oof" };
/**
 *
 * a better approach
 */
export const getServerSideProps = async () => {
  // you would db related stuff and other operations in real life situations.
  // directly connect to your db and run queries you require within codeblock
  const data = oofObject;

  console.log(data);
  return { props: { data } };
};

  
  
  
  

The inefficient version of the code below .

We have an api endpoint "/api/hello" which is being called from within getServerSideProps function.
Nextjs does recommend to directly execute server side logic getServerSideProps .

// path path -> src/pages/blog/is-there-a-better-way
// api route called -> src/pages/api/hello

export default function InternalApiTest({ data }) {
  //log to browser console
  console.log(data);

  return (
    <>
      <h1>{data.oof}</h1>
    </>
  );
}
/**
 *
 * not the best approach but this does work
 */
export const getServerSideProps = async () => {
  // fetching from internal api -- not the best way
  // https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props#getserversideprops-or-api-routes
  // this inefficient and reduces performance
  const res = await fetch(`http://localhost:3000/api/hello`);

  const data = await res.json();

  console.log(data);
  return { props: { data } };
};








//interal api route /api/hello
const oofObject = { oof: "hello oof" };

// this api route just returns the oofObject
// you would db related stuff and other operations in real life situations
export default function handler(req, res) {
  res.status(200).json(oofObject);
}


Comments

Topics

Show more