Design Converter
Education
Last updated on Nov 28, 2024
•5 mins read
Last updated on Nov 29, 2024
•5 mins read
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.
1export async function getServerSideProps(context) { 2 const { query } = context; // Access the query object 3 const category = query.category || 'all'; // Default value 4 const page = query.page || 1; 5 6 // Fetch data based on query parameters 7 const res = await fetch(`https://api.example.com/products?category=${category}&page=${page}`); 8 const data = await res.json(); 9 10 return { 11 props: { data }, // Pass data to the page 12 }; 13} 14 15const ProductsPage = ({ data }) => { 16 return ( 17 <div> 18 <h1>Products</h1> 19 <pre>{JSON.stringify(data, null, 2)}</pre> 20 </div> 21 ); 22}; 23 24export 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:
1export async function getServerSideProps({ params }) { 2 const { id } = params; // Access the dynamic route parameter 3 const res = await fetch(`https://api.example.com/products/${id}`); 4 const data = await res.json(); 5 6 return { props: { data } }; 7} 8 9const ProductPage = ({ data }) => { 10 return ( 11 <div> 12 <h1>{data.name}</h1> 13 <p>{data.description}</p> 14 </div> 15 ); 16}; 17 18export 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.
1import { useRouter } from "next/router"; 2 3const ClientComponent = () => { 4 const router = useRouter(); // Access the router object 5 const { query } = router; // Access the query object 6 7 return ( 8 <div> 9 <h1>Query Parameters</h1> 10 <pre>{JSON.stringify(query, null, 2)}</pre> 11 </div> 12 ); 13}; 14 15export 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"use client"; 2 3import { useSearchParams } from "next/navigation"; 4 5const SearchParamsComponent = () => { 6 const searchParams = useSearchParams(); // Access the search params prop 7 const category = searchParams.get("category"); 8 const page = searchParams.get("page"); 9 10 return ( 11 <div> 12 <h1>Category: {category}</h1> 13 <h1>Page: {page}</h1> 14 </div> 15 ); 16}; 17 18export 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:
1export async function getServerSideProps({ query }) { 2 const filters = query.filter || []; // Access multiple values as an array 3 console.log(filters); // ['red', 'blue'] 4 5 return { props: { filters } }; 6}
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.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.