### E2E Test Setup with Cypress (TypeScript) Source: https://developers.cloudflare.com/turnstile/llms-full.txt Example setup for E2E testing frameworks like Cypress. It intercepts requests to set a test environment header, allowing Turnstile to automatically pass verification during tests. ```typescript // Set test header for all test requests beforeEach(() => { cy.intercept('*', (req) => { req.headers['x-test-environment'] = 'secret-token'; }); }); // Your test can now interact with the form normally it('submits form successfully', () => { cy.visit('/your-form'); cy.get('form').submit(); // Turnstile will automatically pass verification }); ``` -------------------------------- ### Example: Importing a DNS Record Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources This example shows how to import a specific DNS A record for a zone. Replace 'example.com' with your zone name and 'your_record_id' with the actual record ID. ```bash terraform import cloudflare_record.example_record example.com-1234567890abcdef1234567890abcdef ``` -------------------------------- ### Example: Importing a Cloudflare Access Application Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources This example demonstrates importing a Cloudflare Access Application. The `resource_type.resource_name` is `cloudflare_access_application.my_app`, and the `resource_id` is the application's ID. ```bash terraform import cloudflare_access_application.my_app ``` -------------------------------- ### Install pnpm Source: https://developers.cloudflare.com/style-guide/contributions Install the pnpm package manager to preview your documentation edits. ```bash pnpm install ``` -------------------------------- ### Example: Importing a Cloudflare Zone Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources This example shows how to import an existing Cloudflare zone. The `resource_type.resource_name` is `cloudflare_zone.my_zone` and the `resource_id` is the zone's ID, which is typically its domain name. ```bash terraform import cloudflare_zone.my_zone example.com ``` -------------------------------- ### Install cf-terraforming Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources Install the cf-terraforming tool to manage Cloudflare resources with Terraform. ```bash go install github.com/cloudflare/cf-terraforming/cf-terraforming@latest ``` -------------------------------- ### Install Turnstile Pages Plugin with bun Source: https://developers.cloudflare.com/turnstile/llms-full.txt Install the Turnstile Pages Plugin using bun. ```bash bun add @cloudflare/pages-plugin-turnstile ``` -------------------------------- ### Install Turnstile Skill for OpenCode Source: https://developers.cloudflare.com/turnstile/llms-full.txt Installs the Turnstile skill locally for OpenCode by downloading the skill's markdown file. ```shell # OpenCodemkdir -p .opencode/skills/turnstile-spin && \ curl -sSL https://developers.cloudflare.com/turnstile/spin/index.md \ -o .opencode/skills/turnstile-spin/SKILL.md ``` -------------------------------- ### Example: Importing a Cloudflare Worker Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources This example shows how to import a Cloudflare Worker. The `resource_type.resource_name` is `cloudflare_worker_script.my_worker`, and the `resource_id` is the name of the worker. ```bash terraform import cloudflare_worker_script.my_worker ``` -------------------------------- ### Install cf-terraforming CLI Source: https://developers.cloudflare.com/turnstile/get-started/widget-management/terraform Install the `cf-terraforming` command-line tool using Go. This tool is used to generate Terraform configurations from existing Cloudflare resources. ```bash go install github.com/cloudflare/cf-terraforming/cmd/cf-terraforming@latest ``` -------------------------------- ### Install Turnstile Skill for Cursor Source: https://developers.cloudflare.com/turnstile/llms-full.txt Installs the Turnstile skill locally for Cursor by downloading the skill's markdown file. ```shell # Cursormkdir -p .cursor/rules && \ curl -sSL https://developers.cloudflare.com/turnstile/spin/index.md \ -o .cursor/rules/turnstile-spin.md ``` -------------------------------- ### Install Turnstile Plugin Source: https://developers.cloudflare.com/pages/functions/plugins/turnstile Install the Turnstile plugin using npm, yarn, pnpm, or bun. ```bash npm i @cloudflare/pages-plugin-turnstile ``` ```bash yarn add @cloudflare/pages-plugin-turnstile ``` ```bash pnpm add @cloudflare/pages-plugin-turnstile ``` ```bash bun add @cloudflare/pages-plugin-turnstile ``` -------------------------------- ### Example: Importing a Cloudflare Access Policy Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources This example shows how to import a Cloudflare Access Policy. The `resource_type.resource_name` is `cloudflare_access_policy.my_policy`, and the `resource_id` is a combination of the application ID and the policy ID, separated by a forward slash. ```bash terraform import cloudflare_access_policy.my_policy / ``` -------------------------------- ### Install Wrangler Source: https://developers.cloudflare.com/turnstile/spin Install the Wrangler CLI tool. Use the save-dev flag for Node.js projects. ```bash npm install --save-dev wrangler ``` ```bash npm install -g wrangler ``` -------------------------------- ### Install Turnstile Pages Plugin with npm Source: https://developers.cloudflare.com/turnstile/llms-full.txt Install the Turnstile Pages Plugin using npm. ```bash npm i @cloudflare/pages-plugin-turnstile ``` -------------------------------- ### Turnstile WAF Integration Example Source: https://developers.cloudflare.com/turnstile/tutorials/integrating-turnstile-waf-and-bot-management This snippet demonstrates how to integrate Turnstile with Cloudflare WAF. It shows the basic setup for enabling Turnstile checks within your WAF rules. ```javascript (() => { try { if (!matchMedia('(min-width: 50em)').matches) return; /** @type {HTMLElement | null} */ const target = document.querySelector('sl-sidebar-state-persist'); const state = JSON.parse(sessionStorage.getItem('sl-sidebar-state') || '0'); if (!target || !state || target.dataset.hash !== state.hash) return; window._starlightScrollRestore = state.scroll; customElements.define( 'sl-sidebar-restore', class SidebarRestore extends HTMLElement { connectedCallback() { try { const idx = parseInt(this.dataset.index || ''); const details = this.closest('details'); if (details && typeof state.open[idx] === 'boolean') details.open = state.open[idx]; } catch {} } } ); } catch {} })(); ``` -------------------------------- ### Get device Source: https://developers.cloudflare.com/api/resources/turnstile/subresources/widgets/methods/create Gets a device. ```APIDOC ## GET /api/resources/zero_trust/subresources/devices/subresources/devices/methods/get ### Description Gets a device. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/devices/subresources/devices/methods/get ``` -------------------------------- ### Install Turnstile Pages Plugin with yarn Source: https://developers.cloudflare.com/turnstile/llms-full.txt Install the Turnstile Pages Plugin using yarn. ```bash yarn add @cloudflare/pages-plugin-turnstile ``` -------------------------------- ### Example: Importing a Cloudflare Worker Route Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources This example demonstrates importing a Cloudflare Worker route. The `resource_type.resource_name` is `cloudflare_worker_route.my_route`, and the `resource_id` is a combination of the zone ID and the route pattern, separated by a forward slash. ```bash terraform import cloudflare_worker_route.my_route / ``` -------------------------------- ### Install Turnstile Pages Plugin with pnpm Source: https://developers.cloudflare.com/turnstile/llms-full.txt Install the Turnstile Pages Plugin using pnpm. ```bash pnpm add @cloudflare/pages-plugin-turnstile ``` -------------------------------- ### Turnstile Backend Integration Example Source: https://developers.cloudflare.com/turnstile/tutorials/integrating-turnstile-waf-and-bot-management This TypeScript example demonstrates how to verify a Turnstile token on your backend. Replace with your preferred language and framework. Ensure your site is on Cloudflare's network for WAF and Bot Management. ```typescript import { Request, Response, Router } from "express"; const router = Router(); router.post("/login", async (req: Request, res: Response) => { const { username, password, turnstileToken } = req.body; // Verify the Turnstile token const secret = process.env.TURNSTILE_SECRET_KEY; const verificationResponse = await fetch( "https://challenges.cloudflare.com/turnstile/v0/siteverify", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ secret: secret as string, response: turnstileToken as string, }), } ); const verificationData = await verificationResponse.json(); if (!verificationData.success) { return res.status(400).json({ message: "Invalid Turnstile token." }); } // Proceed with your authentication logic here // ... res.status(200).json({ message: "Login successful." }); }); export default router; ``` -------------------------------- ### Install Wrangler for Node.js Projects Source: https://developers.cloudflare.com/turnstile/llms-full.txt Use this command to install the Wrangler CLI as a development dependency in a Node.js project. ```bash npm install --save-dev wrangler ``` -------------------------------- ### Install Turnstile Skill for Claude Code Source: https://developers.cloudflare.com/turnstile/llms-full.txt Installs the Turnstile skill locally for Claude Code by downloading the skill's markdown file. ```shell # Claude Codemkdir -p .claude/skills/turnstile-spin && \ curl -sSL https://developers.cloudflare.com/turnstile/spin/index.md \ -o .claude/skills/turnstile-spin/SKILL.md ``` -------------------------------- ### Get Projects Source: https://developers.cloudflare.com/api/resources/turnstile Lists all projects. ```APIDOC ## GET /api/resources/pages/subresources/projects/methods/list ### Description Lists all projects. ### Method GET ### Endpoint /api/resources/pages/subresources/projects/methods/list ``` -------------------------------- ### Complete HTML Example for Contact Form Source: https://developers.cloudflare.com/turnstile/get-started/client-side-rendering A full HTML document demonstrating Turnstile integration within a contact form. This example includes basic form fields and the Turnstile widget. ```html Implicit Rendering with Cloudflare Turnstile

Contact Us






``` -------------------------------- ### Get Cloud Integration Setup Config Source: https://developers.cloudflare.com/api/resources/turnstile Retrieves the initial setup configuration for a Cloud Integration. This is helpful when setting up a new integration for the first time. ```APIDOC ## GET /api/resources/magic_cloud_networking/subresources/cloud_integrations/methods/initial_setup ### Description Retrieves the initial setup configuration for a Cloud Integration. ### Method GET ### Endpoint /api/resources/magic_cloud_networking/subresources/cloud_integrations/methods/initial_setup ### Parameters #### Query Parameters - **account_id** (string) - Required - The ID of the account. - **integration_id** (string) - Required - The ID of the Cloud Integration. ### Response #### Success Response (200) - **setup_config** (object) - The initial setup configuration details for the integration. ``` -------------------------------- ### Run Development Server Source: https://developers.cloudflare.com/style-guide/contributions Start the local development server to preview your documentation changes in real-time. ```bash pnpm run dev ``` -------------------------------- ### Get Turnstile Widget Data Source: https://developers.cloudflare.com/turnstile/get-started/widget-management/api Example of retrieving data associated with a Turnstile widget instance. This can be used to get the token or other bind data after the widget has been rendered. ```javascript const widgetData = turnstile.getData("#widget-container"); console.log("Widget data:", widgetData); ``` -------------------------------- ### Example: Importing a Firewall Rule Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources This snippet demonstrates importing a Cloudflare Firewall Rule. Provide the zone name and the rule's ID. ```bash terraform import cloudflare_firewall_rule.example_rule example.com-abcdef1234567890abcdef1234567890 ``` -------------------------------- ### Turnstile Server-Side Verification (Python) Source: https://developers.cloudflare.com/turnstile/plans This example demonstrates how to verify a Turnstile token on the server-side using Python with Flask. You will need to install the 'requests' library. ```python from flask import Flask, request, jsonify import requests app = Flask(__name__) CLOUDFLARE_SECRET_KEY = 'YOUR_CLOUDFLARE_SECRET_KEY' CLOUDFLARE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify' @app.route('/', methods=['POST']) def verify_turnstile(): token = request.form.get('cf-turnstile-token') if not token: return jsonify({'success': False, 'error': 'No token provided'}) data = { 'secret': CLOUDFLARE_SECRET_KEY, 'response': token } response = requests.post(CLOUDFLARE_VERIFY_URL, data=data) result = response.json() if result.get('success'): return jsonify({'success': True}) else: return jsonify({'success': False, 'error': result.get('error-codes')}) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Turnstile Server-Side Verification (Node.js) Source: https://developers.cloudflare.com/turnstile/plans This example demonstrates how to verify a Turnstile token on the server-side using Node.js. Ensure you have the Cloudflare Turnstile SDK installed. ```javascript const express = require('express'); const cfTurnstile = require('@cloudflare/turnstile-express'); const app = express(); app.use(cfTurnstile({ siteKey: 'YOUR_CLOUDFLARE_SITE_KEY', secret: 'YOUR_CLOUDFLARE_SECRET_KEY' })); app.post('/', (req, res) => { if (req.headers['cf-turnstile-token']) { // Token is valid, proceed with form submission res.send('Token verified!'); } else { // Token is invalid res.status(400).send('Invalid token'); } }); app.listen(3000, () => console.log('Server listening on port 3000')); ``` -------------------------------- ### Example: Importing a Zone Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources Import an entire Cloudflare zone. The resource ID is simply the zone's name. ```bash terraform import cloudflare_zone.example_zone example.com ``` -------------------------------- ### Getting Turnstile Widget ID Source: https://developers.cloudflare.com/turnstile/spin This example shows how to retrieve the widget ID for a specific Turnstile instance using `turnstile.getWidgetId`. This ID can be used with other Turnstile API functions like `reset`. ```javascript var widgetId = turnstile.getWidgetId("#cf-turnstile-container"); console.log("Turnstile Widget ID: " + widgetId); ``` -------------------------------- ### Upload Worker Module with Service Binding Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module This example shows how to upload a worker module and configure a service binding. It includes the account ID, zone ID, script name, and the service binding details. ```bash curl -X PUT "https://api.cloudflare.com/client/v4/zones/:zone_identifier/workers/script/:script_name" \ -H "X-Auth-Email: user@example.com" \ -H "X-Auth-Key: YOUR_GLOBAL_API_KEY" \ --data-binary @worker.js \ -F "metadata='{\"bindings\":[{\"name\":\"MY_SERVICE\",\"type\":\"service\",\"service\":\"my-worker-service\"}]}'" ``` -------------------------------- ### Initialize Navigation Links Source: https://developers.cloudflare.com/api/resources/turnstile Sets up navigation links based on screen width. It checks local storage for a preferred mode ('mobile' or 'desktop') and applies it to the document's class list. ```javascript function setupNavLinksInitial(){ let mode = localStorage.getItem("stl-nav-links-mode"); // initial guess if(mode === null){ mode = window.innerWidth < 1000 ? "mobile" : "desktop"; } document.documentElement.classList.add("stl-nav-links-mode-" + mode) } setupNavLinksInitial(); ``` -------------------------------- ### Healthchecks - Get Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Get Health Check Details. ```APIDOC ## GET /api/resources/healthchecks/methods/get ### Description Get Health Check Details. ### Method GET ### Endpoint /api/resources/healthchecks/methods/get ``` -------------------------------- ### List Prebuilt Policies Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Lists all available Prebuilt Policies for Catalog Syncs. ```APIDOC ## GET /api/resources/magic_cloud_networking/subresources/catalog_syncs/subresources/prebuilt_policies/methods/list ### Description Lists all available Prebuilt Policies for Catalog Syncs. ### Method GET ### Endpoint /api/resources/magic_cloud_networking/subresources/catalog_syncs/subresources/prebuilt_policies/methods/list ``` -------------------------------- ### Slots - Get Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Get information about the specified slot. ```APIDOC ## GET /api/resources/network_interconnects/subresources/slots/methods/get ### Description Get information about the specified slot. ### Method GET ### Endpoint /api/resources/network_interconnects/subresources/slots/methods/get ``` -------------------------------- ### Example: Importing a Workers Route Source: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources Import a Cloudflare Workers route. You need the zone name and the route's ID. ```bash terraform import cloudflare_workers_route.example_route example.com-abcdef1234567890abcdef1234567890 ``` -------------------------------- ### Get Advertisement Status Source: https://developers.cloudflare.com/api/resources/turnstile/subresources/widgets/methods/create Gets the advertisement status. ```APIDOC ## GET /api/resources/addressing/subresources/prefixes/subresources/advertisement_status/methods/get ### Description Gets the advertisement status. ### Method GET ### Endpoint /api/resources/addressing/subresources/prefixes/subresources/advertisement_status/methods/get ``` -------------------------------- ### Start livestreaming a meeting Source: https://developers.cloudflare.com/api/resources/turnstile/subresources/widgets/methods/create Starts a livestream for a meeting. ```APIDOC ## POST /api/resources/realtime_kit/subresources/livestreams/methods/start_livestreaming_a_meeting ### Description Starts livestreaming for a meeting. ### Method POST ### Endpoint /api/resources/realtime_kit/subresources/livestreams/methods/start_livestreaming_a_meeting ``` -------------------------------- ### Logpush - Jobs - Get Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Get Logpush job details. ```APIDOC ## GET /api/resources/logpush/subresources/jobs/methods/get ### Description Get Logpush job details. ### Method GET ### Endpoint /api/resources/logpush/subresources/jobs/methods/get ``` -------------------------------- ### Create a Turnstile Widget (Go) Source: https://developers.cloudflare.com/api/resources/turnstile/subresources/widgets/methods/create This Go example demonstrates creating a Turnstile widget with the Cloudflare Go SDK. ```go widget, err := cloudflare.Turnstile.Widgets.Create({ Name: "My Widget", // ... other widget options }) if err != nil { // Handle error } ``` -------------------------------- ### Get device (deprecated) Source: https://developers.cloudflare.com/api/resources/turnstile/subresources/widgets/methods/create Gets a device. This method is deprecated. ```APIDOC ## GET /api/resources/zero_trust/subresources/devices/methods/get ### Description Gets a device. This method is deprecated. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/devices/methods/get ``` -------------------------------- ### Healthchecks - Previews - Get Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Get Health Check Preview Details. ```APIDOC ## GET /api/resources/healthchecks/subresources/previews/methods/get ### Description Get Health Check Preview Details. ### Method GET ### Endpoint /api/resources/healthchecks/subresources/previews/methods/get ``` -------------------------------- ### Optimize Performance with Resource Hints Source: https://developers.cloudflare.com/turnstile/get-started/client-side-rendering Place this link tag in your HTML before the Turnstile script to establish early connections to Cloudflare servers, improving loading performance. ```html ``` -------------------------------- ### Diagnostics - Endpoint Healthchecks - Get Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Get an Endpoint Health Check. ```APIDOC ## GET /api/resources/diagnostics/subresources/endpoint-healthchecks/methods/get ### Description Get an Endpoint Health Check. ### Method GET ### Endpoint /api/resources/diagnostics/subresources/endpoint-healthchecks/methods/get ``` -------------------------------- ### Start Tail Source: https://developers.cloudflare.com/api/resources/turnstile Starts a new tail connection for a Cloudflare Worker. ```APIDOC ## POST /api/resources/workers/subresources/scripts/subresources/tail/methods/create ### Description Starts a new tail connection for a Cloudflare Worker. ### Method POST ### Endpoint /api/resources/workers/subresources/scripts/subresources/tail/methods/create ``` -------------------------------- ### Initialize and Plan Terraform Configuration Source: https://developers.cloudflare.com/turnstile/get-started/widget-management/terraform Initialize your Terraform working directory to download the necessary provider plugins. Then, plan the changes to see what Terraform will apply to your infrastructure. ```Shell terraform init terraform plan ``` -------------------------------- ### Logpush - Edge - Create Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Create an Instant Logs job. ```APIDOC ## POST /api/resources/logpush/subresources/edge/methods/create ### Description Create an Instant Logs job. ### Method POST ### Endpoint /api/resources/logpush/subresources/edge/methods/create ``` -------------------------------- ### Create Project Source: https://developers.cloudflare.com/api/resources/turnstile Creates a new project. ```APIDOC ## POST /api/resources/pages/subresources/projects/methods/create ### Description Creates a new project. ### Method POST ### Endpoint /api/resources/pages/subresources/projects/methods/create ``` -------------------------------- ### Turnstile Widget - Getting the Token Source: https://developers.cloudflare.com/turnstile/concepts/widget This snippet shows how to retrieve the Turnstile token programmatically using the get turnstile.getResponse() method. ```javascript const token = turnstile.getResponse(); console.log('Token:', token); ``` -------------------------------- ### Magic Cloud Networking Prebuilt Policies Source: https://developers.cloudflare.com/api/resources/turnstile List Prebuilt Policies associated with Catalog Syncs. ```APIDOC ## List Prebuilt Policies. ### Description Lists all available Prebuilt Policies for Catalog Syncs. ### Method GET ### Endpoint /api/resources/magic_cloud_networking/subresources/catalog_syncs/subresources/prebuilt_policies/methods/list ``` -------------------------------- ### Create account configuration Source: https://developers.cloudflare.com/api/resources/turnstile Creates a new account-level network monitoring configuration. This sets up the initial parameters for monitoring. ```APIDOC ## POST /api/resources/magic_network_monitoring/subresources/configs/methods/create ### Description Creates a new account-level network monitoring configuration. ### Method POST ### Endpoint /api/resources/magic_network_monitoring/subresources/configs/methods/create ### Parameters #### Query Parameters - **account_id** (string) - Required - The ID of the account. #### Request Body - **vpc_flow_settings** (object) - Optional - Initial settings for VPC flow monitoring. - **rule_settings** (object) - Optional - Initial settings for network rules. ### Request Example ```json { "vpc_flow_settings": { "enabled": true, "export_destination": "s3://my-bucket/logs" } } ``` ### Response #### Success Response (200) - **config** (object) - The newly created account configuration object. ``` -------------------------------- ### Create a Bookmark application Source: https://developers.cloudflare.com/api/resources/turnstile Creates a new Bookmark application. ```APIDOC ## POST /api/resources/zero_trust/subresources/access/subresources/bookmarks/methods/create ### Description Creates a new Bookmark application. ### Method POST ### Endpoint /api/resources/zero_trust/subresources/access/subresources/bookmarks/methods/create ``` -------------------------------- ### Install Wrangler Globally Source: https://developers.cloudflare.com/turnstile/spin Use this command to install Wrangler globally if you are in a Node.js project and 'npx wrangler' fails with 'command not found'. ```bash npm install -g wrangler ``` -------------------------------- ### Create account configuration Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Creates a new account configuration for Magic Network Monitoring. ```APIDOC ## POST /api/resources/magic_network_monitoring/subresources/configs/methods/create ### Description Creates a new account configuration for Magic Network Monitoring. ### Method POST ### Endpoint /api/resources/magic_network_monitoring/subresources/configs/methods/create ### Parameters #### Request Body (No specific request body fields are detailed in the source) ### Response #### Success Response (200) (No specific response fields are detailed in the source) ### Request Example (No example provided in the source) ### Response Example (No example provided in the source) ``` -------------------------------- ### Node.js Turnstile Validation Source: https://developers.cloudflare.com/turnstile/get-started/server-side-validation Validate a Turnstile token using Node.js. Ensure you have the 'axios' package installed (`npm install axios`). ```javascript const axios = require('axios'); const secretKey = 'YOUR_TURNSTILE_SECRET_KEY'; const token = 'USER_TOKEN_FROM_REQUEST'; async function validateToken(token) { try { const response = await axios.post('https://challenges.cloudflare.com/turnstile/v0/siteverify', null, { params: { secret: secretKey, response: token } }); if (response.data.success) { console.log('Token is valid!'); // Token is valid, proceed with your action return true; } else { console.error('Token validation failed:', response.data['error-codes']); // Token is invalid, handle accordingly return false; } } catch (error) { console.error('Error validating token:', error); // Handle network or other errors return false; } } // Example usage: // validateToken(token); ``` -------------------------------- ### Turnstile with Advanced Options Source: https://developers.cloudflare.com/turnstile/spin This example demonstrates how to configure Turnstile with additional options such as 'theme', 'action', and 'cffluid'. These options allow for customization of the widget's appearance and behavior. ```html
``` -------------------------------- ### Initialize Turnstile with Pre-clearance Source: https://developers.cloudflare.com/turnstile/concepts/pre-clearance-support This snippet shows how to initialize the Turnstile widget with pre-clearance enabled. You need to provide a `client` token obtained from a previous challenge. ```javascript turnstile.render('my-widget-id', { sitekey: 'YOUR_CLOUDFLARE_SITE_KEY', client: 'PREVIOUSLY_OBTAINED_CLIENT_TOKEN' }); ``` -------------------------------- ### Install Wrangler Locally Source: https://developers.cloudflare.com/turnstile/spin Install Wrangler as a development dependency for non-Node.js projects like Hugo or vanilla HTML. This is the only Node dependency Spin requires. ```bash npm init -ynpm install --save-dev wrangler ``` -------------------------------- ### List your device posture integrations Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Lists all available device posture integrations. ```APIDOC ## GET /api/resources/zero_trust/subresources/devices/subresources/posture/subresources/integrations/methods/list ### Description Lists your device posture integrations. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/devices/subresources/posture/subresources/integrations/methods/list ``` -------------------------------- ### Create a device posture integration Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Creates a new device posture integration. ```APIDOC ## POST /api/resources/zero_trust/subresources/devices/subresources/posture/subresources/integrations/methods/create ### Description Creates a device posture integration. ### Method POST ### Endpoint /api/resources/zero_trust/subresources/devices/subresources/posture/subresources/integrations/methods/create ``` -------------------------------- ### Turnstile Callback Function Example Source: https://developers.cloudflare.com/turnstile/get-started/widget-management/api An example of a JavaScript callback function that is executed when the Turnstile widget successfully verifies the user. The function receives a token as an argument. ```javascript function myCallbackFunction(token) { // Send the token to your backend for verification console.log('Turnstile token received:', token); // Example: fetch('/verify-token', { method: 'POST', body: JSON.stringify({ token: token }) }) } ``` -------------------------------- ### Clip videos given a start and end time Source: https://developers.cloudflare.com/api/resources/turnstile Creates a video clip by specifying a start and end time. This feature allows for extracting segments from existing videos. ```APIDOC ## POST /api/resources/stream/subresources/clip/methods/create ### Description Creates a video clip by specifying a start and end time. ### Method POST ### Endpoint /api/resources/stream/subresources/clip/methods/create ``` -------------------------------- ### List SSL Configurations Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Lists all SSL configurations. ```APIDOC ## GET /api/resources/custom_certificates/methods/list ### Description Lists SSL configurations. ### Method GET ### Endpoint /api/resources/custom_certificates/methods/list ``` -------------------------------- ### Turnstile Widget Initialization with Data-Theme (JavaScript) Source: https://developers.cloudflare.com/turnstile/migration/hcaptcha This example initializes the Turnstile widget and sets 'data-theme' to 'light'. This is an alternative to the 'theme' parameter. ```javascript function onloadCallback() { turnstile.render("#challenge-id", { sitekey: "YOUR_CF_WIDGET_SITEKEY", "data-theme": "light", callback: function(token) { console.log("Turnstile token: " + token); }, }); } ``` -------------------------------- ### Successful API Response Example Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module This is an example of a successful response when uploading a Worker module. It includes details about the deployed script such as its ID, creation date, and deployment status. ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "result": { "startup_time_ms": 10, "id": "this-is_my_script-01", "compatibility_date": "2021-01-01", "compatibility_flags": [ "nodejs_compat" ], "created_on": "2022-05-05T05:15:11.602148Z", "entry_point": "index.js", "etag": "777f24a43bef5f69174aa69ceaf1dea67968d510a31d1vw3e49d34a0187c06d1", "handlers": [ "fetch" ], "has_assets": false, "has_modules": false, "last_deployed_from": "wrangler", "logpush": false, "migration_tag": "v1", "modified_on": "2022-05-20T19:02:56.446492Z", "named_handlers": [ { "handlers": [ "class" ], "name": "MyDurableObject" } ], "observability": { "enabled": true, "head_sampling_rate": 0.1, "logs": { "enabled": true, "invocation_logs": true, "destinations": [ "cloudflare" ], "head_sampling_rate": 0.1, "persist": true }, "traces": { "destinations": [ "cloudflare" ], "enabled": true, "head_sampling_rate": 0.1, "persist": true, "propagation_policy": "authenticated" } }, "placement": { "mode": "smart", "last_analyzed_at": "2025-01-01T00:00:00Z", "status": "SUCCESS" }, "placement_mode": "smart", "placement_status": "SUCCESS", "tag": "e8f70fdbc8b1fb0b8ddb1af166186758", "tags": [ "my-team", "my-public-api" ], "tail_consumers": [ { "service": "my-log-consumer", "environment": "production", "namespace": "my-namespace" } ], "usage_model": "standard" }, "success": true } ``` -------------------------------- ### Environment Configuration for Turnstile Keys Source: https://developers.cloudflare.com/turnstile/troubleshooting/testing Set up different Turnstile sitekeys and secret keys for development, testing, and production environments using .env files. ```bash # .env.development TURNSTILE_SITEKEY=1x00000000000000000000AATURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA # .env.test TURNSTILE_SITEKEY=2x00000000000000000000ABTURNSTILE_SECRET_KEY=2x0000000000000000000000000000000AA # .env.production TURNSTILE_SITEKEY=your-real-sitekeyTURNSTILE_SECRET_KEY=your-real-secret-key ``` -------------------------------- ### Turnstile Widget with Explicit Rendering and Options Source: https://developers.cloudflare.com/turnstile/concepts/widget This example demonstrates explicit rendering with additional configuration options like theme, size, and language. ```javascript turnstile.render('#widget-container', { sitekey: 'YOUR_CLOUDFLARE_SITE_KEY', callback: myCallbackFunction, action: 'my-action', theme: 'light', size: 'compact', language: 'fr' }); ``` -------------------------------- ### Turnstile Client-Side Configuration Example Source: https://developers.cloudflare.com/turnstile/reference/supported-languages Example of how to configure the Turnstile widget's language using a client-side attribute. This snippet demonstrates setting the language to Arabic (Egypt). ```html
``` -------------------------------- ### Client-Side Integration: Use Injected Sitekey Source: https://developers.cloudflare.com/turnstile/tutorials/excluding-turnstile-from-e2e-tests Demonstrates how to use the sitekey passed from the server-side to configure the Turnstile widget on the client-side. ```html
``` -------------------------------- ### Zero Trust Devices Management Source: https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module Endpoints for managing Zero Trust devices, including listing, getting, deleting, and revoking device registrations. Note: Some list and get methods are deprecated. ```APIDOC ## GET /api/resources/zero_trust/subresources/devices/methods/list ### Description Lists devices (deprecated). ### Method GET ### Endpoint /api/resources/zero_trust/subresources/devices/methods/list ### Response #### Success Response (200) - **devices** (array) - A list of devices. ## GET /api/resources/zero_trust/subresources/devices/methods/get ### Description Gets a device (deprecated). ### Method GET ### Endpoint /api/resources/zero_trust/subresources/devices/methods/get ### Parameters #### Query Parameters - **id** (string) - Required - The ID of the device to retrieve. ### Response #### Success Response (200) - **device** (object) - The details of the device. ## GET /api/resources/zero_trust/subresources/devices/subresources/devices/methods/list ### Description Lists devices. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/devices/subresources/devices/methods/list ### Response #### Success Response (200) - **devices** (array) - A list of devices. ## GET /api/resources/zero_trust/subresources/devices/subresources/devices/methods/get ### Description Gets a device. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/devices/subresources/devices/methods/get ### Parameters #### Query Parameters - **id** (string) - Required - The ID of the device to retrieve. ### Response #### Success Response (200) - **device** (object) - The details of the device. ## DELETE /api/resources/zero_trust/subresources/devices/subresources/devices/methods/delete ### Description Deletes a device. ### Method DELETE ### Endpoint /api/resources/zero_trust/subresources/devices/subresources/devices/methods/delete ### Parameters #### Request Body - **id** (string) - Required - The ID of the device to delete. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. ## POST /api/resources/zero_trust/subresources/devices/subresources/devices/methods/revoke ### Description Revokes device registrations. ### Method POST ### Endpoint /api/resources/zero_trust/subresources/devices/subresources/devices/methods/revoke ### Parameters #### Request Body - **device_ids** (array) - Required - A list of device IDs to revoke registrations for. - **id** (string) - Required - The ID of the device. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. ``` -------------------------------- ### Turnstile Widget with Options Source: https://developers.cloudflare.com/turnstile/get-started This example demonstrates how to configure the Turnstile widget with various options such as theme, action, and data attributes. These options allow for customization of the widget's appearance and behavior. ```html
``` -------------------------------- ### Turnstile Error Callback Function Example Source: https://developers.cloudflare.com/turnstile/get-started/widget-management/api An example of a JavaScript error callback function that is executed if the Turnstile widget encounters an error during verification. The function receives an error code as an argument. ```javascript function myErrorCallbackFunction(error) { console.error('Turnstile error:', error); // Handle the error appropriately, e.g., show a message to the user } ``` -------------------------------- ### Flagship Apps Methods Source: https://developers.cloudflare.com/api/resources/turnstile Methods for managing Flagship applications, including listing, getting, creating, and updating them. ```APIDOC ## GET /api/resources/flagship/subresources/apps/methods/list ### Description List apps. ### Method GET ### Endpoint /api/resources/flagship/subresources/apps/methods/list ## GET /api/resources/flagship/subresources/apps/methods/get ### Description Get an app. ### Method GET ### Endpoint /api/resources/flagship/subresources/apps/methods/get ## POST /api/resources/flagship/subresources/apps/methods/create ### Description Create an app. ### Method POST ### Endpoint /api/resources/flagship/subresources/apps/methods/create ## PUT /api/resources/flagship/subresources/apps/methods/update ### Description Update an app. ### Method PUT ### Endpoint /api/resources/flagship/subresources/apps/methods/update ``` -------------------------------- ### Flagship App Create Source: https://developers.cloudflare.com/api/resources/turnstile/subresources/widgets/methods/create Creates a new Flagship application. ```APIDOC ## POST /api/resources/flagship/subresources/apps/methods/create ### Description Creates a new Flagship application. ### Method POST ### Endpoint /api/resources/flagship/subresources/apps/methods/create ``` -------------------------------- ### Turnstile Widget Initialization with Data-Iou (JavaScript) Source: https://developers.cloudflare.com/turnstile/migration/hcaptcha This example initializes the Turnstile widget and includes 'data-iou'. This parameter is for specific integration needs and might require Cloudflare assistance. ```javascript function onloadCallback() { turnstile.render("#challenge-id", { sitekey: "YOUR_CF_WIDGET_SITEKEY", "data-iou": "YOUR_IOU_VALUE", callback: function(token) { console.log("Turnstile token: " + token); }, }); } ``` -------------------------------- ### List all targets Source: https://developers.cloudflare.com/api/resources/turnstile/subresources/widgets/methods/create Lists all targets configured for infrastructure. ```APIDOC ## GET /api/resources/zero_trust/subresources/access/subresources/infrastructure/subresources/targets/methods/list ### Description Lists all targets configured for infrastructure. ### Method GET ### Endpoint /api/resources/zero_trust/subresources/access/subresources/infrastructure/subresources/targets/methods/list ```