How to get the id of an item from router before page renders in next js.

 To achieve this goal we need to use the getServersideProps() method. more about this method can be found here.

This method can be used to get the id from the utl and pass it to the component as a prop.

eg: 

we have a url which is : http://www.example.dev/posts/{some_id} 


export async function getServerSideProps(context) {

  return {
      props: { class_id: context.query.some_id }, // this will return an onject like
      // {class_id: some_id}
  };

}

You can also use getServersideProps() to make api calls and fetch data before the page gets loaded.


Comments