import Router from ‘next/router’ is it ok?

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 🙂.

Leave a Comment