Axios responseType Document Explained for Browsers
Setting responseType: 'document' in Axios configures the
browser to automatically parse an incoming HTML or XML response into a
native DOM Document object. This guide covers how the
setting interacts with browser APIs, changes the structure of
response.data, enables direct DOM querying, and behaves
across different runtime environments.
How It Works Under the Hood
When running in a browser, Axios relies on the native
XMLHttpRequest (XHR) API. Passing
{ responseType: 'document' } in the Axios request
configuration assigns the value directly to
XMLHttpRequest.responseType.
Upon receiving the response, the browser's built-in parsing engine
checks the Content-Type header (such as
text/html, application/xml, or
text/xml) and automatically converts the raw text stream
into an HTMLDocument or XMLDocument.
Impact on
response.data
Without this setting, Axios treats HTML or XML responses as plain
text strings, requiring manual parsing. With
responseType: 'document', response.data
provides immediate access to a fully instantiated DOM tree.
import axios from 'axios';
async function fetchPageTitle() {
try {
const response = await axios.get('https://example.com', {
responseType: 'document'
});
// response.data is an HTMLDocument instance
const doc = response.data;
// Use standard DOM traversal methods directly
const pageTitle = doc.querySelector('title')?.textContent;
const firstHeading = doc.querySelector('h1')?.innerText;
console.log('Title:', pageTitle);
console.log('H1:', firstHeading);
} catch (error) {
console.error('Request failed:', error);
}
}Key Advantages
- No Manual Parsing: Eliminates the need to
instantiate a
DOMParserinstance (e.g.,new DOMParser().parseFromString(data, 'text/html')). - Direct Access to DOM APIs: Standard DOM querying
methods like
getElementById,querySelectorAll, and XPath evaluators work directly onresponse.data. - Performance: Parsing is handled natively at the browser level during the retrieval process rather than as an extra JavaScript processing step.
Limitations and Considerations
- Browser-Only Support: This feature depends on the
browser's native DOM parser. In Node.js environments, setting
responseType: 'document'will not produce a DOM object; libraries likecheerioorjsdommust be used instead. - MIME Type Dependency: If the server returns a
Content-Typeheader that the browser does not recognize as valid HTML or XML, the browser parser may returnnullfor the response body. - Malformed Markup: In XML mode, syntax errors in the returned document will result in an XML parser error document rather than a standard object structure.