In Next.js, a common method to attach query parameters to dynamic routes is by using the Link component or programmatic navigation (using router.push or router.replace).
Using the Link Component
When using the Next.js Link component, you can pass query parameters as an object to the href prop. For example, if you have a dynamic route [id].js, you can create a link like this:
jsximport Link from 'next/link'; const MyComponent = () => { return ( <Link href={{ pathname: '/post/[id]', query: { foo: 'bar' } }} as="/post/123?foo=bar"> <a>Go to Post</a> </Link> ); };
In this example, pathname represents the route pattern, and the query object contains the parameters you want to attach. The as attribute specifies the URL displayed in the browser address bar, which may include query parameters.
Using Programmatic Navigation
If you need to trigger navigation programmatically, use the Next.js useRouter hook to access the router object and call push or replace methods.
jsximport { useRouter } from 'next/router'; const MyComponent = () => { const router = useRouter(); const goToPost = () => { router.push({ pathname: '/post/[id]', query: { foo: 'bar' }, }, '/post/123?foo=bar'); }; return ( <button onClick={goToPost}>Go to Post</button> ); };
Here, the structure of pathname and query objects matches that used with the Link component. The second parameter of router.push defines the URL shown in the browser address bar.
Important Notes
- In the
Linkcomponent orrouter.push/router.replace, thequeryparameter is optional. You can provide only the dynamic route path without query parameters. - When directly specifying query parameters in the
asattribute or the second parameter ofrouter.push/router.replace, ensure the URL is properly encoded, especially when parameter values contain special characters. - In dynamic route pages, access these query parameters via the
queryobject of theuseRouterhook.
Here's an example of retrieving query parameters in a dynamic route page:
jsximport { useRouter } from 'next/router'; const PostPage = () => { const router = useRouter(); const { id, foo } = router.query; return ( <div> <h1>Post: {id}</h1> <p>Query Parameter: {foo}</p> </div> ); }; export default PostPage;
This code demonstrates how to use the query object of useRouter in the PostPage dynamic route to retrieve both route parameters and query parameters.