Skip to content

"ReferenceError: navigator is not defined" in require('axios') #6122

@Bozzzo

Description

@Bozzzo

Describe the bug

There is an unprotected use of navigator global object recently introduced (1.6.2) that can cause crash on NodeJS

To be more precise: when navigator is undefined but window and document are not.

1 - considering the following code in \dist\esm\axios.js

const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';

hasBrowserEnv evaluates to true

2 - considering the following code in \lib\platform\common\utils.js

    const hasStandardBrowserEnv = (
    (product) => {
      return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0
    })(typeof navigator !== 'undefined' && navigator.product);

(typeof navigator !== 'undefined' && navigator.product) evaluates to false

which make hasStandardBrowserEnv evaluate to (true && (-1) < 0) that is true

The consequence is that with navigator undefined but window and document both defined
THE MERE LOADING OF lib\helpers\isURLSameOrigin.js will evaluate following code :

      export default platform.hasStandardBrowserEnv ?
      // Standard browser envs have full support of the APIs needed to test
      // whether the request URL is of the same origin as current location.
        (function standardBrowserEnv() {
          const msie = /(msie|trident)/i.test(navigator.userAgent);
          ...

that causes a "ReferenceError: navigator is not defined" error.

@DigitalBrainJS what do you think?

Suggested fix: in lib\helpers\isURLSameOrigin.js replace code with
const msie = /(msie|trident)/i.test(navigator && navigator.userAgent);

To Reproduce

node -e "window = document = {}; require('axios')"

Code snippet

Real code that was failing:

    const { JSDOM } = require('jsdom');
    const { window } = new JSDOM('<html><body></body></html>');

    global.$ = global.jQuery = require('jquery')(window);

    global.window = window;
    if (global.document === undefined) {
        global.document = window.document;
    }

    ... losts of other things ...

    require('axios'); // Crashes...

Expected behavior

Do not crash... especially during load

Axios Version

at least 1.6.2

Adapter Version

Browser

none, or JSDom fake browser

Browser Version

N.A.

Node.js Version

any

OS

any

Additional Library Versions

-

Additional context/Screenshots

-

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions