Skip to content

Instantly share code, notes, and snippets.

@narennaik
Last active August 11, 2020 09:46
Show Gist options
  • Save narennaik/d8deb480fd68ab1e6bd8e6b0c997ef31 to your computer and use it in GitHub Desktop.
Save narennaik/d8deb480fd68ab1e6bd8e6b0c997ef31 to your computer and use it in GitHub Desktop.
Google Recaptcha V2 implementation snippet with typescript, React & node
// Client Side, React component
import { GOOGLE_RECAPTCHA_URL } from '../../../common/constants';
import { INVALID_CAPTCHA_PROVIDED } from '../../utils/constants';
import { MyWindow } from '../../../common/types/global';
import React from 'react';
import { RecaptchaResponse } from '../../../common/types/thirdParty';
import { SignupFormWithCaptcha } from '../../../common/types/signup';
const onRecaptchaScriptLoad = (): void => {
window.grecaptcha.render('signup-recaptcha', {
sitekey: siteKey,
});
};
export const resetCaptcha = (): void => {
window.grecaptcha.reset();
};
export const getCaptchaValue = (): string => {
return window.grecaptcha.getResponse() || '';
};
export const loadScript = (): void => {
const script = document.createElement('script');
// onload method in the url should have the same name as the one being attached to window object
script.src = `${GOOGLE_RECAPTCHA_URL}?onload=onRecaptchaScriptLoad&render=explicit`;
script.async = true;
script.defer = true;
document.body.appendChild(script);
};
// Generated siteKey with google admin page
const siteKey = (window as MyWindow).conf.siteKey;
export const Recaptcha: React.FC<{}> = () => {
React.useEffect(() => {
(window as MyWindow).onRecaptchaScriptLoad = onRecaptchaScriptLoad;
loadScript();
}, []);
return <div id="signup-recaptcha" />;
};
// Server Code
export const validateRecaptchaResponse = async (
payload: SignupFormWithCaptcha,
): Promise<RecaptchaResponse> => {
const url = getEndpoint('google.recaptcha');
const { captchaResponse } = payload;
const params = {
// recaptcha response/value sent from client
response: captchaResponse,
// get secret from .env file?
secret: getPropertyFromEnvironment('RECAPTCHA_SITE_SECRET'),
};
const response = await axios<RecaptchaResponse>({
method: 'post',
url,
params,
});
if (response.success) {
return response;
} else {
throw new Error(INVALID_CAPTCHA_PROVIDED);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment