CommonJS and ESM modules cause SSR and CSR rendering issues with react contexts when using a custom lib
Link to the code that reproduces this issue
https://github.com/datrycs/nextjs-library-esm-cjs-ssr-issues
To Reproduce
- Navigate to
sample-libfolder - Install deps using
yarn install - Use
yarn buildandyalc publishto publish the package - Navigate to
nextjs-projectfolder - Use
yalc add sample-libinnextjs-projectto make the published package available - Install deps using
yarn install - Start the environment using
yarn dev - Navigate to http://localhost:3000/example_with_lib to see the error
- Navigate to http://localhost:3000/example_without_lib to see it working
- Use
export ANALYZE=trueand 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:
Actual rendering of http://localhost:3000/example_with_lib page:
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