Why can't I get query params in ```getStaticProps```?

Viewed 14922

I will make it simple:

Link: http://localhost:3000/product/bioCloths?activeCategory=medium&id=0

File path: pages/product/[product].js.

Expected: product: "bioCloths, activeCategory: "medium", id: "0"

using getStaticProps at [product].js:

const ProductDetails = (props) => {
  console.log("initial props", props);

  return <div>product details...</div>
};

export default ProductDetails;

export async function getStaticProps(context) {

  return {
    props: {
     context: context
    },
  };
}

export async function getStaticPaths() {
  return {
    paths: [{ params: { product: "1" } }, { params: { product: "2" } }],
    fallback: true,
  };
}

Props returns: context: params: product: "bioCloths", excluding the query params.

Now if I use the deprecated getInitialProps instead:

ProductDetails.getInitialProps = (context) => {
  const activeCategory = context.query.activeCategory;
  const id = context.query.id;
  const product = context.query.product;

  return {
    activeCategory: activeCategory,
    id: id,
    product: product,
  };
};

props logs activeCategory: "medium" id: "0" product: "bioCloths"

I need to get these all of these props so I can fetch data before the client mounts.

I understand that getInitialProps is now deprecated, but it works. Why is not getStaticProps working, and should I use it instead of serverSideProps?

This is an ecommerce, and there is no way I can set getStaticPaths for hundreds of possibilities, to work along with getStaticProps so I guess that in this case I should use getInitialProps or getServerSideProps?

P.S - getServerSideProps hits me an error stating that it will only accept .json files.

2 Answers

According to one of the maintainers of Nextjs this is the reply for anyone learning this framework:

getStaticProps generates the page at build time. There's no possible way to know the custom query params your visitors can use at build time.

getInitialProps and getServerSideProps can know all the possible query params because the page is generated at runtime, whenever you receive a new request.

You can learn more about the above here.

"

This discussion can be read on Github

If your page uses a dynamic route, params contain the route parameters. For instance, If the page name is [id].js, then params will look as follows:

{ id: /* something */ }

You can get URL params from inside your getStaticProps or getServerSideProps function with the context argument. Here’s an example with getStaticProps:

// pages/[id].js

export async function getStaticProps(context) {
    const { params } = context;
    const id = params.id;

    const data = /* Fetching data with the id */

    return {
        props: data,
    }
}

You can do the same with getServerSideProps:

// pages/[id].js

export async function getServerSideProps(context) {
  const { params } = context;
  const id = params.id;

  /* ... */
}
Related