Salta ai contenuti

Verifica un Captcha

Gli endpoints del server possono essere utilizzati come endpoint API REST per eseguire funzioni come autenticazioni, accesso al database e verifiche senza esporre dati sensibili al client.

In questa ricetta, un percorso API viene utilizzato per verificare Google reCAPTCHA v3 senza esporre il secret ai client.

  • Un progetto con SSR (output: 'server') abilitato
  1. Crea un endpoint POST che accetta i dati di recaptcha, quindi li verifica con l’API di reCAPTCHA. Qui puoi definire in modo sicuro i valori segreti o leggere le variabili di ambiente.

    src/pages/recaptcha.js
    export async function POST({ request }) {
    const data = await request.json();
    const recaptchaURL = 'https://www.google.com/recaptcha/api/siteverify';
    const requestHeaders = {
    'Content-Type': 'application/x-www-form-urlencoded'
    };
    const requestBody = new URLSearchParams({
    secret: "YOUR_SITE_SECRET_KEY", // This can be an environment variable
    response: data.recaptcha // The token passed in from the client
    });
    const response = await fetch(recaptchaURL, {
    method: "POST",
    headers: requestHeaders,
    body: requestBody.toString()
    });
    const responseData = await response.json();
    return new Response(JSON.stringify(responseData), { status: 200 });
    }
  2. Accedi al tuo endpoint utilizzando fetch da uno script client:

    src/pages/index.astro
    <html>
    <head>
    <script is:inline src="https://www.google.com/recaptcha/api.js"></script>
    </head>
    <body>
    <button class="g-recaptcha"
    data-sitekey="PUBLIC_SITE_KEY"
    data-callback="onSubmit"
    data-action="submit"> Click me to verify the captcha challenge! </button>
    <script is:inline>
    function onSubmit(token) {
    fetch("/recaptcha", {
    method: "POST",
    body: JSON.stringify({ recaptcha: token })
    })
    .then((response) => response.json())
    .then((gResponse) => {
    if (gResponse.success) {
    // La verifica Captcha è riuscita
    } else {
    // La verifica Captcha è fallita
    }
    })
    }
    </script>
    </body>
    </html>