Last active
August 11, 2020 09:46
-
-
Save narennaik/d8deb480fd68ab1e6bd8e6b0c997ef31 to your computer and use it in GitHub Desktop.
Google Recaptcha V2 implementation snippet with typescript, React & node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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