Skip to content

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.

  • A project with SSR (output: 'server') enabled
  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.

    export async function POST({ request }) {
    const data = await request.json();
    const recaptchaURL = '';
    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. Access your endpoint using fetch from a client script:

    <script is:inline src=""></script>
    <button class="g-recaptcha"
    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

What’s on your mind?

Create GitHub Issue

Quickest way to alert our team of a problem.