Understanding Query Parameters
Query parameters are a common way to pass data to web pages via the URL. They appear after a question mark (?
) in the URL, consisting of key-value pairs separated by ampersands (&
). For example, in the URL https://example.com/about?name=leangchhean&age=30
, name
and age
are query parameters. This is a useful technique for passing dynamic data without altering the core page route.
In Next.js, accessing these query parameters is essential for building dynamic and interactive web applications. This tutorial covers several methods to retrieve query parameters based on your Next.js version and component type (Server Components, Client Components, or older approaches).
Passing Query Parameters
Before we delve into accessing parameters, let’s quickly review how to pass them. The next/link
component is the preferred way to navigate between pages in a Next.js application. You can include query parameters when creating the href
object:
import Link from 'next/link';
<Link href={{ pathname: '/about', query: { name: 'leangchhean', age: '30' } }}>
<a>Learn More</a>
</Link>
This will generate a link to https://example.com/about?name=leangchhean&age=30
.
Accessing Query Parameters in Next.js
Here are different methods for accessing query parameters, depending on your Next.js version and component type.
1. Using useRouter
(Client Components)
The useRouter
hook from next/router
is the primary way to access query parameters in Client Components. This hook provides access to the router object, which includes a query
property containing all query parameters as an object.
'use client' // Important: designates this as a Client Component
import { useRouter } from 'next/navigation';
export default function AboutPage() {
const router = useRouter();
const { name, age } = router.query;
return (
<div>
<h1>About Page</h1>
{name && <p>Name: {name}</p>}
{age && <p>Age: {age}</p>}
</div>
);
}
Explanation:
'use client'
designates the component as a Client Component. This is necessary to use theuseRouter
hook.useRouter()
returns the router object.router.query
is an object containing the query parameters. You can access them using dot notation or destructuring.
2. Using useSearchParams
(Client Components – Recommended for App Router)
In Next.js 13 and later, especially when using the App Router, useSearchParams
is the preferred method for accessing query parameters in Client Components. It offers a more streamlined approach.
'use client'
import { useSearchParams } from 'next/navigation';
export default function AboutPage() {
const searchParams = useSearchParams();
const name = searchParams.get('name');
const age = searchParams.get('age');
return (
<div>
<h1>About Page</h1>
{name && <p>Name: {name}</p>}
{age && <p>Age: {age}</p>}
</div>
);
}
Explanation:
useSearchParams()
returns aURLSearchParams
object.searchParams.get('parameterName')
retrieves the value of a specific query parameter. It returnsnull
if the parameter is not present.
3. Using getStaticProps
or getServerSideProps
(Server Components/Pages Router)
If you are working with Server Components (or using the Pages Router with getStaticProps
or getServerSideProps
), you can access query parameters through the query
property of the context object.
export async function getServerSideProps({ query }) {
const { name, age } = query;
return {
props: {
name,
age,
},
};
}
export default function AboutPage({ name, age }) {
return (
<div>
<h1>About Page</h1>
{name && <p>Name: {name}</p>}
{age && <p>Age: {age}</p>}
</div>
);
}
Explanation:
getServerSideProps
(orgetStaticProps
) receives a context object as an argument.- The
query
property of the context object contains the query parameters. - The query parameters are then passed as props to the component.
4. Handling Static Exports and router.asPath
(For Specific Scenarios)
In rare scenarios where you are working with static exports and need to access query parameters, you might need to manually parse the router.asPath
string. This is because router.query
might not be available in a static export context.
This approach involves:
- Using
router.asPath
to get the full URL path, including query parameters. - Parsing the query string manually or using a library like
query-string
.
This is an advanced technique and should only be used when necessary.
Best Practices
- Choose the appropriate method: Use
useRouter
oruseSearchParams
for Client Components, andgetServerSideProps
orgetStaticProps
for Server Components. - Type safety: Consider using TypeScript to add type safety to your query parameters.
- Error handling: Always handle cases where query parameters are missing or have invalid values.
- Data validation: Validate any data received from query parameters before using it in your application.