Next.js: Parsing Query String Parameters

Last updated on December 3, 2021 A Goodman Loading... 2 comments

In Next.js, you can get the query string parameters of a URL by using the useRouter hook, like this:

import { useRouter } from "next/router";

/*...*/

const router = useRouter();
const queryParams = router.query;
console.log(queryParams);

/*...*/

Example

Let’s say you have a products page with the following code:

// pages/product.js
import { useRouter } from "next/router";
import { useEffect } from "react";

const Products = () => {
  const router = useRouter();

  // Check whether router.query is empty {} or not
  if (Object.keys(router.query).length !== 0) {
    const queryParams = router.query;
    console.log(queryParams);
    console.log("Search", queryParams.search);
    console.log("Page", queryParams.page);
    console.log("Limit", queryParams.limit);
  }

  return (
    <div style={styles.center}>
      <h1>Products</h1>
    </div>
  );
};

export default Products;

const styles = {
  center: {
    width: "100%",
    height: "100vh",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  },
};

Now when you go to:

http://localhost:3000/products?search=abc&page=1&limit=10&sort=id&order=desc

Check your console and you will see:

{search: "abc", page: "1", limit: "10", sort: "id", order: "desc"}
Search abc
Page 1
Limit 10

This result is the same as the screenshot at the top of the post described.

What’s Next?

If you’d like to learn more about Next.js and modern React, take a look at the following:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
nisi
nisi
2 days ago

found out that the problem is in sharp sign in url string except of question mark. thanks!

You May Also Like