Table of Contents
With the introduction of App router in Next.js 13, how routing is handled is changed. In this article, we will see how to read query parameters in Next.js app router.
Accessing query param on the server side
By default Next.js is server side rendered. So to access the query param in page.js
, you can use the following code:
page.js
1export default function Home(props) {2 return (3 <p>Server Side param : {props.searchParams.name}</p>4 );5}
We can use the "use client" directive to specify Next.js that a component should be rendered only in client side. We can access query param in client side as shown below:
GetQueryParam.jsx
1"use client";23import { useSearchParams } from "next/navigation";45export default function GetQueryParam() {6 const searchParams = useSearchParams();7 const param = searchParams.get("name") || "No param set";89 return (10 <div>11 <p>Client Side param : {param}</p>12 </div>13 );14}
Updating the query param
If you want to update the query param, then you can use the useRouter
hook exported by next/navigation
:
UpdateQueryParam.jsx
1"use client";23import { useRouter } from "next/navigation";4import { useState } from "react";56export default function UpdateQueryParam() {7 const router = useRouter();8 const [newValue, setNewValue] = useState("");910 const updateParam = () => {11 router.push(`?name=${encodeURIComponent(newValue)}`);12 };1314 return (15 <div>16 <input17 type="text"18 value={newValue}19 onChange={(e) => setNewValue(e.target.value)}20 placeholder="New param value"21 />22 <button onClick={updateParam}>Update Param</button>23 </div>24 );25}
If you are looking for how to read query params in page router, you can refer to this article.
Do follow me on twitter where I post developer insights more often!
Leave a Comment