Source:  Twitter logo

I'm using the fetch API in React, and I'm pulling down some data from a JSON endpoint.

As part of my requests, I want to send a custom User-Agent string. Currently, when I inspect my requests, the UA string is:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

Since I'm pasing in headers with every request, I figured I'd just append User-Agent to the headers object, like it says in various places online:

fetch(url, {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'User-Agent': 'MY-UA-STRING' // <---

But this doesn't work. I have a feeling it's becuase of a bug in the fetch api, as reported here and here and here.

Anyone have a work around on how to pass UA as part of the headers using fetch?

After some testing, Chrome does indeed have a bug with the User-Agent header.

This is most likely due to the fact that the User-Agent header was on the list of disallowed headers not too long ago (mid 2015).

As this particular header was recently removed from the list of disallowed headers, Firefox (from version 43) will let you change the User-Agent in a fetch call, but Chrome won't.

Here's the Firefox bug, and the Chromium bug

The reason it was disallowed in the first place, was that there's really no good reason to use the User-Agent header to send arbitrary data, it should be used to send the actual User-Agent, and in-browser requests like Fetch of XMLHttpRequest should really have no good reason to spoof the User Agent anyway.

When the bug will be fixed in Chrome is anyones guess, but it is indeed a bug as the list of disallowed headers no longer lists the User-Agent header, and it should change when specified in the options object of Fetch.

As a sidenote, you should generally be creating the headers using the Headers Interface, and include them in the options objects under the headers key

let headers = new Headers({
    "Accept"       : "application/json",
    "Content-Type" : "application/json",
    "User-Agent"   : "MY-UA-STRING"

fetch(url, {
    method  : 'GET', 
    headers : headers 
    // ... etc
}).then( ...
23 users liked answer #0dislike answer #023
adeneo profile pic

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).