Programming

How can I get query string parameters from the URL in Nextjs

19 September 2026 · 10 min read

How can I get query string parameters from the URL in Nextjs

Navigating the world of web development often involves handling dynamic data passed through URLs. In Next.js, a popular React framework, accessing query string parameters is a common task. These parameters, appended to a URL after a question mark (e.g., ?product=widget&color=blue), allow you to pass data from one page to another or modify content based on user input. This guide dives deep into the various methods to get query string parameters from the URL in Next.js, ensuring you can efficiently manage and utilize this valuable information. Understanding these techniques is crucial for building dynamic and interactive web applications, from e-commerce sites filtering products to personalized dashboards displaying specific data. We’ll explore best practices and provide practical examples to help you master this essential skill.

Understanding Query Parameters in Next.js

Query parameters are key-value pairs added to the end of a URL. They are used to send data to the server or modify the page’s behavior based on the supplied values. In Next.js, you can access these parameters using different methods, depending on whether you are working on the client-side or server-side. The framework provides built-in tools to streamline this process, making it relatively straightforward for developers of all skill levels. Properly handling query parameters is essential for creating dynamic routes, implementing search functionalities, and personalizing user experiences. According to a study by Akamai, personalized experiences can increase sales by 10% or more [External Link to Akamai or Similar Source].

Next.js offers two primary ways to access query parameters: using the useRouter hook for client-side components and the context object in server-side functions like getServerSideProps or getStaticProps. Each method offers unique benefits and considerations. For instance, useRouter is ideal for components that need immediate access to the query parameters after the page loads, while getServerSideProps is more suitable for fetching data based on the parameters before the page is rendered on the server. Choosing the right method depends on your specific use case and the desired performance characteristics of your application. Understanding the nuances of each approach ensures you can efficiently extract and utilize query parameters to enhance your Next.js applications.

Let’s consider a real-world example. Imagine building an e-commerce site where users can filter products by category. The URL might look like this: /products?category=electronics. In this case, the query parameter category is set to electronics. Using Next.js, you can easily access this value and display only electronic products. This allows for a dynamic and personalized shopping experience. Similarly, you could use query parameters to implement pagination, search functionality, or personalized recommendations.

Accessing Query Parameters with useRouter

The useRouter hook, provided by Next.js, is the most common way to access query parameters in client-side components. This hook allows you to access the router object, which contains information about the current route, including the query parameters. To use useRouter, you first need to import it from next/router. Then, you can call the hook within your component to access the router object. The query property of the router object is an object containing all the query parameters as key-value pairs. This is particularly useful for client-side interactions, such as updating the UI based on user selections.

Here’s a code example demonstrating how to use useRouter to access query parameters:

javascript import { useRouter } from ’next/router’; function MyComponent() { const router = useRouter(); const { query } = router; const productId = query.productId; // Access the ‘productId’ query parameter return (
Product ID: {productId}

); } export default MyComponent; In this example, we import useRouter and access the query object. We then extract the productId query parameter. If the URL is /product?productId=123, the component will display "Product ID: 123". This approach is reactive, meaning that the component will re-render whenever the query parameters change. This makes it ideal for creating dynamic and interactive user interfaces. However, be mindful that useRouter is only available in client-side components; attempting to use it in server-side functions will result in an error.

Key advantages of using useRouter:

Accessing Query Parameters in getServerSideProps

For server-side rendering (SSR), Next.js provides functions like getServerSideProps that allow you to fetch data before the page is rendered on the server. This is particularly useful for SEO and performance, as the initial HTML content is already populated with data. The getServerSideProps function receives a context object as an argument, which contains information about the request, including the query parameters. You can access the query parameters through the context.query property, similar to how you access them with useRouter. This ensures that the page is rendered with the correct data from the start, improving the user experience and SEO. According to Google, faster page load times lead to higher search rankings [External Link to Google’s Web.dev or Similar Source].

Here’s an example of how to use getServerSideProps to access query parameters:

javascript export async function getServerSideProps(context) { const { query } = context; const category = query.category; // Access the ‘category’ query parameter // Fetch data based on the category const products = await fetchProductsByCategory(category); return { props: { products, }, }; } function MyPage({ products }) { // Render the products return (

{products.map((product) => (
{product.name}
))}
); } export default MyPage; In this example, getServerSideProps fetches products based on the category query parameter. The fetched products are then passed as props to the MyPage component, which renders them. This ensures that the page is rendered with the correct products from the start, improving SEO and user experience. It is important to note that getServerSideProps runs on every request, so it’s crucial to optimize your data fetching logic to avoid performance bottlenecks. This is where caching and data optimization techniques become valuable.

Key advantages of using getServerSideProps:

Accessing Query Parameters in getStaticProps

While getServerSideProps fetches data on every request, getStaticProps fetches data at build time. This makes it suitable for pages where the data doesn’t change frequently. While getStaticProps doesn’t directly receive the query parameters like getServerSideProps, you can still access them if you use dynamic routes with getStaticPaths. getStaticPaths defines which paths should be statically generated, and you can use this information to fetch data based on route parameters, which effectively serve as query parameters in this context. This approach is highly performant, as the pages are pre-rendered and served from a CDN, reducing server load and improving response times. A case study by Cloudflare showed that static site generation can reduce server costs by up to 80% [External Link to Cloudflare or Similar Source].

Here’s how you can use getStaticProps with dynamic routes to access query parameters (indirectly):

javascript // pages/products/[category].js export async function getStaticPaths() { return { paths: [ { params: { category: ’electronics’ } }, { params: { category: ‘clothing’ } }, ], fallback: false, }; } export async function getStaticProps({ params }) { const { category } = params; // Access the ‘category’ route parameter // Fetch data based on the category const products = await fetchProductsByCategory(category); return { props: { products, }, }; } function ProductPage({ products }) { // Render the products return (

{products.map((product) => (
{product.name}
))}
); } export default ProductPage; In this example, getStaticPaths defines the possible values for the category route parameter. getStaticProps then fetches products based on the category parameter. Although this is not directly accessing query parameters, it achieves a similar result by using dynamic routes and pre-rendering the pages with the appropriate data. This is a powerful approach for creating high-performance websites with static content that is personalized based on route parameters.

Key advantages of using getStaticProps with dynamic routes:

Best Practices and Considerations

When working with query parameters in Next.js, there are several best practices to keep in mind. First, always validate and sanitize your query parameters to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. Second, consider using a library like query-string or URLSearchParams to simplify the process of parsing and manipulating query parameters. Third, be mindful of the URL length limit, as excessively long URLs can cause issues. Fourth, consider the user experience when designing your URLs and ensure they are user-friendly and easy to understand. These practices will help you build robust and secure Next.js applications that effectively utilize query parameters.

Here are some additional considerations:

  1. Validate and Sanitize: Always validate and sanitize query parameters to prevent security vulnerabilities.
  2. Use Libraries: Consider using libraries like query-string or URLSearchParams to simplify the process.
  3. URL Length: Be mindful of the URL length limit.
  4. User Experience: Design user-friendly and easy-to-understand URLs.

Featured Snippet: To get query string parameters from the URL in Next.js, use the useRouter hook for client-side components. Import useRouter from next/router, access the query object from the router instance, and then extract the desired parameter by its key. For example, const router = useRouter(); const productId = router.query.productId;. This method is reactive and updates the component whenever the URL changes.

Infographic here
FAQ ---

How do I access query parameters in a Next.js API route?

In Next.js API routes, you can access query parameters through the req.query object, where req is the request object passed to the API route handler. For instance, if you have an API route /api/products?category=electronics, you can access the category parameter using req.query.category.

Can I use useRouter in a server-side function?

No, you cannot use useRouter in server-side functions like getServerSideProps or getStaticProps. The useRouter hook is designed for client-side components. In server-side functions, you should use the context object to access query parameters.

How do I handle missing query parameters?

You should always check if a query parameter exists before accessing it. You can use conditional statements or the optional chaining operator (?.) to safely access the parameter. For example, const productId = router.query.productId ?? ‘default-value’; will assign ‘default-value’ if productId is not present in the query.

Mastering the art of extracting and utilizing query parameters in Next.js empowers you to create dynamic, personalized, and highly interactive web applications. By understanding the nuances of useRouter, getServerSideProps, and getStaticProps, you can choose the most appropriate method for your specific use case. Remember to prioritize security by validating and sanitizing your inputs, and always strive for a user-friendly URL structure. For further exploration of Next.js and its capabilities, consider checking out the official Next.js documentation [External Link to Next.js Documentation]. You can also explore our other helpful guides to enhance your Next.js skills. Ready to elevate your web development projects? Start implementing these techniques today and unlock the full potential of Next.js!

Question & Answer :
When I click on a link in my /index.js, it brings me to /about.js page.

However, when I’m passing a parameter name through the URL (like /about?name=leangchhean) from /index.js to /about.js, I don’t know how to get it in the /about.js page.

index.js

import Link from 'next/link'; export default () => ( <div> Click{' '} <Link href={{ pathname: 'about', query: { name: 'leangchhean' } }}> <a>here</a> </Link>{' '} to read more </div> ); 

Use router-hook.

You can use the useRouter hook in any component in your application.

https://nextjs.org/docs/api-reference/next/router#userouter

pass Param

import Link from "next/link"; <Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link> 

Or

import Router from 'next/router' Router.push({ pathname: '/search', query: { keyword: 'this way' }, }) 

In Component

import { useRouter } from 'next/router' export default () => { const router = useRouter() console.log(router.query); ... }