react-chat-widget icon indicating copy to clipboard operation
react-chat-widget copied to clipboard

Not working on server side rendering

Open chyke007 opened this issue 5 years ago • 5 comments

Is it possible to make this work on server side rendering. I am using Gatsby and it happens to work fine on development but fails on production with the error message "window" is not available during server side rendering.

Is there any work around for this. Thanks.

chyke007 avatar Feb 10 '20 19:02 chyke007

Same case on the Next.js project. Screenshot_1

prettydev avatar Jun 09 '20 00:06 prettydev

I solved this issue by adding these two dependencies to my package.json

  1. react-dynamic-import
  2. @loadable/component

And then importing the component I had my chat code into my display component.

import ReactDynamicImport from "react-dynamic-import" import Chat from './chat';

Then wrapped the chat component using the dynamic import

const loader = () => import('./chat'); const RealComponent = ReactDynamicImport({loader});

Then I rendered it.

  <RealComponent />

Hope this helps.

chyke007 avatar Jun 09 '20 03:06 chyke007

I forked and tried to adapt the code to work server side. But got suck on a problem that I think is related to webpack.

I search the project for all the window references and added a verification to check if it's undefined. But even after adding this condition to all the places the file generated still have a window reference that I couldn't find the origin:

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports["react-chat-widget"]=t(require("React"),require("ReactDOM")):e["react-chat-widget"]=t(e[void 0],e[void 0])}(window,function(e,t){return function(e){var t={};function r(n){if(t[n])return t[n].exports (...)

Since is in the beginning of the final file I think that one of the steps inside webpack may be generating this reference. If I change the part on the final output the code works fine with the build from my project

Any idea where this reference may be coming from? I would be happy to finish the adaptation and make it work on Gatsby

felpsio avatar Sep 24 '20 08:09 felpsio

I have no idea yet where this window reference is imported into the code, I had similar issue but after a long time debugging had to look for a walk around. It is really a great idea that you have picked this up, I would try and search more about this issue in my free time to see if I could also figure it out.

chyke007 avatar Sep 25 '20 14:09 chyke007

@chyke007 I checked again and I think I figured out

It comes from libraryTarget: 'umd'

If I change umd to amd on webpack.config.prod.js the window is removed. Do you think it may generate any dangerous side effect? If not we may try a branch with this change

felpsio avatar Sep 25 '20 18:09 felpsio