Search code examples
next.jsgist

How to embed a GitHub Gist in a NextJS application?


I am working on a static website that uses NextJS. And, I want to embed Github Gist into this website. I tried several npm packages which were created for React. But, those packages seem to use browser features that are not available when my NextJS website generates on the server side. As an example, I used the ReactEmbedGist package. And, it gives these errors: "regeneratorRuntime is not defined" and "ReferenceError: self is not defined". So, What is the most efficient way to embed a Github Gist in a NextJS static application?


Solution

  • This could be achieved using Dynamic imports in NextJS. I used the same npm package (react-embed-gist) which I mentioned in the question.

    Step 1

    Import the react-embed-gist using NextJs dynamic imports. The "ssr" option should be set to false to disable the server-rendering. More details: https://nextjs.org/docs/advanced-features/dynamic-import

    const ReactEmbedGist = dynamic(() => import("react-embed-gist"), {
        ssr: false,
    });
    

    Step 2

    Using the "react-embed-gist" package. More details: https://github.com/msaracevic/react-embed-gist#readme

    <ReactEmbedGist gist="DevLaka/2e99090627052bd300b21aa09089366e" />
    

    Update

    After a while, "react-embed-gist" package didn't work for me. After about two hours of trying to troubleshoot it, I switched to another package called "react-gist" which works fine for my requirements. More details: https://www.npmjs.com/package/react-gist. The process was the same as the earlier one. Only the import statement should be changed.

    Extention of the solution

    Step 1

    Even though the above solution works fine, according to docs, the way I used the dynamic import is used to import components that we wrote, not 3rd party libraries ( https://nextjs.org/docs/advanced-features/dynamic-import ). So, I have created a new component that can be reused as well.

    import Gist from "react-gist";
        
    export default function CodeBlock() {
      return (
        <div>
            <Gist id="c88ac8ea9a43e3379acdc7a1fec3538a" /> 
        </div>
      );
    }
    

    Step 2

    Importing my CodeBlock component using NextJS dynamic import and using it.

    import dynamic from "next/dynamic";
    const CodeBlock = dynamic(() => import("../components/CodeBlock"), {
      ssr: false,
      loading: () => <p>Loading</p>
    });
    
    export default function Home() {
      return (
        <div>
          <CodeBlock id="c88ac8ea9a43e3379acdc7a1fec3538a" />
        </div>
      );
    }