How to Fix Dynamic Server Usage Error in Next.js
Why This Happens
This error occurs because Next.js separates server and client components. Server components can use server-only features like database calls or environment variables. Client components run in the browser and cannot access these server-only features. If you try to use server code inside a client component, Next.js throws a dynamic server usage error.
"use client"; import { getServerSideData } from '../lib/serverData'; export default function MyComponent() { const data = getServerSideData(); // This is server-only code return <div>{data.message}</div>; }
The Fix
To fix this, separate server and client code. Move server-only logic to a server component or API route. Mark components that run in the browser with "use client" at the top. Fetch server data in server components or via API calls, then pass it down as props to client components.
// Server component (no "use client") import { getServerSideData } from '../lib/serverData'; export default async function MyServerComponent() { const data = await getServerSideData(); return <MyClientComponent data={data} />; } // Client component "use client"; export function MyClientComponent({ data }) { return <div>{data.message}</div>; }
Prevention
Always mark components that use browser features with "use client". Keep server-only code like database queries or environment variables inside server components or API routes. Use Next.js linting rules to catch improper imports. Structure your app to clearly separate server and client logic to avoid this error.
Related Errors
- Invalid Hook Call: Happens if React hooks are used in server components.
- Module Not Found: Occurs if server-only modules are imported incorrectly in client code.
- Hydration Mismatch: Caused by differences between server and client rendered output.