Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gatsby build failing if you reference navigator at all during SSR: "navigator" is not available during server side rendering #19317

Closed
kylegwalsh opened this issue Nov 6, 2019 · 15 comments
Labels
type: upstream Issues outside of Gatsby's control, caused by dependencies

Comments

@kylegwalsh
Copy link

Description

It looks like the latest version of gatsby (2.17.7) is throwing errors during build time if you reference "navigator" at all (regardless of usage).

I have been using gatsby and aws-amplify together for a while now, but I recently started receiving build errors after upgrading gatsby.

Steps to reproduce

I would include a repository, but I would have to expose my AWS credentials in order for anyone to actually be able to run the code. I believe this issue is pretty straight forward and not aws-amplify specific, but please correct me if I'm wrong!

To reproduce this error:

  1. yarn add gatsby aws-amplify
  2. Configure Auth via aws-amplify
  3. Add any Auth related methods somewhere in the application
  4. Attempt to gatsby build

Expected result

Gatsby should allow the build to complete if "navigator" is being referenced merely to determine if it exists (as a boolean).

Actual result

Gatsby build fails and complains that "navigator" is not available during server side rendering.

Here is the result of gatsby build:

$ gatsby build
success open and validate gatsby-configs - 0.073s
success load plugins - 0.944s
success onPreInit - 0.009s
success delete html and css files from previous builds - 0.013s
success initialize cache - 0.005s
success copy gatsby files - 0.089s
success onPreBootstrap - 0.006s
success loading DatoCMS content - 2.485s
success source and transform nodes - 2.626s
success building schema - 0.386s
success createPages - 0.029s
success createPagesStatefully - 0.116s
success onPreExtractQueries - 0.007s
success update schema - 0.027s   
success extract queries from components - 0.338s
success write out requires - 0.007s
success write out redirect data - 0.002s
success Build manifest and related icons - 0.003s
success onPostBootstrap - 0.036s
⠀
info bootstrap finished - 7.892 s
⠀
success Building production JavaScript and CSS bundles - 60.922s
success Rewriting compilation hashes - 0.003s
success run queries - 61.082s - 4/4 0.07/s
failed Building static HTML for pages - 12.762s

 ERROR #95312 

"navigator" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html


  85 | var ACCEPTED_CODES = [202];
  86 | var MOBILE_SERVICE_NAME = 'mobiletargeting';
> 87 | var BEACON_SUPPORTED = navigator && typeof navigator.sendBeacon === 'function';
     | ^
  88 | // events buffer
  89 | var BUFFER_SIZE = 1000;
  90 | var FLUSH_SIZE = 100;


  WebpackError: ReferenceError: navigator is not defined

  - AWSPinpointProvider.js:87 Module.../node_modules/@aws-amplify/analytics/lib-esm/Providers/AWSPinpointProvider.js
    node_modules/@aws-amplify/analytics/lib-esm/Providers/AWSPinpointProvider.js:87:1

  - Analytics.js:1 Module.../node_modules/@aws-amplify/analytics/lib-esm/Analytics.js
    node_modules/@aws-amplify/analytics/lib-esm/Analytics.js:1:1

  - index.js:1 Module.../node_modules/@aws-amplify/analytics/lib-esm/index.js
  - index.js:1 Module.../node_modules/aws-amplify/lib-esm/index.js
    node_modules/aws-amplify/lib-esm/index.js:1:1

  - UserStore.tsx:1 Module../src/stores/UserStore.tsx
    src/stores/UserStore.tsx:1:1

  - index.ts:1 Module../src/stores/index.ts
    src/stores/index.ts:1:1

  - AccountIcon.tsx:1 Module../src/components/AccountIcon.tsx
    src/components/AccountIcon.tsx:1:1

  - index.ts:1 Module../src/components/index.ts
    src/components/index.ts:1:1


error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Amplify appears to just be checking whether navigator is available, which shouldn't cause problems during SSR.

I did not have any issues building on a previous version of gatsby (2.7.0). I understand why this check was probably added (to make sure you aren't trying to use something that isn't available during SSR), but this usage seems safe. I do not believe that this should be throwing an error.

Is there a way to suppress this error on my end, or is this a bug?

Environment

  System:
    OS: Windows 10
    CPU: (8) x64 Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz
  Binaries:
    Yarn: 1.19.1 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.10.3 - C:\Program Files\nodejs\npm.CMD
  Languages:
    Python: 3.8.0 - /c/Users/Kyle/AppData/Local/Programs/Python/Python38-32/python
  Browsers:
    Edge: 44.18362.387.0

Additional Information

Versions:

  • gatsby: 2.17.7
  • aws-amplify: 1.1.26

I am only using the Auth portion of aws-amplify currently.

@behivetech
Copy link

I just ran into this same problem.

@behivetech
Copy link

behivetech commented Nov 7, 2019

I find it kind of odd the build completely fails when there's checks like
if (window && window.xxx)
if (navigator && navigator.xxx)
etc.
Why do those fail? That looks like legitimate Javascript to me. If this overall problem could be fixed, it sure seems like problems like this wouldn't keep bubbling up.

@behivetech
Copy link

behivetech commented Nov 7, 2019

@kylegwalsh I did figure out that dynamically importing Amplify works; however, it gets a little weird because of how the module is built (aws-amplify/amplify-js#488). The main thing is configure is inside of default. I threw my import in useEffect (aka componentDidMount).

useEffect(() => {
  // Have to create a function with async inside of useEffect since it doesn't like async on the root function
  async function initAmplify() {
    const Amplify = await import('aws-amplify');
    Amplify.default.configure({
      Auth: {
        mandatorySignIn: true,
        region: authConfig.REGION,
        userPoolId: authConfig.USER_POOL_ID,
        identityPoolId: authConfig.IDENTITY_POOL_ID,
        userPoolWebClientId: authConfig.APP_CLIENT_ID
      },
    });
    // ...other stuff. I added Amplify.Auth to state here so I could use it for signIn, signOut, etc.
  }
  initAmplify();
}, []);

Hope that helps some.

@kylegwalsh
Copy link
Author

@Bruqui

That's easy enough for initially configuring it, but I use amplify pretty extensively for custom authentication functions and would have to add a ton of conditions throughout my application.

I'd rather not add a lot of additional logic if the solution is as easy as suppressing these errors during the gatsby build process.

@behivetech
Copy link

behivetech commented Nov 8, 2019

I'd rather not add a lot of additional logic if the solution is as easy as suppressing these errors during the gatsby build process.

@kylegwalsh
Yeah, I hear you. It's certainly not ideal to do a refactor on a lot of files because of issues you're having from Gatsby. It doesn't make sense why valid Javascript conditions fail like that. I'm pretty sure because it's in a node mode when building and node doesn't like those particular conditionals for browser variables.

I'm in the beginning stages of the current app I'm working on and still trying to establish a good plan. One thing I was thinking of doing was creating an AuthProvider component to house all the function calls (signIn, signOut, etc) and state, then using the React useContext hook in any components that require it. This way, I'm not completely coupled to a library throughout my app if something better comes along or something like this very problem comes up.

@behivetech
Copy link

behivetech commented Nov 8, 2019

Oh... and, I know this isn't ideal at all to do, but you if go into the AWSPinpointProvider.js file in the amplify library and change...

var BEACON_SUPPORTED = navigator && typeof navigator.sendBeacon === 'function';

to something like...

var BEACON_SUPPORTED = typeof navigator === 'object';

...this will alleviate your issue for the time being if it's a complete blocker for you. You may even be able to just set the var to false for now without any issues.

I was trying to figure out how to get typeof navigator.sendBeacon === 'function' to pass by checking for the key in another way then submitting a pull request to amplify, but couldn't figure out how to get that to pass the build.

@simplexologylab
Copy link

Hitting same problem as well

@kylegwalsh
Copy link
Author

@Bruqui
I am also using a context to pass amplify functions and state around. It works pretty well as far as global state.

I would have to fork amplify in order to make those changes to the pinpoint file because my build occurs during the CI process and the fresh library would just be installed.

For now I guess I’ll look into a clean way to add the conditions without messying up the logic too much.

@behivetech
Copy link

@kylegwalsh Well, at least the dynamic import is an option to alleviate the issue. Again, not ideal having to go through a refactor because of it. Hopefully someone can figure out this issue of conditionals failing that shouldn't during Gatsby's build so issues like this stop popping up since Amplify isn't going to be the only issue with this. Any third-party library that uses things like window, document, navigator, etc. are probably going to fail during build process.

@ramseytisher
Copy link

Cross linking to aws-amplify issue that is related/same issue.

aws-amplify/amplify-js#4365

@ramseytisher
Copy link

@kylegwalsh
Copy link
Author

@ramseytisher Awesome! Looks like this will fix our issue with amplify.

I'm still a little concerned on the gatsby side because of the language used to describe the error though:
"navigator" is not available during server side rendering.

This really sounds like gatsby is specifically throwing the error because navigator exists during SSR (even if it shouldn't cause any issues). Just something to think about in case other libraries result in similar issues. I could be wrong though!

@LekoArts LekoArts added the type: upstream Issues outside of Gatsby's control, caused by dependencies label Nov 13, 2019
@LekoArts
Copy link
Contributor

Thank you for opening this!

This wasn't caused by a change of Gatsby's behavior but a PR in Amplify:
aws-amplify/amplify-js#4246

They also already fixed this and will release it in the next minor, so look out for that.

We're marking this issue as answered and closing it for now but please feel free to comment here if you would like to continue this discussion. We also recommend heading over to our communities if you have questions that are not bug reports or feature requests. We hope we managed to help and thank you for using Gatsby!

@jamesb93
Copy link

This is perhaps tangential but I am getting this issue with the BBC peaks.js library.

https://github.com/bbc/peaks.js/tree/master

  13053 | module.exports = function (Cue, Utils) {
  13054 |     'use strict';
> 13055 |     var isHeadless = /HeadlessChrome/.test(navigator.userAgent);
        | ^
  13056 |     function windowIsVisible() {
  13057 |         if (isHeadless || navigator.webdriver) {
  13058 |             return false;

What are the steps to alleviating the problem? If I was pointed in the right direction I could make a PR to the original library to fix the problem for myself and others.

@tonystaark
Copy link

Opening up the issue again here:
image

lfittl added a commit to pganalyze/pganalyze-docs that referenced this issue Dec 14, 2023
See gatsbyjs/gatsby#19317 - even attempting to
reference "navigator" directly will throw an error.

In passing fix whitespace issue in directory.json.
lfittl added a commit to pganalyze/pganalyze-docs that referenced this issue Dec 15, 2023
See gatsbyjs/gatsby#19317 - even attempting to
reference "navigator" directly will throw an error.

In passing fix whitespace issue in directory.json.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: upstream Issues outside of Gatsby's control, caused by dependencies
Projects
None yet
Development

No branches or pull requests

7 participants