Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReferenceError: document is not defined / SSR Production Build / wrong target #478

Closed
aheissenberger opened this issue Feb 12, 2024 · 1 comment · Fixed by #480
Closed

Comments

@aheissenberger
Copy link
Contributor

WAKU Version Commit: 7a8609c (Main / latest)

Error:

ReferenceError: document is not defined
    at file:///Users/ah/SVN-Checkouts/TST/waku-mantine/dist/ssr/assets/rsc271-59485b3e0.js:250:12
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)

The bundled rsc271-59485b3e0.js running on the server contains the code from the library only working in a browser.

  • pnpm waku dev 👍
  • pnpm waku dev --with-ssr 👍
  • pnpm waku build --with-ssr 👍
  • pnpm waku start --with-ssr 👎 - ** ReferenceError: document is not defined**

This problem is created by target: 'webworker', in packages/waku/src/lib/builder/build.ts in buildVite for Server and SSR.

FIX: Switching all three in build.ts to target: 'node20', which is my local runtime and in case of a --with-aws-lambda the correct environment for the lambda! For other deployment targets e.g. Vercel this might be 'webworker'.

I suggest to set this based on the deployment target and when no target is set by detecting the current node version.

This is the same Example as used in #448

Example:

  1. add react-textarea-autosize to package.json
  2. add this component to a page
'use client';
import TextareaAutosize from 'react-textarea-autosize';

export const MyTextarea = () => {
    return (<div><TextareaAutosize/></div>);
}
  1. run pnpm waku build --with-ssr

Error: ReferenceError: document is not defined

The reason is that Waku bundles the wrong module node_modules/react-textarea-autosize/dist/react-textarea-autosize.browser.esm.js into rsc2-fcfef706c.js which is optimized for the browser and fails in nodejs when accessing the global document.

The correct file would be node_modules/react-textarea-autosize/dist/react-textarea-autosize.esm.js based on the "exports" section if the package.json.

@dai-shi
Copy link
Owner

dai-shi commented Feb 12, 2024

I had noticed this and worked around in 010a71d, but it seems like a bigger issue.
I looked into Vite source code, but it seems technically impossible to configure as I want in Waku.
Maybe we can only change ssrTarget for some specific serve.
Or we could add worker condition assuming packages should have worder before browser condition.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants