Search code examples
reactjsnext.jspixi.jsurql

ReferenceError: self is not defined using React-Pixi and Next-urql


I keep getting this error when using the Next-Urql and React-Pixi. I understand that this is because React-Pixi requires WEB APIs.

Server Error

ReferenceError: self is not defined This error happened while generating the page. Any console logs will be displayed in the terminal window.

This is my code:

import { Graphics, Stage } from "@inlet/react-pixi";
import { withUrqlClient } from "next-urql";
import { createUrqlClient } from "../../../utils/urqlUtils/createUrqlClient";
import NoSSR from "react-no-ssr";
const edit = () => {
....
  
  return (
    <Layout metaTags={metaTags}>
      <Flex flexDir="row">
            {typeof window !== "undefined" && (
          <NoSSR>

              <Stage>
                <Graphics
                  draw={(g) => {
                    g.beginFill(0xff3300);
                    g.lineStyle(4, 0xffd900, 1);

                    g.moveTo(50, 50);
                    g.lineTo(250, 50);
                    g.lineTo(100, 100);
                    g.lineTo(50, 50);
                    g.endFill();

                    g.lineStyle(2, 0x0000ff, 1);
                    g.beginFill(0xff700b, 1);
                    g.drawRect(50, 250, 120, 120);

                    g.lineStyle(2, 0xff00ff, 1);
                    g.beginFill(0xff00bb, 0.25);
                    g.drawRoundedRect(150, 450, 300, 100, 15);
                    g.endFill();

                    g.lineStyle(0);
                    g.beginFill(0xffff0b, 0.5);
                    g.drawCircle(470, 90, 60);
                    g.endFill();
                  }}
                />
              </Stage>
              </NoSSR>
            )}
          </Flex>
    </Layout>
  );
};

export default withUrqlClient(createUrqlClient, { ssr: false })(edit);

I understand that I should use dynamic rendering, but when I do I keep getting errors.


Solution

  • I guess you're using Next.js by saying that self it not available on server side globalThis MDN

    You could found a related issue on react pixi repo. Supposedly, you can try import no SSR Next.js.

    // Separate your pixi into a component and import
    import dynamic from 'next/dynamic'
    
    const PixiComponentWithNoSSR = dynamic(
      () => import('../components/your-pixi-component'),
      { ssr: false }
    )
    
    return (
      ...
        <PixiComponentWithNoSSR />
      ...
    )