Client-only APIs in a Server Component

next/server-hookserrorreactnextjs-16correctness

Why it matters

Server Components render once on the server: React state/effect hooks, Next navigation hooks and browser globals (window, document, localStorage…) do not exist there. Next.js fails the build for hooks and the render crashes for browser globals.

Fix

Move the interactive part into a "use client" component and render it from the Server Component, or guard the browser access with typeof window !== "undefined".

Credit

  • From the React team

    Server Components render ahead of time on the server and cannot use state, effects or browser APIs; interactivity needs a 'use client' boundary.

  • From the Next.js team

    Documents which hooks and browser APIs belong in Client Components and how to split them off with 'use client'.

References

See it