I have a React Native application deployed on devices, and they need to communicate with an endpoint requiring TLS mutual authentication: I need to send a TLS client certificate along with the request.
It works well when in Node (API to API) using request-promise for instance.
Reusing the same code in React Native didn't work, so I tried a couple other methods / libraries:
The official fetch API does not allow to send client certificates
axios requires https which is not available either
I came to realize that maybe React Native does not provide a way of doing it "natively" without using a native module (?), since it would mean importing a TLS implementation in pure JS (inefficient and slow I guess?).
What is the best way to perform mutual TLS authentication from a React Native application?
One option you could consider is using the XMLHttpRequest API, which is available in React Native and allows you to set the client certificate through the cert property. Here's an example of how you could use it:
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://your-endpoint.com'); xhr.cert = fs.readFileSync('path/to/client.pem'); // your client certificate xhr.send();
You could also use a third-party library such as pem-jwk to convert the client certificate from PEM format to JWK format, and then use the fetch API with the client_key option, like this:
const pem = fs.readFileSync('path/to/client.pem'); const jwk = pemToJwk(pem, {}); fetch('https://your-endpoint.com', { method: 'GET', client_key: jwk, });
Note that you may need to install the pem-jwk library and add it to your dependencies:
npm install pem-jwk