nextjs module_error ai_generated true

Error: This module cannot be imported from a Server Component module. It should only be used from a Client Component.

ID: nextjs/server-component-import-client-side-only-module

Also available as: JSON · Markdown · 中文
90%Fix Rate
87%Confidence
1Evidence
2023-05-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Next.js 13.4.0 active
Next.js 14.0.0 active
Next.js 14.2.0 active

Root Cause

A module that uses browser-only APIs (e.g., window, document) or is marked with 'use client' at the module level is imported into a Server Component, which runs on the server where those APIs don't exist.

generic

中文

一个使用浏览器专用 API(如 window, document)或在模块级别标记了 'use client' 的模块被导入到服务器组件中,而服务器组件在服务器上运行,这些 API 不存在。

Official Documentation

https://nextjs.org/docs/app/building-your-application/rendering/server-components#third-party-packages

Workarounds

  1. 95% success Use dynamic import with ssr: false to load the module only on the client: 'const MyComponent = dynamic(() => import('./MyClientComponent'), { ssr: false })'.
    Use dynamic import with ssr: false to load the module only on the client: 'const MyComponent = dynamic(() => import('./MyClientComponent'), { ssr: false })'.
  2. 90% success Create a wrapper Client Component that imports the module and pass props from the Server Component.
    Create a wrapper Client Component that imports the module and pass props from the Server Component.
  3. 70% success If the module is small, refactor it to avoid browser APIs and make it usable on the server.
    If the module is small, refactor it to avoid browser APIs and make it usable on the server.

中文步骤

  1. Use dynamic import with ssr: false to load the module only on the client: 'const MyComponent = dynamic(() => import('./MyClientComponent'), { ssr: false })'.
  2. Create a wrapper Client Component that imports the module and pass props from the Server Component.
  3. If the module is small, refactor it to avoid browser APIs and make it usable on the server.

Dead Ends

Common approaches that don't work:

  1. 60% fail

    This converts the entire Server Component to a Client Component, losing server-side benefits and potentially causing other issues.

  2. 70% fail

    The module may still use browser APIs internally; removing the directive doesn't make the code run on the server.

  3. 80% fail

    Dynamic import alone still runs on the server during SSR; use ssr: false to disable server-side rendering.