3

New to NextJS.

I want to check if the current URL is the home page.

If I use

import { useRouter } from "next/router";

const router = useRouter();
const is_home = (router.pathname === '');

I get a front end error

You have a Server Component that imports next/router. Use next/navigation instead.

If I change

import { useRouter } from "next/router";

to

import { useRouter } from "next/navigation";

I get a terminal error

Error: useRouter only works in Client Components. Add the "use client" directive at the top of the file to use it.

If I add "use client" to the top of the file, the terminal error goes away, but pathname in router.pathname is highlighted red in VS Code, and the hover error is

Property 'pathname' does not exist on type 'AppRouterInstance'.ts(2339)..

I can't find any documentation for next/navigation like there is for next/router.

Is there a simpler way to check for the home page?

I want to assign a default meta description for the home page, and assign the post excerpt (initally) as the meta description if the current URL is not the home page.

Steve
  • 2,066
  • 13
  • 60
  • 115
  • Hi Steve! Your question is very likely to be a duplicate of the linked thread. Let us know if it's not, and we will consider reopening it. – Youssouf Oumar Apr 30 '23 at 06:53

1 Answers1

1

If you try to use useRouter in a component that is being rendered on the server-side, you will get this error. To resolve this error, you need to make sure that the component is only rendered on the client-side.

One way to do this is by using the dynamic import function from next/dynamic to load the component asynchronously on the client-side.

    import dynamic from 'next/dynamic';

    const DynamicComponent = dynamic(() => import('../components/MyComponent'), {
      ssr: false, // set ssr to false to render only on the client-side
    });
   

and render it normally like you normally return jsx:

    return (   
          <DynamicComponent /> 
      );

OR if you want to render this component on serverside use getServerSideProps like this:

    export async function getServerSideProps(ctx) {
      const isHome = ctx.req.url === '/';

      return {
        props: {
          isHome
        }
      };
    }
   
   

and use the isHome prop like this:

  const HomePage = ({ isHome })=> (
    <>
      { isHome ? <h1>Welcome to the home page!</h1>: <h1>This is not the home page.</h1>}
    </>
  )

  export default HomePage;
Rupali Yadav
  • 121
  • 4