Skip to content

Instantly share code, notes, and snippets.

@raddeus
Created April 4, 2020 06:14
Show Gist options
  • Save raddeus/6125757e9e850cd942b5251416528b99 to your computer and use it in GitHub Desktop.
Save raddeus/6125757e9e850cd942b5251416528b99 to your computer and use it in GitHub Desktop.
React ReCAPTCHA v3
import React, { useEffect, useState } from 'react';
// Set this to your public ReCAPTCHA client key
const RECAPTCHA_SITE_KEY = 'YOUR_KEY_HERE';
// Set this to your backend URL that verifies ReCAPTCHA tokens
const RECAPTCHA_VERIFY_URL = 'http://www.mocky.io/v2/5e88253631000025303f4835';
/**
* Sends a request to your server to verify the given token
* This makes a few assumptions about your server
* 1. Your server takes a "token" GET parameter with the token
* 2. Your server responds with a 200 status code if successful
* 3. Your server responds with a non-200 status code if not successful
*/
const verifyRecaptchaToken = async (token) => {
const response = await fetch(`${RECAPTCHA_VERIFY_URL}?token=${token}`);
return response.status === 200;
};
const App = () => {
const [recaptchaLoading, setRecaptchaLoading] = useState(false);
const [recaptchaSuccess, setRecaptchaSuccess] = useState(false);
const [recaptchaError, setRecaptchaError] = useState(false);
useEffect(() => {
setRecaptchaLoading(true);
const script = document.createElement('script');
script.src = `https://www.google.com/recaptcha/api.js?render=${RECAPTCHA_SITE_KEY}`;
script.addEventListener('load', () => {
window.grecaptcha.ready(async () => {
try {
const token = await window.grecaptcha.execute(RECAPTCHA_SITE_KEY, {
action: 'homepage',
});
const isValidToken = await verifyRecaptchaToken(token);
setRecaptchaSuccess(isValidToken);
setRecaptchaError(!isValidToken);
} catch (e) {
console.log('Failed to get token', e);
setRecaptchaError(true);
} finally {
setRecaptchaLoading(false);
}
});
});
document.body.appendChild(script);
}, []);
return (
<div>
{recaptchaLoading && <p>ReCAPTCHA Loading...</p>}
{recaptchaError && <p>ReCAPTCHA Error</p>}
{recaptchaSuccess && <p>ReCAPTCHA Success!</p>}
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment