Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access query params inside getServerSideProps in Next.js?

I am trying to use get getServerSideProps in my code and I am not able to do it because I am not able to pass router.query.itmid.

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const router = useRouter();
  var id = router.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}

Here is what I tried https://codesandbox.io/s/youthful-lucy-427g1?file=/src/App.js

I am new to Next.js and and I have no much knowledge of Next.js so please don't tell me to read the docs if I understand the docs I wouldn't be asking this question.

like image 885
vivek kn Avatar asked Jul 14 '26 00:07

vivek kn


1 Answers

You should use context in getServerSideProps to get query params

export async function getServerSideProps(ctx) {
  // Call an external API endpoint to get posts
  var id = ctx.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
like image 199
iamhuynq Avatar answered Jul 16 '26 15:07

iamhuynq