How to use a library that expects to be running in a browser, but is breaking when rendered server-side in the node.js environment, or, how to make react-chat-widget work in next.js.
This article uses the Korerorero project as an example. Korerorero is an open source implementation of an animated chatbot with voice recognition.
For korerorero-front-end to implement react-chat-widget in its next.js framework, SSR broke because react-chat-widget assumes it’s running in a browser environment and so has access to the window
object. The window
object is not available on the server-side node.js environment.
To work around this mismatch in assumptions, the next.js feature dynamic-import came to the rescue. Its stated intent is to break an app into chunks, allowing lazy loading, and so, speeding up the initial page render. In this case, it can be used to make sure that code with references to the browser’s window object only ever executes in the browser.
import React from "react";
import dynamic from "next/dynamic";
const ChatWidget = dynamic(() => import("react-chat-widget").then((mod) => mod.Widget), {
/* code omitted for clarity, see the source file for details */
ssr: false,
});
export default ChatWidget
view raw
ChatWidget.jsx hosted with ❤ by GitHub
#server-side-rendering #react-chat-widget #front-end-development #nextjs #javascript #security