Enhancing React Native App Security with Google reCAPTCHA v2
Tags: reactnative, android, ios, captcha
Published: 2024-05-03 14:16:04

## Introduction:

In today's digital landscape, ensuring the security of mobile applications is paramount. Bots and malicious scripts can pose serious threats, compromising user data and system integrity. One effective way to mitigate these risks is by integrating Google reCAPTCHA v2 into React Native applications. 

> This article delves into the implementation of reCAPTCHA v2 using the react-native-google-recaptcha-v2 library, highlighting its significance and providing a step-by-step guide for developers.

🎬 Let's kick things off with a bang - check out our captivating demo video showcasing the captcha service in action!🚀

---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zgk7zcqe236o68hs3it.gif)

---


## Why Google reCAPTCHA v2?

Google reCAPTCHA v2 is a widely adopted solution for distinguishing between humans and bots. It presents users with challenges, such as image recognition or checkbox verification, to confirm their identity. By incorporating reCAPTCHA v2, React Native apps can prevent automated attacks, spam, and unauthorized access attempts, thereby bolstering their security posture.

## Getting Started:

**Register with Google reCAPTCHA:**

Visit [Google reCAPTCHA Admin Console](https://www.google.com/recaptcha/admin/create) to register a new site.
- Choose reCAPTCHA v2 as the type and whitelist the domain name without 'https://', for example, 'your-domain.com'.
- After registration, you'll receive a Site Key and a Secret Key.

## Setting Up the Project🛠️🔧

**1). Create a new React Native project using the following command:**

```
npx react-native init googleCaptchaApp
```

**2). Navigate to the project directory:**

```
cd googleCaptchaApp
```

**3).Install the required dependencies:**

```
npm install --save react-native-google-recaptcha-v2
--- or ---
yarn add react-native-google-recaptcha-v2
```

**Package.json Dependencies**
Below are the dependencies specified in the `package.json` file for a React Native project:

```
{
    "dependencies": {
    "react": "18.2.0",
    "react-native": "0.72.3",
    "react-native-google-recaptcha-v2": "^1.1.0",
    "react-native-modal": "^13.0.1",
    "react-native-webview": "12.0.2"
  },
}
```

## Usage Code Example

```
import React, {useRef} from 'react';
import {View, StyleSheet, TouchableOpacity, Text} from 'react-native';
import ConfirmGoogleCaptcha from 'react-native-google-recaptcha-v2';
import {baseUrl, siteKey} from '../../utils';

const CaptchaV2Lib1 = () => {
  const captchaFormRef = useRef(null);

  const onMessage = event => {
    console.log('event--->>>>', event);

    if (event && event.nativeEvent.data) {
      if (['cancel', 'error', 'expired'].includes(event.nativeEvent.data)) {
        captchaFormRef.current.hide();
        return;
      } else {
        console.log('Verified code from Google', event.nativeEvent.data);
        setTimeout(() => {
          captchaFormRef.current.hide();
          // do whatever you want here
        }, 1500);
      }
    }
  };

  return (
    <View style={styles.container}>
      <ConfirmGoogleCaptcha
        ref={captchaFormRef}
        baseUrl={baseUrl} // same domain which you mention on google captcha console
        languageCode="en"
        onMessage={onMessage}
        siteKey={siteKey}
        theme="dark"
      />
      <TouchableOpacity
        style={styles.buttonContainer}
        onPress={() => {
          captchaFormRef.current.show();
        }}>
        <Text style={styles.txt}>Open Captcha</Text>
      </TouchableOpacity>
    </View>
  );
};

export default CaptchaV2Lib1;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonContainer: {
    backgroundColor: 'orange',
    paddingHorizontal: 40,
    paddingVertical: 20,
    borderRadius: 4,
  },
  txt: {
    fontSize: 15,
    fontWeight: '600',
  },
});

```

## Usage and Integration:

1). Import the CaptchaV2Lib1 component into your desired React Native screen or component.
2). Integrate the component within your app's UI hierarchy and implement logic to handle reCAPTCHA verification results, such as validating user actions or preventing malicious activities.

## Benefits of reCAPTCHA Integration:

- **Heightened Security:** Protect your React Native app from bot-driven attacks, spam, and unauthorized access attempts.
- **User Verification:** Confirm the identity of users, ensuring genuine interactions and mitigating automated scripts.
- **Trust Building:** Demonstrate a commitment to security, fostering user trust and confidence in your application.
- **Customizable Experience:** Customize reCAPTCHA themes, languages, and interaction flows to align with your app's design and user experience.

> **Note:** Ensure that the domain you entered in the Google reCAPTCHA Admin Console matches the domain used in the baseUrl within your code. For example, if you entered 'your-domain.com' in the console, the same domain ('your-domain.com') should be used in the baseUrl variable in your React Native application. This consistency ensures seamless communication with the reCAPTCHA service and avoids potential configuration errors.

## Token Verification
**Implementing Secure Authentication:** The snippet below illustrates backend code used to authenticate tokens sent from a React Native application in JS

```
export const validateCaptchaToken = async (token = '', callback = {}) => {
  const params = {
    secret: YOUR_SECRET_KEY,
    response: YOUR_TOKEN,
  };

  try {
    const postData = new URLSearchParams(params).toString();
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    };

    const response = await fetch(SITE_VERIFY_URL, {
      ...options,
      body: postData,
    });

    if (response?.ok && response?.status === 200) {
      // do you code here
    } else {
      // handle the failure case here
    }
  } catch (error) {
    // handle the failure case here
  }
};
```

## Conclusion:
By integrating Google reCAPTCHA v2 into React Native applications, developers can significantly enhance security measures, mitigate risks, and protect user data. Follow the outlined steps to seamlessly implement reCAPTCHA functionality and bolster your app's defenses against malicious activities.

## References:

- **Google reCAPTCHA:** [Google reCAPTCHA developer resources](https://www.google.com/recaptcha/admin/create)
- **react-native-google-recaptcha-v2:** [library repository](https://github.com/xuho/react-native-google-recaptcha-v2)
- Download the source code for this post from my [github](https://github.com/amitmehtacode/captcha)

Feel free to customize the content further or add additional details as needed!