bvaughn / react-error-boundary

Simple reusable React error boundary component
MIT License
6.84k stars 203 forks source link

Error when rendering inside a server component in Next.js #143

Closed tom-sherman closed 1 year ago

tom-sherman commented 1 year ago

Relevant code or config

import { ErrorBoundary } from "react-error-boundary";

export default function Home() {
  return (
    <ErrorBoundary fallback={<p>Whoops...</p>}>
      <Broken />
    </ErrorBoundary>
  );
}

function Broken(): JSX.Element {
  throw new Error("Broken");
}

What you did:

Tried to render an error boundary inside a server component

What happened:

Got a build error

 error ./src/app/page.tsx
ReactServerComponentsError:

The "use client" directive must be placed before other expressions. Move it to the top of the file to resolve this issue.

     ,-[/Users/tom.sherman/code/rsc-error-boundary-bug/node_modules/.pnpm/react-error-boundary@4.0.4_react@18.2.0/node_modules/react-error-boundary/dist/react-error-boundary.js:158:1]
 158 | var $faefaad95e5fcca0$exports = {};
 159 | 
 160 | 
 161 | "use client";
     : ^^^^^^^^^^^^^
 162 | $parcel$exportWildcard(module.exports, $6d6d4999e62b3ee0$exports);
 163 | $parcel$exportWildcard(module.exports, $4a61716688322eb0$exports);
 164 | $parcel$exportWildcard(module.exports, $3c4937b727a6fcfb$exports);
     `----

The error was caused by importing 'react-error-boundary/dist/react-error-boundary.js' in './src/app/page.tsx'.

Import path:
  ./src/app/page.tsx

Reproduction repository:

https://github.com/tom-sherman/rsc-error-boundary-bug

Problem description:

Suggested solution:

tom-sherman commented 1 year ago

It's fixed by moving the "use client" to the top of the module

https://github.com/tom-sherman/rsc-error-boundary-bug/commit/c8f38b0b68934d253bf876426b12fbea51198cf5

bvaughn commented 1 year ago

FWIW it's already at the top of the entry file:

https://github.com/bvaughn/react-error-boundary/blob/9f743e1efff2541b6237ca0cd25f454b80174098/src/index.ts#L1-L9

But something (ParcelJS bundler?) is moving it to nearly the bottom of the bundled file.

bvaughn commented 1 year ago

Basically I need to solve this problem:

Screen Shot 2023-05-27 at 12 05 43 PM

I could add a post-processing step, but I think this would break source maps. I'm not sure how to hook into Parcel's build cycle to do this, and I don't see any related issues on GitHub.

Suggestions welcome!

bvaughn commented 1 year ago

Filed https://github.com/parcel-bundler/parcel/issues/9050 asking for direction.

bvaughn commented 1 year ago

Let's see if 82dc8cd helps for now. Hopefully someone will weigh in on the Parcel issue with a better approach.

bvaughn commented 1 year ago

Published as 4.0.5

bvaughn commented 1 year ago

Note that 4.0.7 has a better solution in place for this.