Skip to main content

GetServerSideProps(context) - Example - NextJs

 GetServerSideProps(context) - NextJs example

getServerSideProps-context-query-param-nextjs

GetServerSideProps is executed in the server side but what if we want to access the resolved url , params or query attached to the url ?

This is when "context" parameter of getServerSideProps is used . 

Context is an object so we de-structure the items we want like the usual way. It contains several useful values:

  • query - with this we can get the queries attached to current url . Example - "localhost:3000/?search="oof"" , using the context we can access the query ({search:"oof"}) from the server side & execute operations. (note: query object can also hold the param value if it exists.)
  • params- get the params data if it exists on server side. The params would still follow the dynamic route set key name . For example if a dynamic route page like "pages/post/[id].js" , the param would be stored as {id:1}.(like the useRouter)
  • resolvedUrl - stripped down version of requested url with paths & queries . For example if requested url is "localhost:3000/oof?oof=true" then the resolvedUrl would be "/oof?oof=true" . 

There are several more properties such as : 

req, res, preview, previewData, locale, locales & defaultLocal .

Query & params would be the most used ones , so covered only those. But based on current requirement other properties  inside the getserversideprops "context" object might come in handy as well.


 Getserversideprops(context) - example code



// file path "pages/post/[id].js"
// client side accessed path - assuming it is "localhost:3000/post/69?search=oof"
// param would hold {id:69}// query would hold {search:"oof"}

export default function Home({ pageNumber }) {
  //log to browser console  console.log(pageNumber); 
  return (
    <>
      <div className="oof">
        <h3>Current page number is :{pageNumber}</h3>
      </div>
    </>
  );}

// This gets called on every request
export const getServerSideProps = async (context) => {
  const { query, params, resolvedUrl } = context;
  // log to the terminal
  console.log("query", query);
  console.log("params", params);
  console.log("resolvedUrl", resolvedUrl);
  // const pageNumber = params?.id; --> this will returned undefined if there are no id params.
  const pageNumber = params?.id ? params?.id : null;
  //properly handles undefined cases -> sets null as value if undefined
  // Pass data to the page via props  // make sure this is not undefined otherwise might throw serializing error.
  //handle properly
  return { props: { pageNumber } };
};

Comments

Topics

Show more