Skip to content

Instantly share code, notes, and snippets.

@pedrouid
Last active January 18, 2019 15:14
Show Gist options
  • Save pedrouid/629367f8d1b69bf1f93992b2be87bab1 to your computer and use it in GitHub Desktop.
Save pedrouid/629367f8d1b69bf1f93992b2be87bab1 to your computer and use it in GitHub Desktop.
Using crypto NodeJS module polyfill in React-Native (step-by-step)

Using crypto NodeJS module in React-Native (step-by-step)

This tutorial will show you how to polyfill crypto and other NodeJS modules globally in a React-Native environment. Please note that these implementations are purely javascript and don't use native modules to generate random numbers

Step 1 - Install dependencies

Run the following command

npm install --save node-libs-browser buffer process

# OR

yarn add node-libs-browser buffer process

Step 2 - Require node-libs-browser from react-native-cli

From your root directory create a file called rn-cli.config.js or simply add the following if it already exists

const extraNodeModules = require('node-libs-browser');

module.exports = {
  extraNodeModules,
};

Step 3 - Inject node globals into React Native global scope

From your root directory create a file called global.js or simply add the following if it already exists

global.Buffer = require('buffer').Buffer;
global.process = require('process');

if (typeof btoa === "undefined") {
  global.btoa = function(str) {
    return new Buffer(str, "binary").toString("base64");
  };
}

if (typeof atob === "undefined") {
  global.atob = function(b64Encoded) {
    return new Buffer(b64Encoded, "base64").toString("binary");
  };
}

Step 4 - Add the global imports to your root file

From your root directory add the previous global imports to either index.js or both index.ios.js and index.android.js

import { AppRegistry } from 'react-native';
import './global'
import App from './App';

AppRegistry.registerComponent('react-native-boilerplate', () => App);

Make sure your import global file before your App file

Step 5 - Test your crypto module works inside your App

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import crypto from "crypto";

export default class App extends React.Component<{}> {
  state = {
    key: null
  };
  componentDidMount() {
    this.generateKey();
  }
  generateKey = async () => {
    const key = await crypto.randomBytes(32);
    console.log("key", key);
    this.setState({ key });
  };
  render() {
    return (
      <View style={styles.container}>
        <Text>Random Bytes</Text>
        <Text>{this.state.key || "Generating..."}</Text>
      </View>
    );
  }
}

Check out this example repo: https://github.com/markspereira/react-native-web3-boilerplate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment