next.js: Router.query is empty on subsequent client navigation events
Bug report
Describe the bug
Using Next 9’s routing solution for a Universal App, “router.query” for post-SSR client-side navigation is never populated even if asPath contains a query string for any of the following
router access methods:
import { SingletonRouter, useRouter, withRouter } from 'next/router';
To Reproduce
Perform an initial navigation to /search?term=hello, the server rendered page’s router information contains a populated “query”:
const router = useRouter();
console.log({ router }); // asPath: "/search?term=hello", pathname: "/search", query: { term: "hello" }
Then navigate to the same pathname, with a different query string: /search?term=bye. At this point Router empties “query”, but has the correct new asPath:
const router = useRouter();
console.log({ router }); // asPath: "/search?term=hello", pathname: "/search", query: {}
Expected behavior
For the client side navigation to a route with specified query parameters such as /search?term=bye, router.query contains the parsed query string.
If this is not expected, it would be helpful to better document this behavior and the correct approach on the client. I would prefer to always access routing information off of the available hook / HOC rather than off window on the client to avoid a split-brain solution between the client and the server.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 6
- Comments: 15 (7 by maintainers)
Hi, for the
queryto be populated you must provide it to thehrefvalue not just theasPath. It does look like this needs to be updated in our docs to better explain this so thanks for bringing that to our attention!Works in the same way as the earlier reply:
Many confusion, still existing.
const query = { param1: 'foo', param2: 'bar' }const url = { pathname: '/search/[id]', query };const urlAs = { pathname: '/search/1234', query }router.push(url, urlAs);/search/1234?param1=foo¶m2=barAaaah,
hrefis the first parameter so needs to have query parameres - it finally clicked and works as expected now 😃 Thanks @timneutkens ❤️