Handling Params and Queries in Next.js 14

Read time: 1 minutes

User Profile

Wali Ullah

May 18, Sat

Next.js 13 introduces improvements in handling dynamic routes and parameters, making it even easier to build dynamic and personalized experiences for our users.

Params and Dynamic Pages

Here is how we can pass a parameter to the dynamic page path in the Link Component:

<Link href={`/path/${id}`}></Link>


Now, we have to create a dynamic route and access the id there. Simply go to the app directory and create a page with the syntax [id]/page.js

Inside the page, you can now access that id with the useParams hook:

const params = useParams();
const { id } = params;

Now you can use this id to fetch data from the server or perform any desired actions with it. The page is now dynamic.


Query a Parameter

We can query a parameter to a specific page that will be shown in the URL and accessed on that page. Here is how we can do this:

<Link href={`/path?id=${id}`}></Link>

Pro Tip

The hooks are only usable in the client component. So, what if you want to access these parameters in a server-side component? For that, Nextjs gives us a very easy way to do it.

In the page component props, we have searchParams and params, then we can use these props to access parameters and query parameters:


const Page = async ({ params: { id }, searchParams }) => {    
return (
// JSX
);
}


Interested in Publishing your knowledge and sharing it with the world?

Or ask anything about our services

We thrive by partering with visionary brands and driven individuals.

Say hello 👋

[email protected]