npm i @mac-barrett/svelte-recaptcha
<script lang="ts">
import { ReCaptcha } from '@mac-barrett/svelte-recaptcha';
let SITE_KEY = // your environment variable goes here
let Captcha: ReCaptcha;
</script>
<ReCaptcha bind:this={Captcha} { SITE_KEY } captchaStyle={{theme: 'dark', size: 'compact'}}/>
getRecaptchaResponse()
.formData.token = Captcha.getRecaptchaResponse();
if (formData.token.length === 0) {
return;
}
Captcha.getRecaptchaResponse()
along with any other formData you're sending to your server.const SECRET_KEY = // your environment variable goes here
export const POST: RequestHandler = async ({ request }) => {
const { formData } = await request.json();
// First arg is token from the captcha, second arg is your site's URL
// Yes you may use localhost
const CaptchaResponse = await verifyCaptcha(formData.token, 'localhost:8080');
if (!CaptchaResponse) {
return {
status: 400,
body: 'ReCaptcha Failed to authorize on server, please try again'
}
}
/* Captcha is verified, now you may handle the request as you normally would
Do stuff
Do other stuff...
*/
return {
status: 200,
body: 'Captcha Verified, success or what have you'
}
}
/**
* Calls the captcha API endpoint, returns true if captcha is succesful
*
* @param token ReCaptcha Token from the client
* @param host URL of the site making the request
* @returns Promise containing captcha's success status
*/
async function verifyCaptcha(token: string, host: string): Promise<boolean> {
const res = await fetch(`https://www.google.com/recaptcha/api/siteverify?secret=${SECRET_KEY}&response=${token}&remoteip=${host}`, { method: 'POST' });
const data: { success: boolean; } = await res.json();
return data.success;
}
<ReCaptcha SITE_KEY captchaStyle/>
// The SITE_KEY associated with your domain
export var SITE_KEY: string;
// Used to style the widget
export var captchaStyle: {theme?: 'light'|'dark', size?:'normal'|'compact'} = {
theme: 'light',
size: 'normal'
}
/** Returns the captcha's token if it has one. If no response it returns an empty string */
export function getRecaptchaResponse(): string {
return grecaptcha.getResponse();
}
That's all there is to know! If there are issues please let me know.