Install Universal keys on web pages

A Fraud Defense Universal key helps protect your web applications and API endpoints against automated bot attacks, credential abuse, and fraud. By using a Universal key, you can deploy protections across your website with automated network request interception (AutoExecute), manual JavaScript execution, or a combination of both methods.

Before you begin

  1. Prepare your environment for Google Cloud Fraud Defense.

  2. Create a Universal key.

  3. Configure domains for your Universal key.

  4. To view the Status column for protected endpoints in the Google Cloud console, make sure you have the Cloud Monitoring monitoring.timeSeries.list permission. This permission is included in the predefined Fraud Defense roles: reCAPTCHA Enterprise Admin, reCAPTCHA Enterprise Editor, and reCAPTCHA Enterprise Viewer.

Install Universal keys on your website

To install your Universal key and help protect your web pages, you can use the 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.

Configure AutoExecute

AutoExecute can help simplify your frontend JavaScript integration by intercepting network requests on your web pages and eliminating manual grecaptcha.enterprise.execute() calls for each frontend action.

How AutoExecute works

The Fraud Defense script automatically integrates with network actions defined in the policy configuration of your Universal key. When the script detects an asynchronous network request to a configured 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.

Supported network APIs

AutoExecute only intercepts asynchronous network requests initiated by the following APIs (including frameworks like AJAX that rely on them):

API name Timeout configuration Implementation example
Fetch API Set timeouts using the AbortSignal controller. AbortSignal.timeout(n)
XMLHttpRequest Set timeouts using the native .timeout property. xhr.timeout = n

Integration best practices

  • User-triggered actions only: AutoExecute doesn't support resources that load automatically during page load. To avoid integration failure, only apply AutoExecute to requests triggered by explicit user interactions (for example, clicking a login or submit button).
  • Prevent latency timeouts: Fraud Defense challenge flows can occasionally cause network delays. To prevent client-side timeouts, always configure explicit request timeouts directly using the mechanisms listed in the table.
  • Protect sensitive paths only: Specify protectedEndpoints only for sensitive paths, and use a meaningful name for the user interaction in the action parameter. Avoid protecting every endpoint, because triggering Fraud Defense on every backend request can negatively impact performance. For more guidance, see Actions.

Add the script tag to your web pages

To load Fraud Defense 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

To configure protected endpoints for your Universal key, select a tab:

Console

  1. In the Google Cloud console, go to the Fraud Defense page.

    Go to Fraud Defense

  2. On the console toolbar, check that your project appears in the resource selector. If not, click the resource selector, and then select your project.

  3. Select the Keys tab.

    The Keys tab has two views: Cards and Table. If your project has many keys, only the Table view is available.

  4. In the reCAPTCHA keys section, locate the Universal key that you want to configure:

    • In the Cards view, click Key details on the key card.
    • In the Table view, click the name of the key.
  5. On the Key details page, click the Integration tab.

  6. In the Add reCAPTCHA to your website step, select the AutoExecute (recommended) tab.

    Optional: To manually protect specific endpoints, click the Manual tab to view the grecaptcha.enterprise.execute() code snippet.

  7. In the Protected endpoints section, click Add endpoint to configure each endpoint that you want to protect:

    1. In the Action field, enter a name for the user interaction. For example, login, register, or add_to_cart. For more guidance, see Actions.
    2. In the Path field, enter the unique URL path or glob pattern to intercept. For example, /login_api, /register_api, or /cart_api/add/*.
    3. Optional: To add another endpoint, click Add endpoint.
  8. Click Save to save your protected endpoints.

After you save your configuration, the Status column in the Protected endpoints table indicates whether Fraud Defense received traffic for each action in the last 24 hours. Traffic status can take 10 minutes to update after an endpoint first receives traffic.

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:

clientSettings:
  allowedDomains:
    - example.com
  protectedEndpointGroup:
    protectedEndpoints:
      - 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

Request JSON body:

{
"clientSettings": {
  "allowedDomains": [
    "example.com"
  ],
  "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.

Protected endpoint syntax and limits

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.

Path matching behavior

AutoExecute evaluates protected endpoints sequentially from top to bottom against the URL path only. It ignores the destination domain, scheme, and query parameters. This behavior has the following practical implications:

  • Path matching order: AutoExecute applies the first matching endpoint. If no endpoint matches, AutoExecute doesn't intercept the request. Place specific paths before wildcard patterns to avoid shadowing more specific routes. For example, list /mysite/login before /*/login.
  • 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 also intercepts 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 manual installation if path collisions occur.
  • Cross-domain APIs: If your backend API is hosted on a different domain than your website (for example, cdn.example.com 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.

Verify tokens in your backend

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.

    2. 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.

    3. 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