
Build 10x products in minutes by chatting with AI - beyond just a prototype.
How to get query params in server-side Next.js?
Can we use query params in GET request?
Query parameters are vital in web development, especially when building dynamic, interactive applications. In Next.js, managing query parameters becomes even more essential because of its hybrid nature of server-side rendering (SSR) and client-side capabilities.
This blog dives into how to get query parameters on the server side in Next.js, providing examples, clear explanations, and practical use cases.
Whether you're working with dynamic routes, handling a query object, or parsing a query string, this guide covers everything you need to know about efficiently accessing and using query parameters in Next.js.
Query parameters are key-value pairs appended to a URL after a question mark (?). They allow you to pass values to the server or client for filtering, sorting, and dynamic content rendering.
For example, in the URL https://example.com/products?category=books&page=2, category=books and page=2 are the query parameters.
Handling query parameters server side enables you to fetch and pre-render data during the initial render, ensuring the application loads with all the necessary content upfront. This approach is crucial for SSR applications, where SEO and performance are priorities.
Next.js offers several ways to work with query parameters server side:
• Parsing the query string during server side rendering.
• Using dynamic routes to handle url parameters.
• Leveraging the app directory and app router for advanced server components.
To access query parameters, you can use both server-side and client-side methods. Let’s start with server-side approaches.
The getServerSideProps function allows you to fetch data and handle query parameters during the initial render. The query object is part of the context parameter passed to this function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24export async function getServerSideProps(context) { const { query } = context; // Access the query object const category = query.category || 'all'; // Default value const page = query.page || 1; // Fetch data based on query parameters const res = await fetch(`https://api.example.com/products?category=${category}&page=${page}`); const data = await res.json(); return { props: { data }, // Pass data to the page }; } const ProductsPage = ({ data }) => { return ( <div> <h1>Products</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }; export default ProductsPage;
Here, the query object contains all the query parameters parsed from the url's query string.
Dynamic routes in Next.js allow you to define a file structure that maps directly to url parameters. You can then access these parameters in the server-side functions.
Given a file structure like:
1/pages/products/[id].js
You can access the dynamic param as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18export async function getServerSideProps({ params }) { const { id } = params; // Access the dynamic route parameter const res = await fetch(`https://api.example.com/products/${id}`); const data = await res.json(); return { props: { data } }; } const ProductPage = ({ data }) => { return ( <div> <h1>{data.name}</h1> <p>{data.description}</p> </div> ); }; export default ProductPage;
This approach is helpful when working with dynamic routes and server-side rendering.
If your application requires client-side interactivity, you can use the useRouter hook to access query parameters in a client component.
The useRouter hook from Next.js allows you to access the router object, including the query parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15import { useRouter } from "next/router"; const ClientComponent = () => { const router = useRouter(); // Access the router object const { query } = router; // Access the query object return ( <div> <h1>Query Parameters</h1> <pre>{JSON.stringify(query, null, 2)}</pre> </div> ); }; export default ClientComponent;
Here, the query object contains all parameters from the URL.
If you're using the app directory, the useSearchParams hook is a modern way to handle query string parameters in client components.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18"use client"; import { useSearchParams } from "next/navigation"; const SearchParamsComponent = () => { const searchParams = useSearchParams(); // Access the search params prop const category = searchParams.get("category"); const page = searchParams.get("page"); return ( <div> <h1>Category: {category}</h1> <h1>Page: {page}</h1> </div> ); }; export default SearchParamsComponent;
In a Next.js application, you can combine server components and client components to handle query parameters efficiently. Use server-side rendering for SEO-critical content and client-side logic for interactivity.
If your query string contains multiple values for a single key (e.g., ?filter=red&filter=blue), you can process them as arrays:
1 2 3 4 5 6export async function getServerSideProps({ query }) { const filters = query.filter || []; // Access multiple values as an array console.log(filters); // ['red', 'blue'] return { props: { filters } }; }
Pagination: Pass page and limit query parameters for paginated content.
Filters and Search: Use category or search parameters to refine data.
Dynamic Routes: Enhance your dynamic routes with additional url params.
In this "Next.js Get Query Params Server Side Guide," we’ve explored how to access and use query parameters in both server-side and client-side scenarios. You can create robust and dynamic applications that efficiently handle query parameters by leveraging tools like getServerSideProps, dynamic routes, and the useRouter hook.
Understanding how to properly access query parameters is crucial for building scalable and maintainable applications in Next.js. Whether you're parsing a query string on the server side or interacting with the client, this guide equips you with the knowledge to manage query parameters effectively.