1

I have a URL like

bar?id=foo

If I route to this via router.push('bar?id=foo') everything works fine.

But if I go direct to the route in the browser, the query string does not get passed through.

const BarComponent = ()=>{
    console.log(useRouter())
}

This outputs

ServerRouter {
  route: '/bar',
  pathname: '/bar',
  query: {},
  asPath: '/bar',
  basePath: '',
  events: undefined,
  isFallback: false,
  locale: undefined,
  isReady: false,
  locales: undefined,
  defaultLocale: undefined,
  domainLocales: undefined,
  isPreview: false,
  isLocaleDomain: false
}
0

1 Answer 1

3

That's the output you get on the terminal from the server, and shows its default value ({}). On the client, you should see 2 console logs: first one with an empty query object (from SSR) and a second one with your query string in it (from rehydration).

useRouter() is a React Hook so it'll only run/update on the client.

If you want to have access to the query string on the server-side, you'll need to use getServerSideProps and access it through the query param from the context object.

export async function getServerSideProps({ query }) {
    console.log(query) // `{ id: 'foo' }`
    //...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Abit of a rookie question I guess :(
Valid question, and often times generates confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.