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

[v8] SSR support is broken #335

Closed
OlehRb opened this issue Sep 17, 2021 · 16 comments
Closed

[v8] SSR support is broken #335

OlehRb opened this issue Sep 17, 2021 · 16 comments

Comments

@OlehRb
Copy link

OlehRb commented Sep 17, 2021

It seems, like with introduction of v8 this issue has returned
We are using this package with next v11.0.1 and getting the following error, when trying to start our application:

"ReferenceError: document is not defined"

@malcolm-kee
Copy link

malcolm-kee commented Oct 25, 2021

This seems like due to build optimization.

In source code there is a undefined check:

typeof document !== 'undefined'

But in actual packaged code, the check is gone

// react-textarea-autosize.browser.esm.js
// line 104
var isIE = !!document.documentElement.currentStyle ;

@Andarist
Copy link
Owner

SSR should not reach for react-textarea-autosize.browser.esm.js. This is a browser build - this means that your bundler is configured incorrectly.

@malcolm-kee
Copy link

@Andarist I supposed too! But not sure if it's the same for @OlehRb

@OlehRb
Copy link
Author

OlehRb commented Oct 27, 2021

@Andarist, @malcolm-kee, not sure
We use this library in our own tiny design-system library, which is build by rollup, so unless we move it from build-in dependencies to let's say, peer-dependencies I guess it is not possible to provide a correct build of react-textarea-autosize for SSR apps, as it gets bundled as a part of our library..

But I will investigate if moving it away from built-in dependencies is going to solve this problem

By the way, did anyone test this library with the latest version of nextjs?

@Andarist
Copy link
Owner

Its better not to bundle this dependency and let it be installed as a regular dep

@malcolm-kee
Copy link

@OlehRb check if rollup bundle this package. If yes, you can use the external options: https://rollupjs.org/guide/en/#external

@james-elicx
Copy link

I'm running into this problem when using the Next.js Edge Runtime with SSR as well.

@Andarist
Copy link
Owner

@james-elicx this PR should resolve your issue. Note though that you need to tell Next.js (by customizing the webpack config) to use the worker condition.

@james-elicx
Copy link

@james-elicx this PR should resolve your issue. Note though that you need to tell Next.js (by customizing the webpack config) to use the worker condition.

Many thanks. Using the plugin code mentioned in vercel/next.js#33813 (comment) to add the worker condition, all is working as expected :)

@manojVivek
Copy link

Much appreciate the fix!

Note though that you need to tell Next.js (by customizing the webpack config) to use the worker condition.

@Andarist Do you have any pointer for a sample configuration to use the worker condition?

@Andarist
Copy link
Owner

It depends on your bundler, in Next you can do something like this:

module.exports = async (phase, { defaultConfig }) => {
    /**
     * @type {import('next').NextConfig}
     */
    const nextConfig = {
        reactStrictMode: true,
        webpack: (config, ctx) => {
            if (ctx.nextRuntime === "edge") {
                if (!config.resolve.conditionNames) {
                    config.resolve.conditionNames = ['require', 'node'];
                }
                if (!config.resolve.conditionNames.includes("worker")) {
                    config.resolve.conditionNames.push("worker");
                }
            }
            return config;
        },
        experimental: {
            runtime: 'experimental-edge',
        },
    }
    return nextConfig
}

@manojVivek
Copy link

manojVivek commented Dec 16, 2022

Thanks. Unfortunately throws an error while generating the og image on api/og route in next.js:

Uncaught TypeError: (0 , Xo.default) is not a function
    at <unknown> (webpack-internal:///(:3000/api/og/middleware)/./node_modules/satori/dist/index.wasm.cjs:9)
    at eval (webpack-internal:///(:3000/api/og/middleware)/./node_modules/satori/dist/index.wasm.cjs:9:1726)
    at Object.(middleware)/./node_modules/satori/dist/index.wasm.cjs (:3000/api/og/evalmachine.<anonymous>:2352:1)
    at __webpack_require__ (:3000/api/og/evalmachine.<anonymous>:37:33)
    at fn (:3000/api/og/evalmachine.<anonymous>:296:21)
    at eval (webpack-internal:///(:3000/api/og/middleware)/./node_modules/@vercel/og/dist/index.js:5:69)
    at Module.(middleware)/./node_modules/@vercel/og/dist/index.js (:3000/api/og/evalmachine.<anonymous>:2484:1)
    at __webpack_require__ (:3000/api/og/evalmachine.<anonymous>:37:33)
    at fn (:3000/api/og/evalmachine.<anonymous>:296:21)
    at eval (webpack-internal:///(:3000/api/og/middleware)/./pages/api/og.tsx:11:68)
    at Module.(middleware)/./pages/api/og.tsx (:3000/api/og/evalmachine.<anonymous>:869:1)

Probably because satori package is incompatible with the worker condition?

@Andarist
Copy link
Owner

Probably because satori package is incompatible with the worker condition?

This should be irrelevant. You specify what conditions your environment is able to handle but every single package specifies what conditions they support (with fallbacks and everything). It's a "priority list" - satori only specified import and require conditions:
https://github.com/vercel/satori/blob/df8dec5bb5b4b5c3920e0677c78b358399b91872/package.json#L16-L19

and that should be fine.

You'd have to share a repro case for me to take a further look.

@manojVivek
Copy link

Thanks, Will get back if I can reproduce it in an isolated repo.

@ariofrio
Copy link

ariofrio commented May 21, 2023

FWIW, this is occuring with Remix on Vercel Edge Functions. Remix doesn't have a way of customizing the bundler. The error is:

ReferenceError: document is not defined
    at (node_modules/react-textarea-autosize/dist/react-textarea-autosize.browser.esm.js:99:0)
    at (build/build-edge-eyJydW50aW1lIjoiZWRnZSJ9.js:91:0)
    at (build/server-build-edge-eyJydW50aW1lIjoiZWRnZSJ9.mjs:2:18)
    at (posts/:postId:middleware.js:1:17)

My temporary hack is to use a postinstall hook to replace the browser-optimized build with the generic build like so:

{
  "scripts": {
    "postinstall": "cp node_modules/react-textarea-autosize/dist/react-textarea-autosize{,.browser}.esm.js"
  }
}

That works fine for this package because the added code is minimal, but other packages like Prisma might be too heavy to include in browser builds like this. I'm not sure where exactly to lay the problem on, but let's link in https://github.com/vercel/remix here.

I wonder if the default Next.js configuration on Vercel is already set up to make a separate worker build for Edge Functions, or if users are running into this problem.

@Andarist
Copy link
Owner

Remix automatically configures the worker condition for you when bundling for Cloudflare Workers (see here). You might need to configure serverBuildTarget to enable this.

Next.js currently also enables the worker condition when bundling for workers.

I think that this issue can be closed since the bundler that you are using should always give you the option to configure the build target etc

sungik-choi added a commit to channel-io/bezier-react that referenced this issue Oct 20, 2023
…t error (#1688)

<!--
  How to write a good PR title:
- Follow [the Conventional Commits
specification](https://www.conventionalcommits.org/en/v1.0.0/).
  - Give as much context as necessary and as little as possible
  - Prefix it with [WIP] while it’s a work in progress
-->

## Self Checklist

- [x] I wrote a PR title in **English** and added an appropriate
**label** to the PR.
- [x] I wrote the commit message in **English** and to follow [**the
Conventional Commits
specification**](https://www.conventionalcommits.org/en/v1.0.0/).
- [x] I [added the
**changeset**](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md)
about the changes that needed to be released. (or didn't have to)
- [x] I wrote or updated **documentation** related to the changes. (or
didn't have to)
- [x] I wrote or updated **tests** related to the changes. (or didn't
have to)
- [x] I tested the changes in various browsers. (or didn't have to)
  - Windows: Chrome, Edge, (Optional) Firefox
  - macOS: Chrome, Edge, Safari, (Optional) Firefox

## Related Issue
<!-- Please link to issue if one exists -->

Fixes #1687 

## Summary
<!-- Please brief explanation of the changes made -->

- react-textarea-autosize의 버전을 `8.3.4` 로 다운그레이드하고, 버전을 고정합니다.
- revert #1637

## Details
<!-- Please elaborate description of the changes -->

#1637 에서 react-textarea-autosize의 변경으로 인해 rollup의 node module resolve
방식을 변경했습니다. SSR 환경에서도 browser용 번들을 바라보게되면서, `document` 관련 에러가 발생하여 빌드가
실패하는 문제가 발생했습니다.

이를 해결하고자 여러 방법을 고려해봤는데,

1. main module은 SSR용 모듈로 두고, browser용 exports field를 추가: 빌드 시 browser
exports field를 고려하지 않고 있는 다른 사용처에서의 사이드 이펙트가 우려되어서 선택하지 않았습니다.
2. external dependency로 명시하여 peer dependency로 변경: Breaking change를 발생시키고
싶지 않았습니다. TextArea 컴포넌트를 사용하지 않는 사용처에서도 라이브러리 사용이 강제됩니다.
peerDependenciesMeta.optional를 사용하는 방법으로 우회하더라도 매력적인 선택지는 아니라고 생각했습니다.
3. 런타임에 document 체크를 하는 로직 추가: 로직을 추가하고 테스트 해보았으나 여전히 에러가 발생했습니다. 자세히 빌드
과정(Next.js)을 뜯어보진 않았지만, 런타임을 고려하기 이전에 모든 모듈을 정적 분석 + 에러를 던지는 것으로 보입니다.
4. **다운그레이드 및 리버트**

기존에도 큰 문제없이 잘 동작하던 모듈이고, react-textarea-autosize의 변경사항을 봐도 서버 사이드에서 파일
사이즈의 감소 외에는 로직 변경이 없었습니다. 사용처에 별다른 영향이 없을 거로 판단하고 문제 해결을 위해 다운그레이드하는
방향으로 결정했습니다.

### Breaking change? (Yes/No)
<!-- If Yes, please describe the impact and migration path for users -->

No. 이전 버전도 기존에 정상적으로 잘 동작하던 모듈입니다.

## References
<!-- Please list any other resources or points the reviewer should be
aware of -->

- [관련 채널톡
스레드](https://desk.channel.io/root/groups/WebBezier-124831/6530b7edbda0b8528c47)
- Andarist/react-textarea-autosize#335
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants