19

Next.js documentation mentions two ways to access the router object: useRouter for functional components and withRouter for class-based components.

However, it does not mention something I came across a few times which is the Router object accessed as follows, for example:

import Router from 'next/router'

Router.push("/")

Is it correct to use Router in this way? Why doesn't Next.js documentation mention it?

fredperk
  • 737
  • 1
  • 9
  • 22
  • here is one of their examples https://github.com/vercel/next.js/blob/1d643eb6e1cc57faaecf02e6c3c5e1bb463b2027/examples/with-loading/pages/_app.js#L1 but in their docs they use useRouter https://nextjs.org/docs/api-reference/next/router#routerevents – Christian Ã…ke Widlund May 03 '21 at 17:52
  • The difference is that in that example ([github.com/vercel/next.js/...](https://github.com/vercel/next.js/blob/1d643eb6e1cc57faaecf02e6c3c5e1bb463b2027/examples/with-loading/pages/_app.js#L1)) the Router is used outside of the component, so [useRouter](https://nextjs.org/docs/api-reference/next/router#userouter) or [withRouter](https://nextjs.org/docs/api-reference/next/router#withrouter) can not be used. – kca Jun 16 '21 at 11:44

1 Answers1

18

I guess the main suggestion to not use Router.push() or Router.pathname directly from the object itself is because of the way Next.js serves the applications. When you're trying to do:

import Router from 'next/router';

const HomePage = () => {
  console.log(Router.pathname);

  return (
    <div>hi</div>
  )
}

You will receive an error with: You should only use "next/router" inside the client side of your app. This is because of the way next/router works with SSR.

You could however put this in an useEffect and it will work... but that's hacky and you will probably run into issues in the future.

Both useRouter and withRouter are Next.js their solution to this problem. They are both build so they can work with SSR and CSR. So my suggestion is just to use one of these, they work great .

Rowin
  • 206
  • 2
  • 6
  • 5
    see also https://github.com/vercel/next.js/discussions/18522: "...important for concurrent features..." – kca Jun 16 '21 at 11:47