Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am using the new app Router in nextjs .getting Error:useRouter only works in Client Components. Add the "use client" directive to use it [duplicate]

./app/layout.tsx
ReactServerComponentsError:

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

Import trace:
  ./app/layout.tsx

if i remove use useRouter and use useNavigation then i get the following

Error: (0 , next_navigation__WEBPACK_IMPORTED_MODULE_2__.useNavigation) is not a function

Source
app/layout.tsx (18:30) @ useNavigation

  16 | children: React.ReactNode
  17 | }) {
> 18 | const router = useNavigation()
     |                            ^
  19 | 
  20 | const excludeHeader = router.pathname.startsWith('/admin')

if i add the use client on top of the file ,i get the following error

You are attempting to export "metadata" from a component marked with "use client", which is disallowed. Either remove the export, or the "use client" directive. Read more: https://beta.nextjs.org/docs/api-reference/metadata

    ,-[/Users/veerpratap/Desktop/nodejs-projects/my-Next-apps/product-reviews/app/layout.tsx:5:1]
  5 | import MainHeader from './layout/main-header'
  6 | const inter = Inter({ subsets: ['latin'] })
  7 | 
  8 | export const metadata = {
    :              ^^^^^^^^
  9 |   title: 'Create Next App',
 10 |   description: 'Generated by create next app',
 11 | }

any way i can resolve this error

like image 805
Veer Pratap Avatar asked Jan 29 '26 07:01

Veer Pratap


2 Answers

This worked for me,

import { usePathname } from "next/navigation";
const pathname = usePathname();

useRouter from next/navigation doesn't export pathname etc anymore, as mentioned in the linked docs right before the Router Events section

like image 199
Can Rau Avatar answered Jan 31 '26 22:01

Can Rau


For server files (like APIs), if you want the named param of the path like /users/[slug]/route.ts, use useParams(), like

import { useParams } from 'next/navigation'


export async function GET(request: Request) {
  const { slug } = useParams() as { slug: string }
  ...

Doesn't seem to be documented anywhere in nextJS. I got it from the source code. Thank God for typescript!

like image 28
Vedant Agarwala Avatar answered Jan 31 '26 22:01

Vedant Agarwala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!