Verify a Captcha
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
Section titled Prerequisites- A project with SSR (
output: 'server'
) enabled
Recipe
Section titled Recipe-
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.src/ pages/ recaptcha.js export async function post({ request }) { const data = await request.json(); const recaptchaURL = 'https://www.google.com/recaptcha/api/siteverify'; const requestBody = { 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", body: JSON.stringify(requestBody) }); const responseData = await response.json(); return new Response(JSON.stringify(responseData), { status: 200 }); }
-
Access your endpoint using
fetch
from a client script:src/ pages/ index.astro <html> <head> <script 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>
More recipes
-
Share State Between Islands
Learn how to share state across components — and frameworks! — with Nano Stores.
-
Add an RSS feed
Let users subscribe to your content by adding an RSS feed to your Astro site.
-
Installing a Vite or Rollup plugin
Learn how you can import YAML data by adding a Rollup plugin to your project.
-
Build Forms With API Routes
Learn how to use JavaScript to send form submissions to an API Route
-
Build HTML Forms in Astro Pages
Learn how to build HTML forms and handle submissions in your frontmatter
-
Verify a Captcha
Learn how to verify a user is human using a “recaptcha” API route.
-
Build your Astro Site with Docker
Learn how to build your Astro site using Docker.
-
Add i18n features
Use dynamic routing and content collections to add internationalization support to your Astro site.