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:
-
Add package to react app
yarn add react-google-recaptcha
-
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>
}
}
- After you got your captcha token, pass it from frontend to backend
- 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