Skip to content

Latest commit

 

History

History
80 lines (65 loc) · 2.58 KB

captcha.mdx

File metadata and controls

80 lines (65 loc) · 2.58 KB
title description i18nReady type
Verify a Captcha
Learn how to create an API route and fetch it from the client.
true
recipe

import { Steps } from '@astrojs/starlight/components';

Server endpoints can be used as REST API endpoints to run functions such as authentications, database access, and verifications without exposing sensitive data to the client.

In this recipe, an API route is used to verify Google reCAPTCHA v3 without exposing the secret to clients.

Prerequisites

  • A project with SSR (output: 'server') enabled

Recipe

1. Create a `POST` endpoint that accepts recaptcha data, then verifies it with reCAPTCHA's API. Here, you can safely define secret values or read environment variables.
```js title="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 });
}
```
  1. Access your endpoint using fetch from a client script:

    <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) {
                // Captcha verification was a success
              } else {
                // Captcha verification failed
              }
            })
          }
        </script>
      </body>
    </html>