I'm using fetch on React Native both Android and iOS. I set the User-Agent to the name of the platform so I can distinguish between Android and iOS from the backend:
const URLENCODED_HEADER = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': Platform.OS + "/" + DeviceInfo.getUniqueID().toString()
}
export async function doRegister(secureInfo) {
formBody = encodeParameters(secureInfo)
try {
let response = await fetch(SERVER_URL+'/user/register', {
method: "POST",
headers: URLENCODED_HEADER,
body: formBody,
credentials: 'include'
});
let responseJson = await response.json();
return responseJson;
} catch(error) {
console.error(error);
throw error;
}
}
I have logged the requests in Reactotron and it looks like user-agent was changed successfully:

However, on the server side, the ua logged from the requests is still the default for android and ios devices, such as below:
Mozilla/5.0 (iPad; CPU OS 11_2_6 like Mac OS X) AppleWebKit/604.5.6 (KHTML, like Gecko) Version/11.0 Mobile/15D100 Safari/604.1
okhttp/3.6.0
Dalvik/2.1.0 (Linux; U; Android 5.1.1; Coolpad 3622A Build/LMY47V)
So is it possible to change the user-agent with fetch in React Native? If so what's the proper way to do it?
Browsers will typically disallow you from changing the User-agent string. It's a security restriction. There is no way around it; you'll have to use a different header name, e.g. X-Custom-user-agent, and configure the server to read it.
@ethanyuwang Try to Stop Remote JS Debug to test it.
I was dealing with the same problem too.
It's working for me. :)
Some notes:
<PROJECT_NAME>/<VERSION> CFNetwork/975.0.3 Darwin/17.7.0Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Most helpful comment
Browsers will typically disallow you from changing the
User-agentstring. It's a security restriction. There is no way around it; you'll have to use a different header name, e.g.X-Custom-user-agent, and configure the server to read it.