Skip to content

Instantly share code, notes, and snippets.

@andreydro
Last active January 6, 2022 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreydro/4aabb24c0aa4d2f4b67b3b96dda51b1a to your computer and use it in GitHub Desktop.
Save andreydro/4aabb24c0aa4d2f4b67b3b96dda51b1a to your computer and use it in GitHub Desktop.
Integrating recaptcha to Next.js App (React) + Rails API

Prepare:

  • Go to this URL (https://www.google.com/recaptcha/admin/create) to create a reCAPTCHA app.

  • Give the reCAPTCHA a label.

  • Select reCAPTCHA v2.

  • Add the domain name of where this captcha checkbox will be used. To test this checkbox on your development server, add localhost as your domain name.

  • Click Submit.

Add to code:

  1. Add package to react app yarn add react-google-recaptcha

  2. Add ReCAPTCHA to you component

import ReCAPTCHA from "react-google-recaptcha"


const YouComponent = () => {
  const [recaptchaToken, setRecatpchaToken] = useState(null)
  
  onChangeRecaptcha = (value) => {
    console.log("Captcha value:", value)
    setRecatpchaToken(value)
  }

  return {
    <form>
       ...
       <ReCAPTCHA
         sitekey={constants.RECAPTCHA_PUBLIC_KEY} // (key you got from https://www.google.com/recaptcha/admin/create)
         onChange={setRecatpchaToken}
       />
       ...
    </form>
  }
}

  1. After you got your captcha token, pass it from frontend to backend
  2. Add validation to you backend endpoint
class ValidateRecaptcha
  def call
    uri = URI('https://www.google.com/recaptcha/api/siteverify')

    response = Net::HTTP.post_form(uri,
                                   secret: secret_key, # secret_key you got from https://www.google.com/recaptcha/admin/create
                                   response: token_from_frontend)

    context.success = JSON.parse(response.body)['success'] # true or false
  rescue Net::OpenTimeout => e
    context.success = false
  end

  private

  def token_from_frontend
    context.params[:recaptchaToken]
  end

  def secret_key
    Rails.application.credentials.google_recaptcha_secret_key
  end
end

Idea is taken from this article https://dev.to/kumareth/implementing-google-recaptcha-with-react-and-node-js-1jgf

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