Hertha  Mayer

Hertha Mayer

1624691242

Using Core Node JS Modules in React Native Apps

Sometimes while creating advanced apps in react-native you may want to encrypt the data you are sending to the web for secured web communication. You may also want to encrypt the payment-related data that is sent to the payment gateway.

Let’s say you want to use the crypto module to create some encrypted data. It might seem natural to do something like this:

There are many alternate modules out there namely

expo-crypto, react-native-crypto and many others but none of these have all the methods of crypto module ,especially if you want to use createCipheriv method you wont find it in any of those modules out there.

var crypto = require('crypto');

var mykey = crypto.createCipher('aes-128-cbc', 'mypassword');
var mystr = mykey.update('abc', 'utf8', 'hex')
mystr += mykey.final('hex');

console.log(mystr); //34feb914c099df25794bf9ccb85bea72

Just import a module and create an encrypted string, right? Right? Nope!

But this doesn’t work, because crypto is a core Node JS module, which means it’s probably C++ code bundled with the Node JS binary, not Javascript. The React Native packager can’t package it along with your app’s Javascript bundle, so you get a runtime error:

Unable to resolve module 'crypto' 

This makes core modules like the crypto, stream, etc, and the thousands of npm modules that depend on them unusable from React Native. Fortunately, there’s a solution to this problem, but it takes some work.

#react-native #node #javascript #react

Using Core Node JS Modules in React Native Apps