Skip to content

isURLSameOrigin fails with URL objects due to protocol mismatch #6469

@tstr-st

Description

@tstr-st

Describe the issue

When using isURLSameOrigin with native Javascript URL objects, the protocols mismatch as the resolveURL function strips the ":"-character, while the URL-object's protocol attribute does contain it.

isURLSameOrigin thus returns false if used with URL objects, even if the origins match. This now leads to issues when setting withCredentials = true and withXSRFToken = false as the XSRF token will not be submitted when using URL objects.

Example Code

// locally recreated function that mimics the relevant behavior in isURLSameOrigin
const resolveURL = function (url) {
  let href = url;
  const urlParsingNode = document.createElement('a');

  urlParsingNode.setAttribute('href', href);

  return {
    href: urlParsingNode.href,
    protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
    host: urlParsingNode.host,
    search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
    hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
    hostname: urlParsingNode.hostname,
    port: urlParsingNode.port,
    pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
      urlParsingNode.pathname :
      '/' + urlParsingNode.pathname
  };
};

let originURL = resolveURL("http://www.example.com");
let requestURL = new URL("http://www.example.com");
console.log(originURL.protocol);  // > http
console.log(requestURL.protocol); // > http:

Expected behavior

I do not know if this is to be disregarded as no compatibility with URL objects is explicitly proclaimed in the axios docs. My personal workaround for now is to not pass URL objects directly into axios and use strings only.

A comment in resolveURL however does read "urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils".
According to that spec it seems to me that the ":"-character should be included (if I am reading this correctly):
"The protocol getter steps are to return this’s URL’s scheme, followed by U+003A (:)."

Axios Version

1.7.2 / 1.x

Adapter Version

No response

Browser

No response

Browser Version

No response

Node.js Version

No response

OS

No response

Additional Library Versions

No response

Additional context/Screenshots

No response

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