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
}
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' }`
//...
}