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)

Most upvoted comments

Hi, for the query to be populated you must provide it to the href value not just the asPath. 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:

Router.push('/post/[pid]?hello=123', '/post/abc?hello=123')}

Many confusion, still existing.

This will work for single or multiple query params as well dynamic routing:

const query = { param1: 'foo', param2: 'bar' }

const url = { pathname: '/search/[id]', query };

const urlAs = { pathname: '/search/1234', query }

router.push(url, urlAs);

Output:

/search/1234?param1=foo&param2=bar

Aaaah, href is the first parameter so needs to have query parameres - it finally clicked and works as expected now 😃 Thanks @timneutkens ❤️