Sling Academy
Home/Next.js/Next.js: Parsing Query String Parameters

Next.js: Parsing Query String Parameters

Last updated: January 09, 2023

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);

/*...*/

For more completeness and clarity, see the example below.

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 below:

That’s it. Happy coding!

Next Article: How to Create a Custom 404 (Not Found) Page in Next.js

Previous Article: How to programmatically navigate in Next.js

Series: Next.js Navigation and Routing

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported