Dan
Dan

Reputation: 29375

How do I route with query string params in Next.js?

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
}

Upvotes: 1

Views: 3322

Answers (1)

juliomalves
juliomalves

Reputation: 50368

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

Upvotes: 3

Related Questions