MongoDB Stitch + Gatsby Buid: WebpackError: ReferenceError: self is not defined with

325 Views Asked by At

My react app is developed with Gatsby. The build-process fails on the dependency "whatwg-fetch"

My app structure is based on the following project. https://github.com/mongodb-university/stitch-tutorial-todo-web

I've found some hints on the web where they do a check for window but I can't get it to work with my structure. example: https://www.gitmemory.com/issue/gatsbyjs/gatsby/8612/527732596

Error log:

  1 | var support = {
> 2 |   searchParams: 'URLSearchParams' in self,
    | ^
  3 |   iterable: 'Symbol' in self && 'iterator' in Symbol,
  4 |   blob:
  5 |     'FileReader' in self &&



WebpackError: ReferenceError: self is not defined

- fetch.js:2 Module../node_modules/whatwg-fetch/fetch.js
  node_modules/whatwg-fetch/fetch.js:2:1

- BrowserFetchTransport.js:1 Module../node_modules/mongodb-stitch-browser-core/dist/esm/core/internal/net/BrowserFetchTransport.js
  node_modules/mongodb-stitch-browser-core/dist/esm/core/internal/net/BrowserFetchTransport.js:1:1

- index.js:1 Module../node_modules/mongodb-stitch-browser-core/dist/esm/index.js
  node_modules/mongodb-stitch-browser-core/dist/esm/index.js:1:1

- index.js:1 Module../node_modules/mongodb-stitch-browser-sdk/dist/esm/index.js
  node_modules/mongodb-stitch-browser-sdk/dist/esm/index.js:1:1`
2

There are 2 best solutions below

0
On

The problem is with whatwg-fetch package which is designed to use browser-side. When Gatsby builds your app the code is executed in Node.js therefore the mentioned package fails to run.

MongoDB distributes two packages for Stitch JS SDK - one for browser and one for server. Ideally you should use both of them, each in the environment they're desired to.

https://www.npmjs.com/package/mongodb-stitch-server-sdk

0
On

I was trying to connect to Stitch using mongodb-stitch-browser-sdk in a gatsby application and building static html pages failed. I solved this problem using react-loadable (Import the component where the Stitch is called using react-loadable) Post.js file

...
    const LoadableComponent = Loadable({
      loader: () => import('../components/Comments'),
      loading() {
       return <div>Loading...</div>
      }
    });
...

Comments.js component imports Stitch and connects to the database.