Error: useRouter only works in Client Components. Add the "use client" directive
`useRouter` (and other client-only hooks like `usePathname`, `useSearchParams`) can only run inside a Client Component. Add `"use client"` as the very first line of the file, or move the navigation logic into a smaller Client Component if the rest of the file needs to stay a Server Component.
What causes this error
Hooks like useRouter, usePathname, and useSearchParams from next/navigation depend on browser APIs and React state that only exist on the client. Server Components have no client-side router instance to hook into, so calling them there fails immediately.
The Fix
'use client'; // must be the very first line of the file
import { useRouter } from 'next/navigation';
export function BackButton() {
const router = useRouter();
return <button onClick={() => router.back()}>Back</button>;
}If most of the file needs to stay server-rendered, isolate just the navigation piece into its own small Client Component instead of converting the whole file.
Common causes / variations
- Missing the
"use client"directive entirely - Having
"use client"present, but not as the literal first line (e.g. after an import or a comment) — Next.js requires it to be first - Trying to read
useSearchParams()in a Server Component instead of awaiting thesearchParamsprop, which is the server-side equivalent
Related errors
See also: Event handlers cannot be passed to Client Component props.
Comments
Loading comments...