next.js icon indicating copy to clipboard operation
next.js copied to clipboard

CommonJS and ESM modules cause SSR and CSR rendering issues with react contexts when using a custom lib

Open PBug90 opened this issue 1 year ago • 0 comments

Link to the code that reproduces this issue

https://github.com/datrycs/nextjs-library-esm-cjs-ssr-issues

To Reproduce

  1. Navigate to sample-lib folder
  2. Install deps using yarn install
  3. Use yarn build and yalc publish to publish the package
  4. Navigate to nextjs-project folder
  5. Use yalc add sample-lib in nextjs-project to make the published package available
  6. Install deps using yarn install
  7. Start the environment using yarn dev
  8. Navigate to http://localhost:3000/example_with_lib to see the error
  9. Navigate to http://localhost:3000/example_without_lib to see it working
  10. Use export ANALYZE=true and restart the dev server so you can inspect webpack bundles

Current vs. Expected behavior

Currently, we are trying to use @commercelayer/react-components as part of an internal custom library. When we bundle the library with CJS and ESM exports and reuse it in our nextjs project, SSR fails with context not found issues. We think this has to do with CJS/ESM module resolution on the server side when doing the initial SSR rendering.

The example repo includes two cases where we use a Commercelayer component called LineItemsContainer. LineItemsContainer provides a context that is consumed by a different Commercelayer component further down the tree.

The working case imports LineItemsContainer directly from the node_modules folder and works correctly in SSR and on the client.

The error case imports a custom component from a self hosted npm package that wraps LineItemsContainer as a child, but for some reason SSR and CSR fail in this case. The expected behavior is that the error case also renders without an error.

Expected rendering of the http://localhost:3000/example_with_lib page: image

Actual rendering of http://localhost:3000/example_with_lib page: image

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 24.0.0: Mon Aug 12 20:52:31 PDT 2024; root:xnu-11215.1.10~2/RELEASE_ARM64_T6030
  Available memory (MB): 18432
  Available CPU cores: 11
Binaries:
  Node: 21.6.1
  npm: 10.9.0
  Yarn: 1.22.22
  pnpm: 9.12.0
Relevant Packages:
  next: 14.2.15 // Latest available version is detected (14.2.15).
  eslint-config-next: N/A
  react: 18.3.1
  react-dom: 18.3.1
  typescript: N/A
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Module Resolution, Webpack

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

No response

PBug90 avatar Oct 18 '24 13:10 PBug90