Fetch: user-agent is still the default after I set it in the header

Created on 28 Mar 2018  路  2Comments  路  Source: github/fetch

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:

screen shot 2018-03-22 at 3 12 07 pm

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?

Most helpful comment

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.

All 2 comments

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:

  1. it's only for React Native
  2. React Native already has a default User-Agent. Something like: <PROJECT_NAME>/<VERSION> CFNetwork/975.0.3 Darwin/17.7.0
  3. while using Remote JS Debugging, it'll use the browser user-agent. Something like: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Was this page helpful?
0 / 5 - 0 ratings

Related issues

poppinlp picture poppinlp  路  4Comments

naivefun picture naivefun  路  3Comments

karladler picture karladler  路  4Comments

gkatsanos picture gkatsanos  路  4Comments

ccorcos picture ccorcos  路  3Comments