Class-27 Adding Google reCAPTCHA to Protect Your Bolt.new App

In this section, we’ll explore Google reCAPTCHA, a powerful tool designed to prevent abuse and spam on your website or application. By implementing reCAPTCHA, you add an extra layer of security to protect your platform from bots and malicious users. The best part? It’s easy to integrate, free to use, and works seamlessly with Google products like Firebase.

What is Google reCAPTCHA?

Google reCAPTCHA is a security measure that helps distinguish between humans and automated bots. It is commonly used in login and signup processes to prevent spam and unauthorized access. reCAPTCHA comes in different versions, each offering unique ways to verify user authenticity.

Why Use Google reCAPTCHA?

  • Prevents Bots: Stops automated scripts from creating fake accounts or spamming forms.
  • Enhances Security: Adds an extra layer of protection to user authentication.
  • User-Friendly: Works in the background or presents minimal friction to real users.
  • Free to Use: Google provides this service without any cost.

Setting Up Google reCAPTCHA

Before integrating reCAPTCHA into your application, visit Google reCAPTCHA and navigate to the Admin Console. Follow these steps:

  1. Register Your Application:

    • Click on Admin Console v3.
    • Click on the + (Create) button.
    • Enter your domain name (e.g., example.com).
  2. Choose reCAPTCHA Type:

    • reCAPTCHA v2 (Tick Box): Displays a checkbox labeled “I’m not a robot.”
    • Invisible reCAPTCHA v2: Works in the background without user interaction.
    • reCAPTCHA v3: Assigns a score based on user behavior, without displaying a challenge.
    • Recommended: Use reCAPTCHA v2 (Tick Box) for visible user interaction.
  3. Obtain API Keys:

    • After registration, Google provides a Site Key and Secret Key.
    • Store these securely for integration into your app.

Integrating reCAPTCHA in Your Application

Once you have the API keys, follow these steps to integrate reCAPTCHA:

  1. Add reCAPTCHA to Your Login/Signup Page

    • Insert the reCAPTCHA script in your HTML file:
      <script src="https://www.google.com/recaptcha/api.js" async defer></script>
      
    • Add the reCAPTCHA widget:
      <form action="your-server-endpoint" method="POST">
          <input type="email" name="email" required>
          <input type="password" name="password" required>
          <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
          <button type="submit">Submit</button>
      </form>
      
  2. Verify reCAPTCHA on Your Server

    • On form submission, validate reCAPTCHA on the backend:
      const axios = require('axios');
      
      app.post('/verify-recaptcha', async (req, res) => {
          const token = req.body['g-recaptcha-response'];
          const secretKey = 'YOUR_SECRET_KEY';
          
          const response = await axios.post(`https://www.google.com/recaptcha/api/siteverify`, null, {
              params: { secret: secretKey, response: token }
          });
          
          if (response.data.success) {
              res.json({ success: true, message: 'reCAPTCHA verified successfully' });
          } else {
              res.json({ success: false, message: 'reCAPTCHA verification failed' });
          }
      });
      

Integrating Google reCAPTCHA with Firebase Authentication

If you’re using Firebase for authentication, you can integrate reCAPTCHA as follows:

  1. Enable reCAPTCHA in Firebase:

    • Go to Firebase Console.
    • Navigate to Authentication > Sign-in method.
    • Under Phone Authentication, enable reCAPTCHA.
  2. Modify Your Client-Side Code:

    • Use Firebase’s built-in reCAPTCHA verifier:
      import firebase from 'firebase/app';
      import 'firebase/auth';
      
      const appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
          'size': 'invisible',
          'callback': (response) => {
              console.log('reCAPTCHA solved, proceeding with authentication');
          }
      });
      
      firebase.auth().signInWithPhoneNumber('+1234567890', appVerifier)
          .then(confirmationResult => {
              console.log('OTP sent');
          })
          .catch(error => {
              console.error('Error during authentication', error);
          });
      
  3. Verify OTP from User:

    • Once the user enters the OTP, verify it using:
      confirmationResult.confirm(otp)
          .then(result => {
              console.log('User signed in successfully', result.user);
          })
          .catch(error => {
              console.error('OTP verification failed', error);
          });
      

Monitoring reCAPTCHA Usage

  • Visit the Admin Console to monitor reCAPTCHA statistics.
  • Review analytics for suspicious activity and adjust security settings accordingly.

Conclusion

Implementing Google reCAPTCHA enhances your application’s security by blocking bots and reducing spam. Whether using Firebase or another backend, integrating reCAPTCHA is a best practice for maintaining a secure and trustworthy platform. By following these steps, you can ensure that only legitimate users access your application while keeping unwanted automated traffic out.


Was this article helpful?