Install Universal keys on web pages

This document describes how you can install and integrate a Universal key with your web pages.

Before you begin

  1. Prepare your environment for Google Cloud Fraud Defense.

  2. Create a Universal key and configure domains.

Install Universal keys on your website

To install your Universal key and help protect your web pages, you can use the Google Cloud Fraud Defense AutoExecute configuration, the manual JavaScript installation, or both methods together across different endpoints using the same Universal key:

  • AutoExecute configuration (recommended): Automatically intercepts asynchronous network requests to configured URL paths and attaches the reCAPTCHA token to the request header.
  • Manual installation: Uses manual grecaptcha.enterprise.execute() calls or HTML button attributes. You can use this method on its own or alongside AutoExecute for network requests that AutoExecute doesn't support, requests that require custom token placement in the payload, or during incremental migrations to AutoExecute.

Depending on your integration approach, choose the appropriate option:

AutoExecute configuration

Fraud Defense AutoExecute can help simplify your frontend JavaScript integration through intercepting network requests on your web pages, eliminating the need to manually call grecaptcha.enterprise.execute() for each frontend action.

  • AutoExecute only intercepts asynchronous network requests initiated with the Fetch API or XMLHttpRequest, including requests from frameworks like AJAX that use these APIs.
  • AutoExecute is not supported for resources that load automatically at page load time. Instead, apply AutoExecute to network requests triggered by user actions on the page, such as a login button.
  • To prevent Fraud Defense challenges from causing network timeouts, apply timeouts directly to the requests. Use AbortSignal.timeout(n) for the Fetch API and the XMLHttpRequest.timeout property for XMLHttpRequest.

Add the script tag to your web pages

To load reCAPTCHA on your web page, add the JavaScript API with your Universal key within the <head></head> element of your web page:

<head>
  <script src="https://www.google.com/recaptcha/enterprise.js?render=KEY_ID"></script>
  ...
</head>

Fraud Defense uses the browser's language by default. If you want to specify a different language, use the hl=LANG attribute in your script. For example, to use French, specify the following:

<script src="https://www.google.com/recaptcha/enterprise.js?render=KEY_ID&hl=fr"></script>

To learn about the supported languages, see language codes for Fraud Defense.

Configure protected endpoints

The Fraud Defense script automatically integrates with network actions defined in the policy configuration of your Universal key. This section defines a mapping of URL paths (path) to action names (action).

If the Fraud Defense script detects an asynchronous network request to a mapped path, it intercepts the request, triggers a risk evaluation, and potentially displays a CAPTCHA challenge to the user before the original request continues. The generated response token is automatically attached to the X-Recaptcha-Token header in the request.

gcloud

To inspect the current policy configuration for your Universal key, use the gcloud alpha recaptcha policies describe command:

gcloud alpha recaptcha policies describe --key=KEY_ID

To update the policy configuration with your protected endpoints, create a YAML file (for example, POLICY.yaml) defining your protected paths and actions:

client_settings:
  allowedDomains:
    - example.com
  protected_endpoint_group:
    protected_endpoints:
      - path: "/login_api"
        action: login
      - path: "/register_api"
        action: register
      - path: "/cart_api/add/*"
        action: add_to_cart

Update your key configuration with the YAML file using the gcloud alpha recaptcha policies update command:

gcloud alpha recaptcha policies update \
    --key=KEY_ID \
    --policy=POLICY.yaml

REST API

To update the policy configuration to define protected endpoints using the REST API, use the projects.keys.updatePolicy method.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID
  • KEY_ID: the ID of your Universal key

HTTP method and URL:

PATCH https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/keys/KEY_ID/policy?updateMask=clientSettings.protectedEndpointGroup

Request JSON body:

{
"clientSettings": {
  "protectedEndpointGroup": {
    "protectedEndpoints": [
      {
        "path": "/login_api",
        "action": "login"
      },
      {
        "path": "/register_api",
        "action": "register"
      },
      {
        "path": "/cart_api/add/*",
        "action": "add_to_cart"
      }
    ]
  }
}
}

To send your request, expand one of these options:

If successful, the request returns the updated policy configuration.

You can configure up to 25 protected endpoints per Universal key. Each endpoint must meet the following requirements:

  • action: The action name must contain 1 to 100 characters, and use only letters, numbers, slashes (/), and underscores (_).
  • path (case-sensitive): The path must meet the following criteria:
    • Be unique, start with /, and contain 1 to 200 characters without consecutive slashes (//).
    • Include at least one non-wildcard segment (for example, cannot be /, /*, /**, or /*/).
    • Wildcards must occupy complete segments: * matches a single segment (for example, /api/*/login or /api/* are valid; /api/login* is invalid), and ** matches multiple segments as the final segment only (for example, /api/** is valid; /api/**/login is invalid).
  • Third-party requests: If third-party tools running on your page (such as analytics or partner scripts) send requests to paths that match your protected endpoints (for example, https://analytics.example.net/login matching /login), AutoExecute will also intercept them. This can cause extra network latency, skewed metrics, or unexpected CAPTCHA challenges. To avoid conflicts, ensure your protected paths are distinctive (for example, /auth/v1/login), or use the Manual installation if path collisions occur.
  • Cross-domain APIs: If your backend API is hosted on a different domain than your website (for example, examplecdn.net versus www.example.com), AutoExecute works automatically without extra domain configuration.

If matching against specific destination domains is important for your integration, file a feature request.

In your backend, get the response token from the X-Recaptcha-Token request header and create an assessment within two minutes.

Manual installation

We recommend that you add Fraud Defense verification on a user interaction that needs to be verified. For example, if you want to verify the submit action of a form, then you need to add Fraud Defense verification on the submit action.

Depending on where you want to add Fraud Defense verification, choose the appropriate option:

Add verification on a user interaction

  1. To load reCAPTCHA on your web page, add the JavaScript API with your Universal key within the <head></head> element of your web page:

    <head>
      <script src="https://www.google.com/recaptcha/enterprise.js?render=KEY_ID"></script>
      ...
    </head>
    

    Fraud Defense uses the browser's language by default. If you want to specify a different language, use the hl=LANG attribute in your script. For example, to use French, specify the following:

    <script src="https://www.google.com/recaptcha/enterprise.js?render=KEY_ID&hl=fr"></script>

    To learn about the supported languages, see language codes for Fraud Defense.

    If you want to specify a location for the badge, use badge=LOCATION as a query parameter in the script tag. For example, https://www.google.com/recaptcha/enterprise.js?render=KEY_ID&badge=bottomleft. By default, the location is set to bottomright. Other possible values are inline and bottomleft.

  2. To add Fraud Defense verification on a user interaction, do the following:

    1. To help ensure that grecaptcha.enterprise.execute() runs after the Fraud Defense library loads, use grecaptcha.enterprise.ready().
    2. Call grecaptcha.enterprise.execute() on each interaction that you want to protect with your Universal key. Specify a meaningful name for a user interaction in the action parameter. For more guidance, see Actions.

      The following example shows how to call grecaptcha.enterprise.execute() on a login action:

      <script>
        // Use `requestSubmit()` for extra features like browser input
        // validation.
        function onClick(e) {
          e.preventDefault();
          grecaptcha.enterprise.ready(async () => {
            const token = await grecaptcha.enterprise.execute(
              'KEY_ID',
              {action: 'LOGIN'}
            );
            // IMPORTANT: The 'token' that results from execute is an
            // encrypted response sent by Fraud Defense to
            // the end user's browser.
            // This token must be validated by creating an assessment.
            // See https://cloud.google.com/recaptcha/docs/create-assessment
          });
        }
      </script>
      
  3. After the token is generated, send the reCAPTCHA token to your backend and create an assessment within two minutes.

Add Fraud Defense on an HTML button

  1. To load reCAPTCHA on your web page, add the JavaScript API with your Universal key within the <head></head> element of your web page:

    <head>
      <script src="https://www.google.com/recaptcha/enterprise.js?render=KEY_ID"></script>
      ...
    </head>
    

    Fraud Defense uses the browser's language by default. If you want to specify a different language, use the hl=LANG attribute in your script. For example, to use French, specify the following:

    <script src="https://www.google.com/recaptcha/enterprise.js?render=KEY_ID&hl=fr"></script>

    To learn about the supported languages, see language codes for Fraud Defense.

  2. To add Fraud Defense on an HTML button, do the following:

    1. Define a callback function to handle the token.
    <script>
      function onSubmit(token) {
        document.getElementById("demo-form").submit();
      }
      // Use `requestSubmit()` for extra features like browser input
      // validation.
    </script>
    

    For more information, see the requestSubmit() method.

    1. Add attributes to your HTML button.
    <button class="g-recaptcha"
        data-sitekey="KEY_ID"
        data-callback="onSubmit"
        data-action="submit">Submit</button>
    

    If you want to specify a location for the badge, use the data-badge="LOCATION" attribute on the element that has class="g-recaptcha". By default, the location is set to bottomright. Other possible values are inline and bottomleft.

    1. When this button is used to submit a form on your site, the g-recaptcha-response POST parameter contains the response token.
  3. After the token is generated, send the reCAPTCHA token to your backend and create an assessment within two minutes.

What's next