Use Cases

Use cases

import { CardGrid, Description, LinkTitleCard } from "~/components";

Select a category below to find the Cloudflare solutions, features, and architecture patterns that apply to your use case.

Build something new

Deploy applications, APIs, and platforms on Cloudflare from the ground up.

Build, deploy and secure full-stack applications globally with serverless compute and storage.

Build and deploy AI-powered applications with inference, vector databases, and model gateways.

Build multi-tenant platforms with custom domains, isolated compute, and per-customer configuration.

Build, secure, and manage APIs with rate limiting, authentication, and observability.

Secure and accelerate your applications

Add Cloudflare to an existing application or infrastructure.

Block attacks with application security, DDoS protection, and SSL/TLS encryption.

Speed up your applications with global caching, image optimization, and smart routing.

Protect employees, devices, and data with Zero Trust access, secure web gateway, and email security.

Deliver video, images, and rich media at scale with encoding, optimization, and global distribution.

Secure and accelerate online storefronts with caching, bot protection, and global delivery.


More resources

Detailed diagrams and design patterns for enterprise deployments.

Structured, module-based guidance for specific workflows.

Step-by-step guides to help you build with Cloudflare solutions.

Build and run AI applications

To build and deploy an AI application, you need compute for application logic, a way to run inference, and a gateway to manage costs across providers. Cloudflare Workers hosts your application logic and serves your frontend. Workers AI runs inference at the edge with pay-per-use pricing. AI Gateway adds caching, rate limiting, and observability across OpenAI, Anthropic, and other providers. Durable Objects coordinate stateful workflows and multi-turn conversations.

Solutions

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Workers AI

Run inference on Cloudflare's global network via a Workers binding, with pay-per-use pricing. Learn more about Workers AI.

AI Gateway

Proxy requests to any AI provider with caching, rate limiting, and unified analytics. Learn more about AI Gateway.

Durable Objects

Stateful objects with strongly consistent storage and coordination. Learn more about Durable Objects.

Get started

  1. Workers AI get started
  2. AI Gateway get started
  3. Durable Objects get started

Control costs and improve quality

AI inference costs can grow unpredictably as your application scales, especially when using multiple providers. Cloudflare AI Gateway caches identical queries to avoid redundant inference calls, applies rate limits per user or API key, and provides unified analytics across all providers.

Solutions

AI Gateway

Cache responses, rate limit requests, and monitor usage across providers. Learn more about AI Gateway.

Workers Analytics Engine

Store and query time-series analytics data from Workers. Learn more about Workers Analytics Engine.

Get started

  1. AI Gateway get started
  2. Configure caching
  3. Workers Analytics Engine get started

AI applications

import { CardGrid, DirectoryListing, LinkTitleCard, YouTube, } from "~/components";

Build and deploy AI applications on Cloudflare's global network with inference at the edge, vector databases, and model gateways. Workers AI runs Large Language Models (LLMs), text embeddings, image generation, and other models with pay-per-use pricing. AI Gateway proxies requests to OpenAI, Anthropic, and other providers with caching and unified analytics. Vectorize stores embeddings for Retrieval Augmented Generation (RAG) workflows.

AI applications can present unique infrastructure challenges, such as unpredictable inference costs, latency-sensitive user experiences, and the need to work with multiple model providers. Cloudflare provides a complete platform for building AI applications that are fast, cost-effective, and globally distributed.

Architecture patterns

Retrieval Augmented Generation (RAG)

Combine vector search with Large Language Model (LLM) inference to ground responses in your own data:

Multi-provider AI gateway

Use AI Gateway to route requests across providers while maintaining a single interface:

Real-time AI features

Deploy low-latency AI features directly at the edge:


Prerequisites

Create a new application

Use an existing application


Browse available models for text generation, embeddings, image generation, and more.

Connect to OpenAI, Anthropic, Google AI, and other providers through AI Gateway.

Store and retrieve context

AI applications need specialized storage for vector embeddings, conversation history, training data, and cached responses. Cloudflare Vectorize stores and queries embeddings for Retrieval Augmented Generation (RAG), D1 provides SQL storage for structured data, R2 stores documents and assets, and KV caches frequent responses at the edge.

Solutions

Vectorize

Vector database for storing and querying embeddings. Learn more about Vectorize.

D1

Serverless SQL database built on SQLite, with global read replication. Learn more about D1.

R2

S3-compatible object storage with zero egress fees. Learn more about R2.

KV

Globally distributed key-value storage for low-latency reads. Learn more about KV.

Get started

  1. Vectorize get started
  2. D1 get started
  3. R2 get started

Deploy APIs at the edge

Deploying APIs on traditional infrastructure means managing servers, configuring regions, and provisioning for traffic spikes. Cloudflare Workers runs your API handlers in 300+ locations worldwide with automatic scaling and fast startup times.

Solutions

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Queues

Reliable message queuing and background processing for Workers. Learn more about Queues.

D1 and Durable Objects

Serverless SQL database built on SQLite, with global read replication (learn more about D1). Stateful objects with strongly consistent storage and coordination (learn more about Durable Objects).

Get started

  1. Workers get started
  2. D1 get started
  3. Queues get started

APIs and microservices

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

Build, secure, and manage Application Programming Interfaces (APIs) with rate limiting, authentication, and observability. Cloudflare Workers deploys API handlers globally with automatic scaling. API Shield validates requests against your OpenAPI specification. Rate Limiting prevents abuse. mTLS authenticates machine-to-machine communication. Cloudflare Tunnel and Access secure internal microservices. Logpush and Workers Analytics Engine provide monitoring.

Architecture patterns

Secure API gateway

Protect your APIs with defense in depth:

Edge-native APIs

Build APIs that run entirely on Cloudflare:

Microservices mesh

Connect and secure internal services:


Prerequisites

Create a new application

Use an existing application


Complete documentation for API discovery, schema validation, and security.

Code examples for building APIs with Workers.

Connect your internal network services

Internal services and microservices often need to communicate without exposing endpoints to the public Internet. Cloudflare Tunnel creates outbound-only connections with no inbound firewall rules, while Access enforces Zero Trust policies for every request between services.

Solutions

Cloudflare Tunnel

Connect infrastructure to Cloudflare without opening inbound firewall ports. Learn more about Cloudflare Tunnel.

Access

Zero Trust access control for applications and infrastructure. Learn more about Access.

Service Tokens

Non-interactive credentials for machine-to-machine authentication. Learn more about Service Tokens.

Get started

  1. Create a Cloudflare Tunnel
  2. Cloudflare Access get started
  3. Create service tokens

Monitor your APIs

Understanding how your APIs are used — request volume, latency, error rates, and undocumented endpoints — is essential for reliability and security. Cloudflare API Shield Analytics discovers endpoints from observed traffic, Logpush streams logs to your analytics platform, and Workers Analytics Engine tracks custom business metrics.

Solutions

API Shield Analytics

Discover endpoints and monitor API traffic patterns. Learn more about API Shield Analytics.

Logpush

Stream logs from Cloudflare products to external destinations. Learn more about Logpush.

Workers Analytics Engine

Store and query time-series analytics data from Workers. Learn more about Workers Analytics Engine.

Get started

  1. API Shield get started
  2. Configure Logpush
  3. Workers Analytics Engine get started

Protect your APIs

APIs are exposed to abuse, injection attacks, and unauthorized access. Cloudflare provides defense in depth with API Shield schema validation, per-endpoint rate limiting, mutual TLS (mTLS) client authentication, and security rules.

Solutions

API Shield

Discover, secure, and monitor your APIs. Learn more about API Shield.

Rate Limiting

Limit request rates based on flexible matching criteria. Learn more about Rate Limiting.

mTLS

Mutual TLS client certificate authentication. Learn more about mTLS.

Application Security

Get automatic protection from vulnerabilities and create your own custom rules. Learn more about Application Security.

Access

Zero Trust access control for applications and infrastructure. Learn more about Access.

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Get started

  1. API Shield get started
  2. Configure rate limiting rules
  3. Set up mTLS authentication
  4. Configure applications with Cloudflare Access
  5. Service tokens
  6. Workers get started

Secure API endpoints

API endpoints are vulnerable to schema violations, abuse, and unauthorized access. Cloudflare API Shield validates requests against your OpenAPI specification, and mutual TLS (mTLS) authenticates known clients with certificates.

Solutions

API Shield

Discover, secure, and monitor your APIs. Learn more about API Shield.

mTLS

Mutual TLS client certificate authentication. Learn more about mTLS.

Get started

  1. API Shield get started
  2. Set up mTLS

Block application attacks

Web applications face constant threats from SQL injection, Cross-Site Scripting (XSS), and other Open Web Application Security Project (OWASP) Top 10 vulnerabilities. Cloudflare WAF managed rulesets block these attacks automatically, and rate limiting prevents brute force abuse.

Solutions

Application security (WAF)

Get automatic protection from vulnerabilities and create your own custom rules. Learn more about WAF.

Rate limiting

Limit request rates based on flexible matching criteria. Learn more about rate limiting.

Get started

  1. Deploy WAF managed rulesets
  2. Create custom rules
  3. Configure rate limiting rules

For custom rules and rate limiting patterns specific to bot traffic, refer to Stop malicious bots while allowing legitimate traffic (Free, Pro, and Business).

Stop malicious bots

Malicious bots perform credential stuffing, content scraping, and inventory hoarding. Cloudflare provides multiple tools to detect and block automated threats while allowing legitimate bots like search engine crawlers.

For a step-by-step workflow that combines these tools into a layered defense, refer to Stop malicious bots while allowing legitimate traffic.

Solutions

Bot Fight Mode

Baseline bot protection available on all plans, including Free. Challenges requests that match known bot patterns. Learn more about Bot Fight Mode.

Super Bot Fight Mode

Granular bot controls for Pro plans and above. Allows verified bots, configures per-category actions, and extends protection to static resources. Learn more about Super Bot Fight Mode.

Bot Management

Machine learning-powered bot detection for Enterprise with granular signal detections. Assigns a bot score from 1 (bot) to 99 (human) to every request, along with additional signals for more precise and customizable security rules. Learn more about Bot Management.

Turnstile

Privacy-preserving challenge for forms and user interactions. Available on all plans at no cost. Learn more about Turnstile.

WAF custom rules

Targeted rules that act on traffic signals including headers, request patterns, and bot management variables. Available on all plans. Learn more about custom rules.

Get started

  1. Stop malicious bots while allowing legitimate traffic — layered defense guide covering all products above
  2. Enable Bot Fight Mode — quickest single step (Free plan)
  3. Add Turnstile to forms — protect login and signup forms

Protect against client-side threats

Third-party scripts on your site can be compromised to exfiltrate data or inject malicious code. Cloudflare's client-side security (previously known as Page Shield) monitors every JavaScript resource loading on your pages, detects suspicious behavior, and helps you manage Content Security Policies (CSPs).

Solutions

Client-side security

Monitor and control third-party scripts and outbound connections on your pages. Learn more about client-side security.

Get started

  1. Enable Client-side security
  2. Review detected scripts
  3. Configure rules

Mitigate DDoS attacks

Distributed Denial of Service (DDoS) attacks can take your application offline by flooding it with traffic. Cloudflare DDoS Protection mitigates these attacks automatically at the network edge, with no caps on attack size or duration and no manual intervention required.

Solutions

DDoS Protection

Automatic mitigation of volumetric and application-layer DDoS attacks. Learn more about DDoS Protection.

Get started

  1. DDoS protection overview
  2. Configure DDoS managed rulesets

Application security

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

Protect your website or application from attacks, bots, and abuse. Cloudflare's application security (also known as Web Application Firewall or WAF) blocks SQL injection, XSS, and OWASP Top 10 vulnerabilities. DDoS Protection mitigates volumetric and application-layer attacks automatically. Bot Security uses machine learning to score every request. API Shield validates API traffic against your OpenAPI specification. Client-side security monitors third-party scripts for malicious behavior.

Architecture patterns

Web application security

Protect a website or web application from common attacks:

API security

Secure Application Programming Interface (API) endpoints with schema enforcement and authentication:

Client-side defense

Protect visitors from threats that execute in the browser:


Prerequisites


Structured learning path for application security.

Analyze security events and fine-tune your configuration.

Explore how companies secure their applications with Cloudflare.

Prevent data loss

Sensitive data — Personally Identifiable Information (PII), payment card numbers, health records — can leave your network through employee uploads, SaaS misconfigurations, or compromised applications. Cloudflare One detects sensitive data patterns in traffic and blocks exfiltration in real time.

Solutions

Cloudflare One

Secure your organization with a cloud security platform that replaces legacy perimeters with Cloudflare's global network. Learn more about Cloudflare One.

Get started

  1. Configure DLP policies
  2. Set up CASB integrations
  3. Create Gateway HTTP policies for DLP

Ensure device endpoint security

Granting access to corporate applications without verifying device health creates risk. Cloudflare One checks OS version, disk encryption, and antivirus status before allowing a device to connect, and integrates with CrowdStrike, SentinelOne, and other Endpoint Detection and Response (EDR) tools.

Solutions

Cloudflare One

Secure your organization with a cloud security platform that replaces legacy perimeters with Cloudflare's global network. Learn more about Cloudflare One.

Cloudflare One client

Device agent that routes traffic through Cloudflare's network. Learn more about Cloudflare One client.

Get started

  1. Deploy the Cloudflare One client
  2. Configure device posture checks
  3. Add posture checks to Access policies

Stop email phishing attacks

Email is the most common vector for phishing, Business Email Compromise (BEC), and malware delivery. Cloudflare Email Security scans inbound messages to block these threats before they reach the inbox, and DMARC management prevents domain spoofing.

Solutions

Email security

Detect and block email-based threats including phishing, BEC, and malware. Learn more about Email security.

DMARC management

Prevent email spoofing and improve deliverability. Learn more about DMARC management.

Get started

  1. Deploy Email security
  2. Set up DMARC management

Access internal applications securely

Traditional VPNs grant broad network access, create bottlenecks, and are difficult to scale. Cloudflare replaces VPNs with Zero Trust access — verifying identity and device posture on every request — using Cloudflare Tunnel, Access, and the Cloudflare One client.

Solutions

Cloudflare One

Secure your organization with a cloud security platform that replaces legacy perimeters with Cloudflare's global network. Learn more about Cloudflare One.

Cloudflare Tunnel

Connect infrastructure to Cloudflare without opening inbound firewall ports. Learn more about Cloudflare Tunnel.

Cloudflare One client

Securely route traffic through Cloudflare's network. Learn more about Cloudflare One client.

Get started

Access internal applications securely

Company security

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

Protect employees, devices, and data with Zero Trust access, secure web gateway, and email security. Cloudflare Access and Tunnel replace VPNs with identity-verified, per-request access to internal applications. Gateway filters DNS and HTTP traffic to block threats. DLP prevents sensitive data from leaving your network. Email Security stops phishing, BEC, and malware. DMARC management prevents domain spoofing.

Architecture patterns

VPN replacement

Replace traditional VPNs with Zero Trust access to internal applications:

Secure web gateway

Filter and inspect Internet-bound traffic from employees:

Email threat protection

Stop phishing, malware, and spoofing before they reach the inbox:


Prerequisites


Complete documentation for Zero Trust and Secure Access Service Edge (SASE).

Complete documentation for email threat protection.

Explore how enterprises implement Zero Trust with Cloudflare.

Secure your company's Internet access

Employees browsing the Internet encounter malware, phishing, and data exfiltration risks. Cloudflare Gateway filters DNS and HTTP traffic to block threats and enforce acceptable use policies, while browser isolation executes risky content in a remote browser.

Solutions

Gateway

Secure web gateway with DNS, HTTP, and network filtering. Learn more about Gateway.

Cloudflare One

Secure your organization with a cloud security platform that replaces legacy perimeters with Cloudflare's global network. Learn more about Cloudflare One.

Get started

  1. Set up Gateway DNS filtering
  2. Configure HTTP inspection
  3. Deploy Browser Isolation

Secure your company's Internet access

Observe traffic patterns and analytics

Understanding how shoppers experience your store — page load times, security events, and traffic patterns — requires analytics that do not slow down your site. Cloudflare Web Analytics collects real user metrics without cookies, Security Analytics shows WAF and bot activity, and Logpush exports logs for compliance.

Solutions

Web analytics

Privacy-first, cookie-free analytics for websites. Learn more about Web analytics.

Security analytics

Analyze security events and fine-tune your Application Security configuration. Learn more about Security analytics.

Logpush

Stream logs from Cloudflare products to external destinations. Learn more about Logpush.

Get started

  1. Enable Web Analytics
  2. Configure Logpush
  3. Review Security Analytics

E-commerce

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

E-commerce applications require exceptional performance, security, and reliability. Cloudflare protects and accelerates online stores with application security against attacks, bot security against credential stuffing and fraud, cache and image optimization for fast global delivery of product pages, load balancing and Waiting Room for handling traffic spikes, and Zaraz for server-side analytics and marketing tags.

Architecture patterns

Self-hosted storefront

Protect and accelerate a store running on your own infrastructure:

SaaS-hosted storefront

Add Cloudflare on top of a platform like Shopify, BigCommerce, or Salesforce Commerce Cloud:

High-traffic store

Handle flash sales, seasonal peaks, and viral demand:


Prerequisites

Create a new application

Use an existing application


Explore how e-commerce companies use Cloudflare.

Detailed diagrams and design patterns for enterprise deployments.

Accelerate your store's performance

Slow page loads directly reduce e-commerce conversion rates. Cloudflare accelerates your storefront with global edge caching, on-the-fly image optimization for product images, automatic asset minification, and server-side loading of analytics and marketing tags through Zaraz.

Solutions

Cache

Cache content at Cloudflare's global network of edge locations. Learn more about Cache.

Images

Transform, optimize, and deliver images at scale. Learn more about Images.

Speed

Automatic optimizations for HTML, CSS, JavaScript, and fonts. Learn more about Speed.

Zaraz

Server-side loading of third-party tools to improve performance and privacy. Learn more about Zaraz.

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Get started

  1. Configure Cache Rules
  2. Set up Cloudflare Images
  3. Enable Speed optimizations
  4. Configure Zaraz
  5. Rewrite HTML at the edge with HTMLRewriter

Protect your store

Online stores are targets for DDoS attacks, credential stuffing, payment fraud, and supply chain script injections. Cloudflare provides layered security — from SSL/TLS encryption and application security managed rulesets to bot detection and client-side script monitoring — that protects your store without adding friction for shoppers.

Solutions

SSL/TLS

Encrypt all traffic with free, automatic SSL certificates. Learn more about SSL/TLS.

Application security

Get automatic protection from vulnerabilities and create your own custom rules. Learn more about application security.

DDoS protection

Automatic mitigation of volumetric and application-layer DDoS attacks. Learn more about DDoS protection.

Bot security

Machine learning powered bot detection with granular control over bot traffic. Learn more about Bot security.

Turnstile

Privacy-preserving CAPTCHA alternative for forms and user interactions. Learn more about Turnstile.

Client-side security

Monitor and control third-party scripts and outbound connections on your pages. Learn more about Client-side security.

Get started

  1. Enable SSL/TLS
  2. Configure Application Security managed rules
  3. Set up Bot security
  4. Add Turnstile to forms
  5. Enable Client-side security

Handle traffic at scale

Flash sales, seasonal peaks, and viral moments can overwhelm your origin infrastructure. Cloudflare Load Balancing distributes traffic across multiple origins with automatic failover, Waiting Room queues excess visitors to prevent overload, and Argo Smart Routing reduces latency between edge and origin.

Solutions

Load balancing

Distribute traffic across origins with health checks and automatic failover. Learn more about Load balancing.

Waiting Room

Manage visitor queuing during traffic surges. Learn more about Waiting Room.

Argo Smart Routing

Route traffic through the fastest paths across Cloudflare's network. Learn more about Argo Smart Routing.

Get started

  1. Set up Load Balancing
  2. Configure Waiting Room
  3. Create Health Checks

See also

Cloudflare Smart Shield acts as an intermediate caching layer between Cloudflare's content delivery network and your origin server, consolidating multiple requests from various locations into a single request. Learn more about Smart Shield.

Cache and accelerate media delivery

Streaming video and serving images to a global audience requires low-latency delivery from locations close to each viewer. Cloudflare Cache serves media globally, and Argo Smart Routing ensures cache misses take the fastest path back to your origin.

Solutions

Cache

Cache content at Cloudflare's global network of edge locations. Learn more about Cache.

Argo Smart Routing

Route traffic through the fastest paths across Cloudflare's network. Learn more about Argo Smart Routing.

Get started

  1. Configure Cache Rules
  2. Enable Tiered Cache
  3. Enable Argo Smart Routing

Optimize and transform images for the web

Serving images at multiple sizes and formats traditionally requires pre-generating variants for every resolution and device. Cloudflare Images transforms images on-the-fly via URL parameters — resizing, cropping, and converting to WebP or AVIF — while Polish compresses originals without visible quality loss.

Solutions

Images

Transform, optimize, and deliver images at scale. Learn more about Images.

Polish

Automatic image compression without quality loss. Learn more about Polish.

Get started

  1. Images get started
  2. Enable Polish
  3. Transform images via URL

Media and streaming

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

Deliver video, images, and rich media at scale with encoding, optimization, and global distribution. Cloudflare Stream handles video upload, encoding, and adaptive bitrate delivery. Images transforms and optimizes images on-the-fly. R2 stores media files with zero egress fees. Cache serves content from 300+ edge locations. Hotlink Protection and signed URLs secure media from unauthorized access.

Architecture patterns

Video platform

Build a complete video hosting and delivery solution:

Image optimization pipeline

Serve optimized images without pre-generating variants:

  1. R2 stores original high-resolution images
  2. Images transforms images on-the-fly based on URL parameters
  3. Workers applies custom logic for format selection and caching

User-generated content

Handle media uploads from users at scale:

  1. R2 receives uploads directly via presigned URLs
  2. Workers validates and processes uploaded content
  3. Stream or Images optimizes media for delivery

Prerequisites

Create a new application

Use an existing application


Complete documentation for video upload, encoding, and delivery.

Complete documentation for image optimization and transformation.

Explore how media companies use Cloudflare.

Secure your content

Media assets are vulnerable to hotlinking, unauthorized downloads, and piracy. Cloudflare Hotlink Protection blocks other sites from embedding your media, Stream signed URLs provide time-limited access tokens, and Access gates premium content behind identity policies.

Solutions

Block unauthorized embedding of resources from external sites. Learn more about Hotlink Protection.

Stream

Live streaming with automatic recording and instant playback. Learn more about Stream Live.

Access

Zero Trust access control for applications and infrastructure. Learn more about Access.

Get started

Store media at scale

Media files are large, and egress fees from traditional cloud storage can be significant at scale. Cloudflare R2 provides S3-compatible object storage with zero egress fees, and Workers lets you build custom processing pipelines for validation, transformation, and routing.

Solutions

R2

S3-compatible object storage with zero egress fees. Learn more about R2.

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Get started

  1. R2 get started
  2. Generate presigned URLs
  3. Workers get started

Upload, encode, and deliver videos

Building a video platform requires upload handling, encoding to multiple resolutions, adaptive bitrate delivery, and global distribution. Cloudflare Stream handles all of this — upload, transcode, store, and deliver — with no video infrastructure to manage.

Solutions

Stream

Upload, encode, store, and deliver video with adaptive bitrate streaming. Learn more about Stream.

Stream Live

Live streaming with automatic recording and instant playback. Learn more about Stream Live.

RealtimeKit

Add customizable live video and voice to web or mobile applications. Learn more about RealtimeKit.

Get started

  1. Stream get started
  2. Set up Stream Live
  3. Secure videos with signed URLs

Cache content globally

Every request that reaches your origin server adds latency and costs. Cloudflare Cache serves static and dynamic content globally, reducing round-trip times for visitors and offloading traffic from your origin.

Solutions

Cache

Cache content at Cloudflare's global network of edge locations. Learn more about Cache.

Get started

  1. Configure Cache Rules
  2. Enable Tiered Cache
  3. Set up Cache Reserve

Accelerate connections

Network congestion and suboptimal routing between your origin and visitors add latency. Cloudflare Argo Smart Routing uses real-time network telemetry to route requests through the fastest paths, while Early Hints preloads assets before the full HTML response arrives.

Solutions

Argo Smart Routing

Route traffic through the fastest paths across Cloudflare's network. Learn more about Argo Smart Routing.

Speed

Improve the performance of your website or web application. Learn more about Speed.

Early Hints

Preload assets before the HTML response arrives. Learn more about Early Hints.

Get started

  1. Enable Argo Smart Routing
  2. Enable HTTP/3
  3. Enable Early Hints

Optimize images

Images are often the largest assets on a page and the biggest contributor to slow load times. Cloudflare Images resizes and converts images on-the-fly to modern formats like WebP and AVIF, while Polish compresses existing images without visible quality loss.

Solutions

Images

Transform, optimize, and deliver images at scale. Learn more about Images.

Polish

Automatic image compression without quality loss. Learn more about Polish.

Speed

Improve page load performance with built-in optimizations. Learn more about Speed.

Get started

  1. Images get started
  2. Enable Polish

Performance

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

Accelerate websites and applications with Cloudflare CDN (Content Delivery Network) caching, image optimization, smart routing, load balancing, and web analytics.

Prerequisites


Structured learning path for site optimization.

Analyze cache hit rates and optimize caching.

Explore how companies accelerate their applications with Cloudflare.

Balance traffic across origins

If a single origin server handles all your traffic, any failure or overload takes your application offline. Cloudflare's load balancing distributes traffic across multiple origins with health checks and automatic failover.

Solutions

Load balancing

Distribute traffic across origins with health checks and failover. Learn more about load balancing.

Health checks

Monitor origin server health and availability. Learn more about health checks.

Get started

  1. Create a load balancer
  2. Configure health checks
  3. Set up steering policies

Monitor performance

Understanding how real visitors experience your site requires metrics from actual sessions, not synthetic tests. Cloudflare Web Analytics collects Core Web Vitals and performance data from 100% of page views without cookies or sampling.

Solutions

Web Analytics

Privacy-first, cookie-free analytics for websites. Learn more about Web Analytics.

Observatory

Run performance tests and get optimization recommendations. Learn more about Observatory.

Get started

  1. Enable Web Analytics
  2. Run a speed test

Optimize web assets

Unoptimized HTML, CSS, and JavaScript increase page weight and slow down rendering. Cloudflare Speed automatically minifies and compresses these assets, while Zaraz loads third-party analytics and marketing tags server-side to avoid blocking page rendering.

Solutions

Speed

Improve the performance of your website or web application. Learn more about Speed.

Zaraz

Server-side loading of third-party tools to improve performance and privacy. Learn more about Zaraz.

Get started

  1. Enable Speed optimizations
  2. Zaraz get started

Enable customer code deployment

SaaS platforms often need to let customers run their own code — custom logic, integrations, webhooks — without compromising tenant isolation or platform stability. Cloudflare Workers for Platforms runs each customer's code in a separate V8 isolate with dispatch routing based on hostname, path, or header.

Solutions

Workers for Platforms

Deploy isolated Workers execution environments for your customers. Learn more about Workers for Platforms.

Get started

  1. Workers for Platforms get started
  2. Configure Dispatch Namespaces

Customer domains with SSL for SaaS

SaaS customers expect to use their own domains (for example, app.theirdomain.com) instead of a subdomain on your platform. Cloudflare SSL for SaaS provisions and renews SSL certificates automatically for every custom hostname, with no manual steps or customer action required.

Solutions

Cloudflare for Platforms

Extend Cloudflare's network and services to your customers. Learn more about Cloudflare for Platforms.

SSL for SaaS

Provision and manage SSL certificates for custom customer domains. Learn more about SSL for SaaS.

Get started

  1. SSL for SaaS get started
  2. Create custom hostnames
  3. Validate certificates

Store and isolate customer data

Multi-tenant platforms need to store customer data with appropriate isolation — per-tenant databases, separate object storage, or row-level separation. Cloudflare provides serverless storage options that support tenant isolation at the database, bucket, or key-prefix level.

Solutions

D1

Serverless SQL database built on SQLite, with global read replication. Learn more about D1.

R2

S3-compatible object storage with zero egress fees. Learn more about R2.

Durable Objects

Stateful objects with strongly consistent storage and coordination. Learn more about Durable Objects.

KV

Globally distributed key-value storage for low-latency reads. Learn more about KV.

Get started

  1. D1 get started
  2. R2 get started
  3. Durable Objects get started

SaaS platforms

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

Build multi-tenant platforms with custom domains, isolated compute, and per-customer configuration. Cloudflare SSL for SaaS provisions and renews SSL certificates for every customer hostname. Workers for Platforms runs customer code in isolated V8 environments. D1, KV, and R2 provide per-tenant data storage. Workers Analytics Engine and Logpush track usage for billing and compliance.

Architecture patterns

Custom domains with SSL

Allow customers to use their own domains with automatic certificate management:

Multi-tenant compute

Let customers deploy their own code on your platform:

Full multi-tenant platform

Combine custom domains, tenant compute, and isolated storage:


Prerequisites

Create a new application

Use an existing application


Complete documentation for managing custom hostnames and certificates.

Let customers deploy their own code on your platform.

Explore how SaaS companies build on Cloudflare.

Protect your platform

SaaS platforms are high-value targets because a single breach can expose data across all tenants. Cloudflare's managed rulesets protect your platform and customer endpoints, rate limiting prevents any single tenant from degrading service for others, and Cloudflare One gates admin tools behind Zero Trust policies.

Solutions

Application security

Get automatic protection from vulnerabilities and create your own custom rules. Learn more about Application security.

Rate limiting

Limit request rates based on flexible matching criteria. Learn more about Rate limiting.

Cloudflare One

Secure your organization with a cloud security platform that replaces legacy perimeters with Cloudflare's global network. Learn more about Cloudflare One.

Get started

  1. Deploy application security managed rulesets
  2. Configure rate limiting rules
  3. Cloudflare Access get started

Observe customer usage and billing

Usage-based billing and per-tenant performance monitoring require detailed analytics broken down by customer. Cloudflare Workers Analytics Engine tracks request counts, latency, and bytes per tenant ID, while Logpush exports detailed logs for compliance and audit trails.

Solutions

Workers Analytics Engine

Store and query time-series analytics data from Workers. Learn more about Workers Analytics Engine.

Logpush

Stream logs from Cloudflare products to external destinations. Learn more about Logpush.

Get started

  1. Workers Analytics Engine get started
  2. Configure Logpush

Discover and secure your API endpoints (Free, Pro, and Business)

import { Render, Steps, DashButton } from "~/components";

Once your API is in production and receiving traffic, you need to decide which endpoints to protect first, what restrictions to apply, and how to monitor for abuse without blocking legitimate clients. This guide walks through that process in five stages: inventory your endpoints, enforce encrypted connections, restrict access to expected traffic patterns, block automated abuse, and monitor the results.

The core workflow uses Cloudflare Application Security (also known as Web Application Firewall or WAF) features, SSL/TLS settings, and bot detection, all available on Free, Pro, and Business plans. Enterprise callouts cover API Shield capabilities for teams that need schema validation, JSON Web Token (JWT) validation, and sequence analysis.

Know what you are exposing

Before configuring any security rules, build an inventory of your API endpoints. Without a complete list, you cannot target protections at the right paths or detect when an unknown endpoint starts receiving traffic.

Audit your API surface manually

  1. Review your application's routing configuration and list every endpoint with its HTTP method and expected parameters.

    :::tip[AI-assisted endpoint discovery] Consider using an AI agent to analyze the API routes exposed in your codebase and then generate an OpenAPI schema from the findings. :::

  2. Categorize each endpoint by access level (public, authenticated, internal). Prioritize endpoints that accept file uploads, process payments, or return sensitive data.

    Access level Description Example endpoints
    Public No authentication required /api/status, /api/products
    Authenticated Require a token or session /api/account, /api/orders
    Internal Should not be publicly accessible /api/admin, /api/debug
  3. Record the inventory in a spreadsheet or OpenAPI schema file for reference when writing rule expressions in later sections. If you already have an OpenAPI specification, you can use it directly with API Shield's schema validation (covered in the Enterprise callout below).

:::tip[API Shield Endpoint Discovery (Enterprise)] API Shield can automatically discover API endpoints by analyzing your traffic patterns, surfacing endpoints you may not know are being called. This includes abandoned or undocumented endpoints (also known as shadow APIs) that may be unpatched and unmonitored. For more information, refer to API Discovery. :::

Enforce HTTPS for all API traffic

API requests carry credentials, tokens, and response data that attackers can intercept over unencrypted connections. Some API clients silently downgrade to HTTP if the server accepts it, sending sensitive data in plaintext. Enforcing HTTPS at the edge prevents this.

Set your SSL/TLS encryption mode

Set your encryption mode to Full (Strict) to encrypt traffic between visitors and Cloudflare and between Cloudflare and your origin server. This mode requires a valid certificate on your origin.

  1. In the Cloudflare dashboard, go to the SSL/TLS Overview page.

  2. For SSL/TLS encryption, select Full (Strict).

For more information on encryption modes and their requirements, refer to SSL/TLS encryption modes.

Turn on Always Use HTTPS

Always Use HTTPS redirects all HTTP requests to HTTPS for every subdomain and host in your application. This prevents clients from accidentally sending API requests over unencrypted connections.

:::note If only some parts of your application support HTTPS, do not turn on Always Use HTTPS. Use a single redirect to redirect specific API paths instead. Refer to Redirect admin area requests to HTTPS for an example. :::

  1. In the Cloudflare dashboard, go to the SSL/TLS Overview page.

  2. Verify that your SSL/TLS encryption mode is not set to Off. The Always Use HTTPS option is not visible when encryption is off.

  3. Go to the Edge Certificates page.

  4. Turn on Always Use HTTPS.

Set minimum TLS version to 1.2

Since APIs can carry sensitive information, like credentials and tokens, you want to select an appropriate minimum TLS version with this in mind.

TLS 1.0 and 1.1 have known vulnerabilities. Setting the minimum to TLS 1.2 rejects connections from clients using older protocols.

  1. In the Cloudflare dashboard, go to the Edge Certificates page.

  2. For Minimum TLS Version, select TLS 1.2.

For more information, refer to Minimum TLS Version.

Disable Automatic HTTPS Rewrites for API-only domains

Automatic HTTPS Rewrites changes HTTP links to HTTPS within HTML responses. For API endpoints that return JSON or other non-HTML content, this rewriting is unnecessary and can cause unexpected behavior if API clients follow rewritten URLs. If your domain serves only API traffic, turn off this setting.

  1. In the Cloudflare dashboard, go to the Edge Certificates page.

  2. Turn off Automatic HTTPS Rewrites.

:::note If your domain serves both a website and an API, keep Automatic HTTPS Rewrites on for the website. The rewriting only applies to HTML responses, so JSON API responses are not affected. :::

Restrict access to your API endpoints

Legitimate API clients send predictable request patterns: specific HTTP methods, expected headers like Content-Type: application/json, and requests to documented paths. Application Security custom rules let you block traffic that deviates from these patterns. Rate limiting rules cap request volume per client to prevent abuse.

Block requests missing expected headers

API clients typically include a Content-Type header and may include an Authorization header or a custom API key header. Requests to your API paths that lack these headers are not from your expected clients.

The following custom security rule blocks requests to /api/ paths that are missing a Content-Type header. Adjust the path and header checks to match your API.

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Custom rules.

  3. Define the rule name. For example, Block API requests missing Content-Type.

  4. In the expression editor, enter:

    (starts_with(http.request.uri.path, "/api/") and not len(http.request.headers["content-type"][0]) > 0)
    
  5. For Choose action, select Block.

  6. Select Deploy.

Restrict HTTP methods per endpoint

If your /api/users endpoint only accepts GET and POST requests, block all other HTTP methods on that path. This prevents attackers from probing with PUT, DELETE, or PATCH requests against endpoints that do not support them.

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Custom rules.

  3. Define the rule name. For example, Block unexpected methods on /api/users.

  4. In the expression editor, enter:

    (http.request.uri.path eq "/api/users" and http.request.method ne "GET" and http.request.method ne "POST")
    

    Adjust the path and allowed methods to match your endpoint.

  5. For Choose action, select Block.

  6. Select Deploy.

Repeat this pattern for each endpoint with restricted methods. You can combine multiple paths into a single rule using or operators if they share the same allowed methods.

:::tip

Instead of manually creating rules for each endpoint, consider creating a single fallthrough custom rule. You need to:

  1. Add your API endpoints to Endpoint Management from a schema or manually.
  2. Create a fallthrough rule that blocks requests that do not match a saved endpoint in Endpoint Management.

:::

Rate limit API endpoints

API endpoints receive more targeted abuse than web pages because attackers can call them at machine speed without rendering a browser. Rate limiting caps the number of requests a single client can send within a time window.

Create separate rate limiting rules for authenticated and unauthenticated endpoints. Unauthenticated endpoints (login, registration, password reset) need tighter limits because they are primary targets for credential stuffing and brute force attacks.

The following example limits requests to /api/auth/login to 10 per minute per IP address. Adjust the path, request threshold, and period for your endpoints.

  1. In the Cloudflare dashboard, go to the Security rules page.

  2. Select Create rule > Rate limiting rules.

  3. Enter a descriptive name. For example, Rate limit login endpoint.

  4. In the Field drop-down, select URI Path. Set Operator to equals and Value to /api/auth/login.

  5. Under With the same characteristics, add IP.

  6. Under When rate exceeds, set Requests to 10 and Period to 1 minute.

  7. Under Then take action, select Block.

  8. Set the Duration (mitigation timeout) to 1 minute.

  9. Select Deploy.

For more information on rate limiting parameters and counting characteristics, refer to Rate limiting parameters.

:::note Rate limiting rules may allow a small number of excess requests before enforcement starts, due to counter propagation delays across data centers. For more information, refer to Request rate calculation. :::

For an API-specific example using an API key as a counting characteristic, refer to Rate limiting rule examples.

:::tip[Schema Validation and JWT Validation (Enterprise)]

API Shield can validate incoming requests against your OpenAPI schema, blocking requests with unexpected parameters, methods, or content types before they reach your origin. Upload your schema or let Cloudflare learn it from your traffic. For more information, refer to Schema validation.

API Shield can also validate JSON Web Tokens (JWTs) at the edge, rejecting expired, tampered, or invalid tokens before requests reach your origin. This requires adding your JWT issuer's public keys and creating a validation rule. For more information, refer to JSON Web Tokens validation.

:::

Protect against automated API abuse

Bots call API endpoints at machine speed without browser overhead. Common automated attacks against APIs include credential stuffing against authentication endpoints, data scraping through listing endpoints, and inventory manipulation through cart or checkout endpoints.

Turn on Bot Fight Mode (Free)

:::note If you are on a Cloudflare Pro or Business plan, go to the next section. You will configure Super Bot Fight Mode later. :::

Bot Fight Mode challenges requests that match known bot patterns. It applies to your entire domain and is available on all plans at no additional cost.

Bot Fight Mode may interfere with legitimate automated traffic to your API, such as monitoring tools, CI/CD pipelines, or partner integrations. If you have legitimate bot clients, create an exception rule before turning on Bot Fight Mode (see the next section).

For more information on Bot Fight Mode behavior and limitations, refer to Bot Fight Mode.

Create exception rules for legitimate bot clients (Pro, Business)

If your API receives traffic from known automated clients (monitoring services, partner APIs, CI/CD systems), create a custom security rule with the Skip action to exclude them from bot protections. Create the exception rule before turning on Super Bot Fight Mode in the next section.

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Custom rules.

  3. Define the rule name. For example, Skip bot protections for monitoring service.

  4. Build an expression that matches your known bot traffic. For example, to skip protections for requests from a specific IP range with a known User-Agent:

    (ip.src in {203.0.113.0/24} and http.user_agent contains "MonitoringBot")
    

    Replace the IP range and User-Agent with values that match your legitimate bot clients.

  5. For Choose action, select Skip and then select All Super Bot Fight Mode rules.

  6. Select Deploy.

:::note Place exception rules above (before) enforcement rules in your rule list. Cloudflare evaluates custom rules in order, and the first matching rule with a terminating action stops evaluation. For more information, refer to Rule execution order. :::

Configure Super Bot Fight Mode (Pro, Business)

Super Bot Fight Mode provides granular controls that apply across your domain, allowing you to apply different actions to different bot types.

To configure Super Bot Fight Mode:

With Super Bot Fight Mode, you can configure different actions for different bot types:

Super Bot Fight Mode applies domain-wide and does not support path-specific rules. If you need to apply different bot thresholds to different API paths, you need a Bot Management subscription (Enterprise).

:::tip[Bot score in custom rules (Enterprise)] With a Bot Management subscription, you can write custom rules using cf.bot_management.score to set path-specific thresholds. For example, block requests with a bot score below 30 on /api/auth paths while allowing all scores on other API paths. For more information, refer to Bot Management. :::

Detect leaked credentials on login endpoints

Application Security leaked credentials detection checks incoming requests for username and password combinations that appeared in known data breaches. Use this detection to rate limit or challenge requests containing compromised credentials on your authentication endpoints.

:::note Access to the cf.waf.credential_check.username_and_password_leaked field (User and Password Leaked) requires a Pro plan or above. If you are on a Free plan, use the cf.waf.credential_check.password_leaked field (Password Leaked) instead, which indicates whether the password detected in the request was previously leaked. :::

The following rate limiting rule limits requests that contain a previously leaked username and password combination to 5 per minute per IP:

Setting Value
Expression cf.waf.credential_check.username_and_password_leaked
Counting characteristics IP
Requests per period 5 requests / 1 minute
Action Block

For the full expression including account takeover (ATO) detection IDs, refer to Example mitigation rules.

:::tip[Sequence Analytics and sequence mitigation custom rules (Enterprise)]

API Shield tracks the order of API endpoint requests over time, grouping important user journeys (sequences) across your API. Sequences with high precedence scores indicate requests that are likely to occur together in order. Anomalous sequences may indicate automated abuse, such as a bot that calls /auth, then /account, then /transfer in rapid succession. For more information, refer to Sequence Analytics.

Enterprise users with a Fraud Detection subscription can also create sequence mitigation custom rules to mitigate invalid sequences of API calls.

:::

Monitor your API traffic

After deploying your security rules, review the results to identify false positives and tune your thresholds. False positives (legitimate clients being blocked) and false negatives (abuse getting through) both require adjustments.

Review Security Events for API paths

Security Events shows every request that your rules matched, including the action taken and the rule that triggered it. Filter by your API path prefix to see what Cloudflare is blocking and why.

  1. In the Cloudflare dashboard, go to the Analytics page.

  2. Select the Events tab.

  3. Add a filter for URI Path starts with /api/.

  4. Review the events. Look for legitimate clients that are being blocked (false positives). Common indicators of false positives:

    • Requests from known partner IP addresses
    • Requests with valid API keys or authorization headers
    • Requests from monitoring services with known User-Agent strings

If you find false positives, update your custom rules to exclude the affected traffic. Refer to the exception rule procedure in an earlier section.

Tune rate limiting thresholds

Rate limiting thresholds that are too tight block legitimate clients. Thresholds that are too loose allow abuse. Review rate limiting events in Security Events to find the right balance.

  1. In the Cloudflare dashboard, go to the Analytics page.

  2. Select the Events tab.

  3. Filter by Action equals Block and Service equals Rate limiting.

  4. Check whether blocked requests come from legitimate clients or abusive traffic.

  5. If legitimate clients are being rate limited, edit the relevant rate limiting rule to increase the request threshold or widen the time period for the affected rule.

  6. If abusive traffic is getting through, lower the rule threshold or narrow the time period.

:::tip[Security Analytics rate analysis requires an Enterprise plan] Enterprise customers can use the Request rate analysis tab in Security Analytics to visualize request rate distributions and the Log action to observe rule matches without taking action. On other plans, estimate thresholds based on your expected traffic patterns. Refer to Find an appropriate rate limit for the full methodology. :::

Set up notifications for security event spikes

Cloudflare Notifications can alert you when security event volume exceeds a threshold, indicating a potential attack or a misconfigured rule.

  1. In the Cloudflare dashboard, go to the Notifications page.

  2. Select Add.

  3. Filter by WAF and select Security Events Alert.

  4. Define a name for the notification and the delivery method (email, webhook, or PagerDuty).

  5. Next, configure the domains for which you want to receive notifications. You can also filter events by a targeted action (for example, Block or Skip).

  6. Select Create.

For the full list of available notification types, refer to Available notifications.

:::tip[Advanced security events notifications (Enterprise)] Enterprise customers have access to the Advanced Security Events Alert notification type, which includes an additional filter for the app security services the alert should monitor. :::

Application Security

Bots

SSL/TLS

API Shield (Enterprise)

Enforce HTTPS and encrypt all traffic (Free, Pro, and Business)

import { DashButton, Render, Steps, TabItem, Tabs } from "~/components";

HTTPS on Cloudflare involves two separate connections: visitor to Cloudflare, and Cloudflare to your origin server. Both must be encrypted for end-to-end security. This guide walks through five stages:

  1. Configure your SSL/TLS encryption mode.
  2. Redirect all HTTP requests to HTTPS.
  3. Harden your HTTPS setup with minimum TLS versions and HSTS.
  4. Monitor third-party scripts on your pages.
  5. Verify your configuration.

The core workflow is available on Free, Pro, and Business plans.

<Render file="domain-scope-note-with-exception" product="use-cases" params={{ exception: "Client-Side Security is the exception: it is configured at the account level." }} />

Configure your SSL/TLS encryption mode

Your SSL/TLS encryption mode controls how Cloudflare connects to your origin server. For end-to-end encryption, use Full (strict) — it encrypts both connections and verifies your origin certificate. For a detailed comparison of all available modes, refer to Encryption modes.

Check your current mode

  1. In the Cloudflare dashboard, go to the SSL/TLS Overview page.

  2. Check the current encryption mode displayed on the page.

    • If the mode is already Full (strict), skip to Redirect all HTTP requests to HTTPS.
    • If the mode is not Full (strict), continue below to install an origin certificate (if needed) and change the mode.

Install a Cloudflare Origin CA certificate

If your origin server does not have a valid SSL certificate, install a free Cloudflare Origin CA certificate. Origin CA certificates are valid for up to 15 years and are trusted by Cloudflare, which means you can set your encryption mode to Full (strict) after installing one.

If your origin already has a valid certificate from a publicly trusted certificate authority, skip to Set your encryption mode to Full (strict).

1. Create an Origin CA certificate

  1. Go to the Origin Server page.

  2. On the Origin Certificates tab, select Create Certificate.

  3. Choose either:

    • Generate private key and CSR with Cloudflare: Private key type can be RSA or ECC.
    • Use my private key and CSR: Paste your Certificate Signing Request (CSR) into the text field.
  4. List the hostnames (including wildcards) the certificate should protect with SSL encryption. The zone apex and first level wildcard hostname are included by default.

  5. Choose a Certificate Validity period.

  6. Select Create.

  7. Choose the Key Format:

    • Servers using OpenSSL (such as Apache and NGINX) generally expect PEM files (Base64-encoded ASCII), but also work with binary DER files.
    • Servers using Windows and Apache Tomcat require PKCS#7 (a .p7b file).
  8. Copy the signed Origin Certificate and Private Key into separate files. For security reasons, you cannot see the Private Key after you exit this screen.

  9. Select OK.

:::note For details about working with certificates programmatically, refer to [API calls](/ssl/origin-configuration/origin-ca/#api-calls). :::

2. Install the certificate on your origin server

  1. Upload the Origin CA certificate to your origin web server.

  2. Update your web server configuration to use the certificate. For server-specific installation instructions, refer to Origin CA certificates.

  3. (Required for some servers) Upload the Cloudflare CA root certificate to your origin server.

  4. Enable SSL and port 443 at your origin web server.

:::note If you do not see your server listed, search the [DigiCert documentation](https://www.digicert.com/search-results) or contact your hosting provider. :::

Set your encryption mode to Full (strict)

After installing a valid certificate on your origin server, set the encryption mode to Full (strict) by following the steps below.

:::caution If your site shows a 526 error after changing the encryption mode, your origin certificate may not meet the requirements for Full (strict). The certificate must be unexpired, issued by a trusted CA or Cloudflare Origin CA, and contain a Common Name (CN) or Subject Alternative Name (SAN) that matches your hostname. For redirect loop issues, refer to ERR_TOO_MANY_REDIRECTS. :::

Redirect all HTTP requests to HTTPS

Even with an active edge certificate, visitors can still access resources over unsecured HTTP connections. Two settings work together to fix this:

  1. Always Use HTTPS redirects HTTP requests to HTTPS
  2. Automatic HTTPS Rewrites fixes mixed content references in your page HTML

Turn on Always Use HTTPS

Always Use HTTPS redirects all HTTP requests to HTTPS before they reach your origin.

:::note If only some parts of your application can support HTTPS traffic, do not turn on Always Use HTTPS. Use a single redirect to selectively redirect specific paths to HTTPS instead. Refer to Redirect admin area requests to HTTPS for an example. :::

  1. In the Cloudflare dashboard, go to the SSL/TLS Overview page.

  2. Make sure that your SSL/TLS encryption mode is not set to Off. When the encryption mode is Off, the Always Use HTTPS option is not visible in the dashboard.

  3. Go to the Edge Certificates page.

  4. Turn on Always Use HTTPS.

  1. Make sure that your SSL/TLS encryption mode is not set to Off.

  2. Send a PATCH request with always_use_https as the setting name in the URI path, and the value parameter set to "on".

Turn on Automatic HTTPS Rewrites

Automatic HTTPS Rewrites prevents mixed content errors by rewriting HTTP resource URLs in your page HTML to HTTPS. This is useful for sites where you do not control all asset URLs, such as CMS-hosted content or embedded third-party resources.

  1. In the Cloudflare dashboard, go to the Edge Certificates page.

  2. For Automatic HTTPS Rewrites, switch the toggle to On.

Send a PATCH request with automatic_https_rewrites as the setting name in the URI path, and the value parameter set to "on".

:::note Automatic HTTPS Rewrites does not rewrite all HTTP URLs. Some passive content (such as images) may not be rewritten, which can still cause mixed content warnings. For details on how rewrites work and troubleshooting, refer to Automatic HTTPS Rewrites and Mixed content errors. :::

Harden your HTTPS configuration

After your encryption mode is set and HTTP traffic is redirected, strengthen your configuration by setting a minimum TLS version, turning on HTTP Strict Transport Security (HSTS), and turning on TLS 1.3.

Set your minimum TLS version

TLS 1.0 and 1.1 have known vulnerabilities and are no longer considered secure. Setting the minimum TLS version to 1.2 blocks connections from clients using older protocols. For guidance on which version to choose, refer to TLS protocols.

  1. In the Cloudflare dashboard, go to the Edge Certificates page.

  2. For Minimum TLS Version, select TLS 1.2.

Send a PATCH request with min_tls_version as the setting name in the URI path, and the value parameter set to "1.2".

:::note[Per-hostname minimum TLS version requires Advanced Certificate Manager] To set minimum TLS versions for individual hostnames instead of the entire zone, refer to Per-hostname setup. This requires an Advanced Certificate Manager subscription. :::

Turn on TLS 1.3

TLS 1.3 provides faster handshakes and improved security over TLS 1.2.

  1. In the Cloudflare dashboard, go to the Edge Certificates page.

  2. For TLS 1.3, switch the toggle to On.

Send a PATCH request with tls_1_3 as the setting name in the URI path, and the value parameter set to "on". To also turn on 0-RTT (Zero Round Trip Time Resumption), set the value to "zrt".

Turn on HSTS

HTTP Strict Transport Security (HSTS) adds a response header that tells browsers to connect to your site over HTTPS only, even if a link or redirect tries to send them over HTTP. HSTS protects against protocol downgrade attacks.

:::caution Only turn on HSTS after your HTTPS configuration is fully working and tested. If you remove HTTPS before disabling HSTS or before waiting for the duration of the original Max Age Header, your website becomes inaccessible to visitors for the Max Age Header duration or until you re-enable HTTPS. Refer to HTTP Strict Transport Security (HSTS) before configuring. :::

Before turning on HSTS, confirm these prerequisites:

  1. In the Cloudflare dashboard, go to the Edge Certificates page.

  2. For HTTP Strict Transport Security (HSTS), select Enable HSTS.

  3. Read the dialog and select I understand.

  4. Select Next.

  5. Configure the HSTS settings:

    • Max Age Header: Choose a duration (start with 6 months, increase to 12 months after confirming stability).
    • Apply HSTS policy to subdomains (includeSubDomains): Turn on if all your subdomains support HTTPS. Subdomains without HTTPS become inaccessible when this is enabled.
    • Preload: Turn on only after setting Max Age Header to 12 months. Preload inclusion prevents downgrade attacks on the first visit. Submit your domain at hstspreload.org after turning on preload.
    • No-Sniff Header: Sends the X-Content-Type-Options: nosniff header. Turn on to prevent browsers from MIME-type sniffing.
  6. Select Save.

Send a PATCH request with security_header as the setting name in the URI path, and specify the value object that includes your HSTS settings.

Review your cipher suites

Cloudflare's default cipher suites provide strong encryption for most sites. You do not need to change them unless a security audit or compliance requirement specifies particular cipher configurations.

For details on the default cipher suites and how to customize them, refer to Cipher suites. For compliance-specific cipher configurations, refer to Customize cipher suites via API.

:::note[Custom cipher suites require Advanced Certificate Manager] Customizing cipher suites requires an Advanced Certificate Manager subscription. The default cipher suites are applied automatically on all plans. :::

Monitor third-party scripts with client-side security

HTTPS encrypts data in transit, but third-party scripts loaded by your pages can still exfiltrate data from the browser. Client-side security monitors these scripts and alerts you to unexpected additions.

Turn on script monitoring

  1. In the Cloudflare dashboard, go to the Security Settings page.

  2. (Optional) Filter by Client-side abuse.

  3. Turn on Continuous script monitoring.

### Review detected resources

After turning on monitoring, it may take some time for Cloudflare to generate a list of detected scripts on your domain.

  1. In the Cloudflare dashboard, go to the Web assets page.

  2. Select the Client-side resources tab.

  3. Review the list of detected scripts. Check for unknown or unexpected scripts from domains you do not recognize.

Depending on your Cloudflare plan, you may also be able to review connections made by scripts and check them for malicious activity. For setup details, refer to [Get started with client-side security](/client-side-security/get-started/).

:::note[Content security rules require Client-Side Security Advanced] To block scripts not on your approved list, you can create content security rules that define an allowlist. This requires the Client-Side Security Advanced add-on. Refer to Content security rules for setup instructions. :::

Verify your configuration

After completing the previous stages, verify that your HTTPS configuration works as expected.

Use Automatic SSL/TLS

Cloudflare's Automatic SSL/TLS analyzes your origin server and selects the most secure encryption mode your origin supports. If your zone uses Automatic SSL/TLS (the default for new zones), Cloudflare adjusts the mode automatically and will not downgrade to a less secure mode if your origin certificate expires.

To check whether your zone uses Automatic SSL/TLS:

  1. In the Cloudflare dashboard, go to the SSL/TLS Overview page.

  2. Check whether Automatic SSL/TLS or Custom SSL/TLS is selected. If Custom is selected and you want Cloudflare to manage the mode automatically, select Automatic SSL/TLS.

:::note The SSL/TLS Recommender is deprecated in favor of Automatic SSL/TLS. If you previously used the Recommender, Automatic SSL/TLS replaces it. Refer to SSL/TLS Recommender for migration details. :::

Test with external tools

Use SSL Labs Server Test to verify your HTTPS configuration from outside the Cloudflare network. Enter your domain and review the report. An A or A+ grade indicates that your TLS configuration, certificate chain, and protocol support meet current security standards.

:::note[PCI DSS compliance] For PCI DSS compliance, TLS 1.2 is the minimum required version. Refer to PCI compliance and vulnerabilities mitigation for details. :::

SSL/TLS

Client-side security

Solution guides

import { DirectoryListing } from "~/components";

Each guide starts from your goal, identifies which Cloudflare products you need, and walks through setting them up. For more information about solution guides, refer to Solution guide.

Protect your forms from spam and abuse (Free, Pro, and Business)

import { Render, Steps, DashButton } from "~/components";

Contact, registration, and checkout forms are common targets for automated abuse. This guide covers form protection: verifying that visitors are human, limiting repeated submissions, and blocking known attack patterns. The core workflow uses features available on all plans. Pro and Business plan features are included as callouts.

<Render file="domain-scope-note-with-exception" product="use-cases" params={{ exception: "Turnstile is the exception: widgets are configured at the account level." }} />

Add Turnstile to your forms

Turnstile verifies visitors are human without visible challenges. This guide uses Managed mode, which automatically chooses between a non-interactive or checkbox challenge based on visitor risk level. For other widget modes, refer to Widget types.

Adding Turnstile involves three steps: create a widget in the dashboard, add the client-side snippet to your form page, and validate the token on your server before processing the submission.

Create a Turnstile widget

Store the sitekey and secret key. You will use the sitekey in the client-side snippet and the secret key for server-side validation.

Add the client-side snippet

Add the Turnstile script and widget div element to each form you want to protect. Replace <YOUR-SITE-KEY> with the sitekey from the previous step.

<form id="contact-form" action="/submit" method="POST">
  <input type="text" name="name" placeholder="Name" required />
  <input type="email" name="email" placeholder="Email" required />
  <textarea name="message" placeholder="Message" required></textarea>
  <div class="cf-turnstile" data-sitekey="<YOUR-SITE-KEY>"></div>
  <button type="submit">Submit</button>
</form>

<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>

The widget renders in the form and generates a token when the visitor passes verification. The token is included in the form submission as the cf-turnstile-response field.

Validate the token on your server

Server-side validation is required. The client-side widget alone does not protect your forms because attackers can submit directly to your form endpoint. Tokens can only be validated once.

Call the Siteverify API before processing any form submission:

const SECRET_KEY = "<YOUR-SECRET-KEY>";

async function validateTurnstile(token, remoteip) {
  try {
    const response = await fetch(
      "https://challenges.cloudflare.com/turnstile/v0/siteverify",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          secret: SECRET_KEY,
          response: token,
          remoteip: remoteip,
        }),
      },
    );

    const result = await response.json();
    return result;
  } catch (error) {
    console.error("Turnstile validation error:", error);
    return { success: false, "error-codes": ["internal-error"] };
  }
}

Replace "<YOUR-SECRET-KEY>" with your Turnstile secret key. The endpoint returns a JSON object with a success field. Only process the form submission if success is true.

For validation examples in PHP, Python, Java, and C#, refer to Validate the token.

Rate limit form submission endpoints

Some abuse scripts skip the browser entirely and POST directly to your form endpoints. Application Security rate limiting rules catch these requests because client-side verification only runs in a browser.

Find your baseline request rate

Before creating a rate limiting rule, check the normal submission rate for your form endpoints. Your rate limit threshold should be above this baseline to avoid blocking legitimate traffic.

  1. In the Cloudflare dashboard, go to the Analytics page.

  2. In the Traffic tab, select a time period with non-peak traffic, or with the lowest visitor activity.

  3. Use the Add filter button to narrow results to your form endpoint traffic.

  4. Note the typical request rate per IP address. Your rate limit should be above this baseline.

If you do not have enough traffic data to establish a baseline, start with a conservative threshold and adjust based on Security Events after deployment.

:::note[Enterprise: Request rate analysis] The Request rate analysis tab in Security Analytics displays request rate distributions for your top unique clients. For details, refer to Find appropriate rate limit. :::

Create a rate limiting rule

Create a rule that limits how many times a single IP address can submit to your form endpoint within a given period. Adjust the path, threshold, and period for your site.

<Render file="create-rate-limiting-rule" product="waf" params={{ ruleName: "Rate limit contact form submissions", expression: '(http.request.uri.path eq "/contact" and http.request.method eq "POST")', expressionHelp: 'Replace "/contact" with your form endpoint path.', threshold: "5" }} />

:::note Rate limiting rule parameters (counting characteristics, periods, number of rules) vary by plan. For the full availability matrix, refer to Rate limiting rules. :::

Configure a custom response for blocked requests (Pro and above)

Instead of showing the default Cloudflare error page when a rate limit is reached, you can configure a custom response. For details, refer to Create a rate limiting rule in the dashboard.

Add Application Security rules for known abuse patterns

Rate limiting alone does not catch targeted attack patterns like SQL injection or cross-site scripting (XSS) in form fields. Application Security custom rules and managed rulesets let you block these specific patterns targeting your form endpoints. Custom rules run before rate limiting rules and managed rulesets in the execution order.

Challenge non-bot requests to form endpoints

Create a custom rule that challenges POST requests to your form endpoints from sources that are not verified bots.

  1. In the Cloudflare dashboard, go to the Security rules page.

  2. Select Create rule > Custom rules.

  3. Enter a name for the rule (for example, "Challenge spam form submissions").

  4. Under When incoming requests match, select Edit expression and enter:

    (http.request.uri.path eq "/contact" and http.request.method eq "POST" and not cf.client.bot)
    

    Replace /contact with your form endpoint path. The not cf.client.bot clause exempts verified bots (such as search engine crawlers) from the rule.

  5. Under Then take action, select Managed Challenge.

    Start with Managed Challenge to observe which requests are flagged before switching to Block.

  6. Select Deploy.

After deploying, review Security Events to check whether the rule is matching legitimate traffic. If legitimate users are being challenged, narrow the expression or switch to a less aggressive action.

:::note[Pro plans and above: Managed rulesets] The Cloudflare Managed Ruleset protects against common web attack patterns, including form-based injection attacks (SQL injection, XSS). Verify the ruleset is deployed on the Security rules page under Managed rules. For plan availability, refer to Managed Rules. :::

Turn on bot protection

Bot Fight Mode challenges requests that match known bot patterns across your entire domain. It is available on all plans and requires no configuration beyond turning it on.

Bot Fight Mode protects your entire domain without endpoint restrictions. You cannot create exceptions using custom rules to bypass Bot Fight Mode.

:::note[Pro, Business, and Enterprise] Super Bot Fight Mode provides more granular controls. You can configure how your domain responds to different categories of bot traffic (definitely automated, likely automated, verified bots) and create exceptions using custom rules with the Skip action. Enterprise customers with Bot Management can use cf.bot_management.score in custom rule expressions for path-specific bot protection. :::

Monitor your form endpoints

After deploying Turnstile, rate limiting rules, and Application Security rules, monitor your form endpoints to verify your rules are working and to detect new attack patterns.

Review Security Events

Security Events shows requests that Cloudflare security products acted on or flagged, including blocks, challenges, and skips. Filter by your form endpoint paths to see what is being blocked and what is getting through. A high volume of blocked or challenged requests to your form paths confirms the rules are active.

  1. In the Cloudflare dashboard, go to the Analytics page.

  2. Select the Events tab.

  3. Use the Add filter button to narrow results to your form endpoint traffic.

  4. Review the sampled logs. For each event, check:

    • Action taken: Whether the request was blocked, challenged, or allowed
    • Source: The rule or feature that triggered the action
    • IP address: Whether a single IP is generating many events
    • URI path: Whether requests target your form endpoints specifically

If legitimate users are being challenged, narrow the rule expression or switch to a less aggressive action.

Set up security event alerts

Configure a notification to receive alerts when there is an unusual spike in security events on your domain.

For alert types, trigger thresholds, and setup instructions, refer to Alerts for security events.

Turn on client-side resource monitoring

If a third-party script is injected into your form page, it can exfiltrate submitted data, including payment information. Client-Side Security monitors third-party scripts on your pages for changes and potential supply chain attacks.

To enable monitoring:

  1. In the Cloudflare dashboard, go to the Security Settings page.

  2. (Optional) Filter by Client-side abuse.

  3. Turn on Continuous script monitoring.

After enabling, review detected scripts on the Web assets page under the Client-side resources tab to identify any unexpected scripts on your form pages. For the full setup workflow, refer to Get started with client-side security.

Turnstile

Application Security

Bots

Client-Side Security

Stop account takeover attacks (Free, Pro, and Business)

import { Steps, DashButton, GlossaryTooltip, Render, } from "~/components";

When your site has login pages, you need to decide how to verify that visitors are human, how aggressively to limit failed attempts, and which request patterns to block. This guide covers five stages: enforce HTTPS, turn on bot protection, add Turnstile to your login form, create Application Security rate limiting rules and custom rules for suspicious patterns, and monitor for ongoing attacks using SSL/TLS transport security and Cloudflare bot solutions. The core workflow covers features available on Free, Pro, and Business plans. Enterprise features such as leaked credentials custom detection locations and Bot Management custom rules are included as callouts.

<Render file="domain-scope-note-with-exception" product="use-cases" params={{ exception: "Turnstile is the exception: widgets are configured at the account level." }} />

Enforce HTTPS to protect credentials in transit

Credentials sent over plain HTTP are visible to anyone on the network path between the visitor and your origin server. Cloudflare SSL/TLS provides two settings that enforce HTTPS connections: Always Use HTTPS and HTTP Strict Transport Security (HSTS). For additional control over which encryption standards your domain accepts, refer to Cipher suites.

Turn on Always Use HTTPS

Always Use HTTPS redirects all visitor requests from http to https for all subdomains and hosts.

:::note Cloudflare recommends not performing redirects at your origin web server, as this can cause redirect loop errors. :::

:::note[Optional: HTTP Strict Transport Security (HSTS)] For additional transport hardening, consider enabling HTTP Strict Transport Security (HSTS). HSTS tells browsers to only connect over HTTPS, preventing downgrade attacks on the initial request. HSTS is irreversible for the configured Max Age duration. If you later disable HTTPS, your site becomes inaccessible until the Max Age expires. Review the HSTS requirements before turning it on. :::

Turn on bot protection

Cloudflare provides bot protection on all plans, with features that vary by plan tier. Turning on bot protection before configuring login-specific rules gives you a baseline filter against automated traffic across your entire domain.

Bot Fight Mode (Free)

Bot Fight Mode challenges requests that match known bot patterns. It applies to all traffic on your domain and cannot be customized with exceptions or path-specific rules.

:::note Bot Fight Mode cannot be skipped by custom rules because it does not run inside the Ruleset Engine. If you need to exempt specific traffic (monitoring tools, partner APIs), upgrade to Super Bot Fight Mode on the Pro plan. :::

Super Bot Fight Mode (Pro, Business, and Enterprise)

Super Bot Fight Mode identifies traffic matching patterns of known bots, can challenge or block bots, and offers protection for static resources. You configure a separate action for each bot grouping: Definitely automated, Likely automated, and Verified bots. You can also configure exceptions using Application Security custom rules with the Skip action.

For login protection, the following are recommended starting values. Adjust based on your traffic patterns.

:::caution If your organization also uses Cloudflare Tunnel, keep Definitely Automated set to Allow. Otherwise, tunnels might fail with a websocket: bad handshake error. :::

Custom rules are executed before Super Bot Fight Mode. To create exceptions for specific paths or traffic, create a custom rule with the Skip action. The Skip action allows the request to bypass the Super Bot Fight Mode phase without terminating the request, enabling it to continue through the rest of the security stack.

Protect your login form with Turnstile and rate limiting

Two tools protect login endpoints from automated abuse, and they cover different attack vectors:

Both together provide the strongest coverage. Turnstile challenges automated submissions at the form level. Rate limiting catches high-volume attacks that bypass or do not encounter the form, such as direct POST requests to the endpoint.

Add Turnstile to your login form

Implementing Turnstile involves three steps: create a widget, add the client-side snippet to your login form, and validate the token on your server. Turnstile supports multiple rendering methods including explicit and implicit rendering. You can also inject Turnstile into HTML using a Cloudflare Worker if you do not control the login form source code.

1. Create a Turnstile widget

Turnstile is configured at the account level.

You need both the sitekey and secret key in the following steps.

2. Add the client-side snippet

Add the Turnstile script and widget container to your login form. Replace <YOUR-SITE-KEY> with the sitekey from the previous step.

<form id="login-form">
	<input type="text" id="username" placeholder="Username" required />
	<input type="password" id="password" placeholder="Password" autocomplete="off" required />
	<div class="cf-turnstile" data-sitekey="<YOUR-SITE-KEY>"></div>
	<button type="submit">Log in</button>
</form>

<script
	src="https://challenges.cloudflare.com/turnstile/v0/api.js"
	async
	defer
></script>

The widget renders inside the div and produces a token when the visitor passes the challenge. When the form is submitted, a cf-turnstile-response token is included in the form data.

3. Validate the token on your server

Before processing the form submission, send the token to the Turnstile siteverify endpoint to confirm the visitor passed the challenge.

const SECRET_KEY = "<YOUR-SECRET-KEY>";

async function validateTurnstile(token, remoteip) {
	try {
		const response = await fetch(
			"https://challenges.cloudflare.com/turnstile/v0/siteverify",
			{
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					secret: SECRET_KEY,
					response: token,
					remoteip: remoteip,
				}),
			},
		);

		const result = await response.json();
		return result;
	} catch (error) {
		console.error("Turnstile validation error:", error);
		return { success: false, "error-codes": ["internal-error"] };
	}
}

Replace "<YOUR-SECRET-KEY>" with your Turnstile secret key. The endpoint returns a JSON object with a success field. Only process the form submission if success is true.

For additional fraud detection, Turnstile supports Ephemeral IDs that provide a unique, temporary identifier for each visitor session without storing personal data.

For the complete response format, error codes, and examples in other languages, refer to Validate the token.

Test your implementation

Turnstile provides test site keys that return predictable results without contacting the Siteverify API.

For the full list of test keys and expected behaviors, refer to Test your Turnstile implementation.

Rate limit your login endpoint

Create a rate limiting rule for your login endpoint

The following example creates a rate limiting rule that issues a Managed Challenge after more than five POST requests to your login path from the same IP within one minute. Start with Managed Challenge rather than Block. Managed Challenge allows legitimate users who trigger the limit to pass by completing a challenge, while blocking automated traffic that cannot solve it. After monitoring Security Events to confirm the rule is not producing false positives, switch to Block. Adjust the path (/login), threshold, and period for your site.

:::caution Managed Challenge and other challenge types require an HTML response to render. They do not work for non-HTML responses such as AJAX/XHR requests, which are common on login endpoints that use single-page applications (SPAs) or API-based authentication. If your login flow uses AJAX, consider using Turnstile Pre-Clearance instead. :::

<Render file="create-rate-limiting-rule" product="waf" params={{ ruleName: "Rate limit login endpoint", expression: 'http.host eq "example.com" and http.request.uri.path eq "/login" and http.request.method eq "POST"', expressionHelp: 'Replace example.com with your domain and /login with your login endpoint path.', threshold: "5" }} />

:::note (Optional) To count only failed login attempts instead of all matching requests, Business plan and above users can add a separate counting expression under Increment counter when:

http.request.uri.path eq "/login" and http.request.method eq "POST" and http.response.code in {401 403}

This counts requests based on the response status code. Successful logins (200) do not increment the counter. :::

:::note[Advanced Rate Limiting (Enterprise)] Enterprise customers with Advanced Rate Limiting can rate limit by characteristics beyond IP address, which is useful when attackers distribute attempts across many IP addresses. For available characteristics and plan availability, refer to Rate limiting parameters. :::

Escalating rate limits for persistent attackers

For sites that experience sustained credential stuffing campaigns, consider deploying multiple rate limiting rules with increasing severity. The Rate limiting best practices page describes an escalating penalty pattern that uses three rules: a short-window rule for quick bursts, a medium-window rule for slower distributed attacks, and a long-window rule that blocks persistent attackers from the entire domain. The counting expressions use response status codes, so successful logins do not count against the limit. Refer to the best practices page for the recommended thresholds and expression syntax.

:::note These example rules require a Business plan or above because they use counting expressions that reference HTTP response codes. :::

Add Application Security rules for suspicious login patterns

Application Security custom rules and traffic detections give you additional signals beyond request rate to identify and act on suspicious login traffic. Detections populate request fields (such as leaked credential status and bot score) that your custom rules can then reference.

Turn on leaked credentials detection

Leaked credentials detection scans incoming login requests for usernames and passwords that appear in known data breach databases. Cloudflare hashes credentials before comparison and does not store plaintext passwords. When a match is found, the detection populates fields you can use in custom rules and rate limiting rules.

The cf.waf.credential_check.password_leaked field is available on all plans.

:::note The cf.waf.credential_check.username_and_password_leaked field requires a Pro plan or above. :::

After turning on the detection, your origin server can receive leaked credential status via the Exposed-Credential-Check request header. To forward this header, turn on the Add leaked credentials checks header managed transform. Your origin can then trigger a password reset for affected users.

:::note[Enterprise: Custom detection locations] If your application uses non-standard credential field names, Enterprise customers can configure custom detection locations to tell Cloudflare where to find usernames and passwords in HTTP requests. :::

Create a skip rule for legitimate automated traffic

Before deploying rules that challenge or block login traffic, create a skip rule that exempts known legitimate automated traffic. This prevents your monitoring tools, health checks, and partner integrations from being blocked by the rules that follow.

  1. In the Cloudflare dashboard, go to the Security rules page.

  2. Select Create rule and choose Custom rules.

  3. Enter a name for the rule (for example, "Skip login rules for known clients").

  4. Select Edit expression and enter an expression that matches your legitimate automated traffic. For example, to skip verified bots and a specific monitoring service IP:

    (cf.client.bot) or (ip.src eq 198.51.100.1)
    

    Replace 198.51.100.1 with the IP address of your monitoring service. Add additional conditions for other known clients.

  5. Under Then take action, select Skip. Under WAF components to skip, select the components that apply to your login protection rules (for example, All remaining custom rules and All rate limiting rules).

  6. Select Deploy.

  7. Under Place at, place the rule above your blocking and challenge rules. Custom rules execute in order, so the skip rule must come first.

For more information about the Skip action and available skip options, refer to Skip action.

Block requests with suspicious headers

Credential stuffing tools often send requests without standard browser headers or with known-bad User-Agent patterns. Create a custom rule that issues a Managed Challenge for POST requests to your login path where the User-Agent is empty. This targets direct POST requests from tools like curl, python-requests, or undici that do not set a User-Agent header.

:::note The Application Security Managed Ruleset includes rules for empty user-agents, but these are disabled by default and apply broadly. The custom rule below targets your login path specifically. :::

  1. In the Cloudflare dashboard, go to the Security rules page.

  2. Select Create rule and choose Custom rules.

  3. Enter a name for the rule (for example, "Challenge empty UA on login").

  4. Select Edit expression and enter:

    (http.request.uri.path eq "/login" and http.request.method eq "POST" and len(http.user_agent) eq 0)
    

    Replace /login with your login endpoint path.

  5. Under Then take action, select Managed Challenge.

  6. Select Deploy.

Create a rate limiting rule with leaked credentials

Combine rate limiting with leaked credentials detection to throttle login attempts that use known-compromised passwords. This rule issues a Managed Challenge when the same IP sends more than three requests with leaked passwords within one minute.

  1. On the Security rules page, select Create rule and choose Rate limiting rules.

  2. Enter a name for the rule (for example, "Rate limit leaked credentials").

  3. Under When incoming requests match, enter the following expression:

    http.request.uri.path eq "/login" and http.request.method eq "POST" and cf.waf.credential_check.password_leaked
    

    Replace /login with your login endpoint path.

  4. Under With the same characteristics, verify that IP is selected. On Free plans, this is preset to IP.

  5. Under When rate exceeds, enter 3 for Requests and select a value for Period. On Free plans, select 10 seconds.

  6. Under Then take action, select an action. On Free plans, select Block. On Pro and above, Managed Challenge is recommended.

  7. Under For duration, select a duration for the action. On Free plans, select 10 seconds.

  8. Select Deploy.

:::note[Enterprise: Bot Management] Enterprise customers with Bot Management get additional tools for login protection:

Monitor for ongoing compromise attempts

After deploying the rules and configurations from the previous sections, monitor your login endpoint to verify the rules are working and to detect new attack patterns.

Review Security Events

Security Events shows requests that Cloudflare security products acted on or flagged, including blocks, challenges, and skips.

  1. In the Cloudflare dashboard, go to the Analytics page.

  2. Select the Events tab.

Review the Sampled logs to inspect individual requests. Each log entry shows the action taken, the rule that triggered, the source IP, user agent, URI path, and country. Use the Add filter button to narrow results by action, source IP, ASN, or other fields.

Look for false positives — legitimate traffic that your rules incorrectly challenged or blocked. Common signs include:

If you see legitimate users being affected, adjust your rate limiting thresholds or add skip rules for specific IP ranges.

Set up notifications for security event spikes (Business and Enterprise)

Set up a Security Events Alert notification to receive alerts when security event volume spikes, giving you early warning of a new attack campaign. This notification is in the WAF category of the Notifications page. For setup instructions, refer to Create a notification. Enterprise customers can use Advanced Security Events Alert for more granular filtering.

Review bot traffic patterns (Pro and above)

Bot traffic analytics show bot score distribution on your login endpoint over time. A sudden spike in low-score traffic (scores 1-29) on your login path is an early signal of a credential stuffing campaign.

  1. In the Cloudflare dashboard, go to Security > Analytics > Bot analysis.

  2. Review the traffic distribution across the bot score groupings above.

If you see sustained automated traffic reaching your login endpoint despite the rules deployed in this guide, review the Security features interoperability page to verify your rules are executing in the expected order, and consider adjusting thresholds.

Application Security

Cloudflare Bots

Turnstile

SSL/TLS

Stop malicious bots while allowing legitimate traffic (Free, Pro, and Business)

import { Steps, Render, DashButton } from "~/components";

The right defense against malicious bot traffic depends on the traffic patterns on your site and your plan. This guide covers a layered approach using Cloudflare Bots, Cloudflare Application Security (also known as Web Application Firewall or WAF), and Turnstile, from baseline protection to targeted custom rules. The core workflow uses features on Free, Pro, and Business plans, with callouts for Enterprise options.

<Render file="domain-scope-note-with-exception" product="use-cases" params={{ exception: "Turnstile is the exception: widgets are configured at the account level.", }} />

Review your bot traffic

Before you change any bot settings, review your traffic data to understand what bots are doing on your site.

Find your bot analytics

Bot analytics show you how much of your traffic is automated, which pages bots target, and how Cloudflare scores each request.

:::note[Bot Analytics requires a Business plan or above] Bot score distribution data and detailed bot analytics are available on Business and Enterprise plans. Free and Pro plan users can review basic security metrics through Security Events. For full bot analytics capabilities, refer to Bot Analytics. :::

  1. In the Cloudflare dashboard, go to the Analytics page.

  2. Select the Bot analysis tab.

Review the following:

Understand bot categories

Block automated traffic with Bot Fight Mode

Bot Fight Mode identifies requests that match known bot patterns and issues a computational challenge. It reduces automated traffic across your entire site without requiring you to write any rules.

What Bot Fight Mode does

Bot Fight Mode is included with Free plans. When enabled, it:

For more details, refer to Bot Fight Mode considerations.

Turn on Bot Fight Mode (Free plan)

Enable Super Bot Fight Mode (Pro, Business, and Enterprise)

Super Bot Fight Mode adds verified bot allowlisting, per-category actions, static resource protection, and JavaScript detections.

:::note[Plan availability] Super Bot Fight Mode is available on Pro, Business, and Enterprise plans. Free plan users can use Bot Fight Mode for baseline protection. Enterprise customers who need machine learning-based bot scoring and custom allow/block rules can add Bot Management. :::

:::caution If your organization uses Cloudflare Tunnel, keep Definitely Automated set to Allow in Super Bot Fight Mode. Otherwise, tunnels might fail with a websocket: bad handshake error. :::

Protect forms from automated abuse

Turnstile and Application Security rate limiting rules protect form endpoints in different ways and work best together.

Turnstile versus rate limiting

Turnstile challenges suspected bots before they can submit a form (login, signup, contact, or checkout), without showing visitors a CAPTCHA. It can be embedded into any website without sending traffic through Cloudflare. Use Turnstile when you need to challenge automated form submissions.

Rate limiting allows you to define rate limits for requests matching an expression and the action to perform when those limits are reached. Use rate limiting to protect endpoints from abuse, such as brute-force attacks on a login page or excessive API calls from a single client.

Both together provide the strongest coverage. Turnstile challenges automated submissions at the form level. Rate limiting catches high-volume attacks that bypass or do not encounter the form, such as direct POST requests to the endpoint that skip the client-side widget.

Add Turnstile to a form

Adding Turnstile involves three steps: create a widget, add the client-side snippet, and validate the token on your server.

1. Create a Turnstile widget

Turnstile is configured at the account level.

You need both the sitekey and secret key in the following steps.

2. Add the client-side snippet

Add the Turnstile script and widget container to your form HTML:

<script
	src="https://challenges.cloudflare.com/turnstile/v0/api.js"
	async
	defer
></script>

<form action="/submit" method="POST">
	<!-- Your existing form fields -->
	<div class="cf-turnstile" data-sitekey="<YOUR_SITE_KEY>"></div>
	<button type="submit">Submit</button>
</form>

Replace <YOUR_SITE_KEY> with the sitekey from the previous step. The widget renders inside the div and produces a token when the visitor passes the challenge.

3. Validate the token on your server

Before processing the form submission, send the token to the Turnstile siteverify endpoint to confirm the visitor passed the challenge:

curl https://challenges.cloudflare.com/turnstile/v0/siteverify \
  --header "Content-Type: application/json" \
  --data '{
  "secret": "<YOUR_SECRET_KEY>",
  "response": "<TURNSTILE_RESPONSE_TOKEN>"
}'

Replace <YOUR_SECRET_KEY> with your secret key and <TURNSTILE_RESPONSE_TOKEN> with the cf-turnstile-response value from the form submission. The endpoint returns a JSON object with a success field. Only process the form submission if success is true.

For complete integration details, refer to Turnstile get started.

Limit request volume on form endpoints with rate limiting

For login endpoints, a tiered rate limiting approach works well alongside Turnstile. The following example from the Rate limiting best practices shows two rules that escalate the response based on the volume of failed attempts. Adjust the thresholds for your site's traffic patterns.

:::note[Tiered rate limiting rules require a Business plan or above] Rules that use counting expressions with response codes (such as counting only 401 and 403 responses) require a Business plan or above. On Free and Pro plans, you can create simpler rate limiting rules with IP-based counting. Refer to Rate limiting rules for plan availability details. :::

Short-window rule: Challenge an IP that sends too many failed login requests in a short window.

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Rate limiting rules.

  3. Enter a descriptive name in Rule name.

  4. Under If incoming requests match, select Edit expression and enter: http.request.uri.path eq "/login" and http.request.method eq "POST"

  5. Under With the same characteristics, select IP.

  6. Enable Use custom counting expression and enter: http.request.uri.path eq "/login" and http.request.method eq "POST" and http.response.code in {401 403}

  7. Under When rate exceeds, enter 4 requests per 1 minute.

  8. Under Then take action, select Managed Challenge.

  9. Select Deploy.

Long-window rule: Block an IP that accumulates failed login attempts over a longer period.

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Rate limiting rules.

  3. Enter a descriptive name in Rule name.

  4. Under If incoming requests match, select Edit expression and enter: http.request.uri.path eq "/login" and http.request.method eq "POST"

  5. Under With the same characteristics, select IP.

  6. Enable Use custom counting expression and enter: http.request.uri.path eq "/login" and http.request.method eq "POST" and http.response.code in {401 403}

  7. Under When rate exceeds, enter 20 requests per 1 hour.

  8. Under Then take action, select Block with a duration of 1 day.

  9. Select Deploy.

This pattern uses a counting expression that only counts POST requests returning authentication failure codes. Legitimate users who log in successfully on the first attempt never trigger the rule. Review the results in Security Events to confirm the thresholds are not catching legitimate users.

For the full tiered credential stuffing example with three rules, refer to Rate limiting best practices.

Target bot patterns with custom rules and rate limiting

Application Security custom rules and rate limiting rules let you target specific traffic patterns that built-in bot protection does not catch. Cloudflare separates detection (scoring traffic) from mitigation (acting on those scores). You write rules that reference detection signals to decide what action to take.

Block requests with missing or suspicious headers

Legitimate browsers typically send headers like User-Agent, Accept, and Accept-Language. Many bots omit these headers or send non-browser values. A custom rule targeting requests with empty or suspicious headers catches bots that evade score-based detection.

Before creating custom rules, review the built-in bot settings in Security > Settings (filter by Bot traffic). These settings handle common scenarios like blocking AI crawlers, challenging automated traffic, and allowing verified bots without requiring you to write expressions. For the full list of built-in settings, refer to Challenge bad bots.

:::note[Plan availability] Built-in bot settings are part of Super Bot Fight Mode (Pro and above). On Free plans, only the Bot Fight Mode toggle is available. Custom rules are available on all plans, with the number of rules increasing on higher plans. :::

If the built-in settings do not cover your needs, create custom rules. Start by creating an exception for verified bots so they are protected before you deploy any blocking rules.

Navigate to custom rules, then create both rules:

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Custom rules.

First, create a verified bot exception:

  1. Enter a descriptive name in Rule name.
  2. Under When incoming requests match, select Edit expression and enter: (cf.client.bot)
  3. Under Then take action, select Skip from the Choose action dropdown. Then select All remaining custom rules.
  4. Under Place at, select First from the Select order dropdown so this rule executes before any blocking rules.
  5. Select Deploy.

This ensures verified bots (search engine crawlers, monitoring services) bypass your custom rules. If you have internal APIs, partner integrations, or monitoring tools that send automated traffic, create additional Skip rules for their IP addresses or user agents before deploying blocking rules. Review your expected automated traffic in Security Events to identify what to allowlist.

Then, create a blocking rule:

  1. Select Create rule.
  2. Enter a descriptive name in Rule name.
  3. Under When incoming requests match, select Edit expression and enter: (http.request.uri.path eq "/login" and http.request.method eq "POST")
  4. Under Then take action, select Managed Challenge from the Choose action dropdown.
  5. Under Place at, leave the Select order dropdown set to Last. This places the rule after the verified bot exception.
  6. Select Deploy.
  7. Review the results in Security Events. If the rule matches only bot traffic, edit the rule and change the action from Managed Challenge to Block.

For additional custom rule options including the visual field builder, refer to Create a custom rule in the dashboard.

If your bot traffic is concentrated from countries where you have no real users, you can combine geographic filters with the rules above. Add ip.src.country to your expression to restrict the rule to specific regions. For examples, refer to Block traffic by geographical location.

Protect high-frequency paths with rate limiting

Beyond form endpoints, bots also target checkout flows, API endpoints, and other high-value paths. Rate limiting rules cap the number of requests a single client can make to these paths within a time window.

The following example creates a rate limiting rule for a checkout endpoint. Adjust the path, rate, and action for your site.

:::note[Rate limiting options vary by plan] Available periods, actions, and counting options vary by plan. The example below uses a 1-minute period with Managed Challenge. Refer to Rate limiting rules availability for your plan's options. :::

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Rate limiting rules.

  3. Enter a descriptive name in Rule name.

  4. Under If incoming requests match, select Edit expression and enter: http.request.uri.path eq "/api/checkout" and http.request.method eq "POST"

  5. Under With the same characteristics, select IP.

  6. Under When rate exceeds, enter 10 requests per 1 minute.

  7. Under Then take action, select Managed Challenge.

  8. Select Deploy.

  9. Review the results in Security Events. If the rule matches only bot traffic, edit the rule and change the action to Block if needed.

For additional patterns and thresholds, refer to Rate limiting best practices.

:::note[Security Analytics rate analysis requires an Enterprise plan] Enterprise customers can use the Request rate analysis tab in Security Analytics to visualize request rate distributions and the Log action to observe rule matches without taking action. On other plans, estimate thresholds based on your expected traffic patterns. Refer to Find an appropriate rate limit for the full methodology. :::

:::note[Enterprise Bot Management: bot score in custom rules] Enterprise customers with Bot Management can reference the cf.bot_management.score field in custom rule expressions for granular control over bot traffic. Bot Management assigns a score from 1 to 99 to each request, where lower scores indicate more automated behavior. Refer to Bot scores and Bot Management variables for details. :::

Verify and tune your rules

After you deploy bot protection rules, use Security Events to verify they are working as intended and adjust thresholds based on the results.

Check Security Events

Security Events displays requests that Cloudflare security products acted on or flagged, including blocks, challenges, and flags.

  1. In the Cloudflare dashboard, go to the Analytics page.

  2. Select the Events tab.

Review the Sampled logs to inspect individual requests. Each log entry shows the action taken, the rule that triggered, the source IP, user agent, URI path, and country. Available dashboard sections vary by plan. Refer to Security Events availability for your plan's features.

Look for false positives (legitimate traffic that your rules incorrectly challenged or blocked). Common signs include:

For rules using the Managed Challenge action, check the challenge solve rate (CSR). A low CSR likely indicates the rule is effectively filtering automated traffic rather than legitimate users.

Bot Fight Mode and Super Bot Fight Mode are aggressive by design. False positives are expected, especially in the first few days after turning them on. The key difference between the two is how you handle exceptions:

For more information on handling false positives, refer to False positives.

Adjust your rules

After reviewing Security Events, adjust your rules based on the results.

Scenario 1: Your monitoring tools or services are being blocked.

Internal monitoring tools, health check services, or partner APIs appear in blocked events. The fix depends on which feature is blocking them:

For details on Skip action configuration, refer to Configure a rule with the Skip action.

Scenario 2: Malicious traffic is still getting through.

Bot activity appears in Security Events that your current rules do not catch. Bots that stay under rate limits or evade single-signal rules require combining multiple signals. For example, to challenge POST requests to /login that are not from verified bots:

  1. In the Cloudflare dashboard, go to Security > Security rules.

  2. Select Create rule > Custom rules.

  3. Enter a descriptive name.

  4. Under When incoming requests match, select Edit expression and enter:

    (http.request.uri.path eq "/login" and http.request.method eq "POST" and not cf.client.bot)
    
  5. Under Then take action, select Managed Challenge.

  6. Select Deploy.

  7. Review the results in Security Events. If the rule matches only bot traffic, change the action to Block.

For more expression fields and examples, refer to Custom rules use cases.

If bots are staying under your rate limiting thresholds, edit the rate limiting rule and reduce the request count or shorten the time window.

:::note Custom rules execute before Super Bot Fight Mode in the evaluation order. If a custom rule takes a terminating action (Block, Managed Challenge), the request does not reach Super Bot Fight Mode. Refer to Security features interoperability. :::

:::note[Enterprise Bot Management] Enterprise customers with Bot Management can tune rules using the cf.bot_management.score field for more granular control. Refer to Bot Management variables for available fields. :::

Bots

Application Security

Turnstile

Deploy frontend applications

Deploying a frontend application with React, Vue, Astro, or any other framework requires a platform that handles builds, previews, and global distribution. Cloudflare Workers deploys your frontend to 300+ edge locations with automatic builds triggered on push to GitHub or GitLab.

Solutions

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Get started

  1. Workers get started
  2. Configure custom domains

Web sites and web apps

import { CardGrid, DirectoryListing, LinkTitleCard } from "~/components";

Build and deploy full-stack web applications globally with serverless compute, storage, and instant deployments. Cloudflare Workers runs your frontend and backend logic at the edge. D1 provides a serverless SQL database. KV stores key-value data globally. R2 provides S3-compatible object storage with zero egress fees. Durable Objects coordinates real-time state. Queues handles background processing.

Architecture patterns

Full-stack application

Build a complete application with frontend and backend:

Real-time collaborative app

Build multiplayer or collaborative features:

Static site with dynamic features

Add interactivity to static content:


Prerequisites

Create a new application

Use an existing application


Complete documentation for building and deploying applications on Cloudflare.

Step-by-step guides for building on Cloudflare.

Optimize performance

Slow page loads increase bounce rates and reduce conversions. Cloudflare accelerates your application with edge caching, Argo Smart Routing to avoid congested network paths, and automatic asset optimization that improves Core Web Vitals scores.

Solutions

Cache

Cache content at Cloudflare's global network of edge locations. Learn more about Cache.

Argo Smart Routing

Route traffic through the fastest paths across Cloudflare's network. Learn more about Argo Smart Routing.

Speed

Automatic optimizations for HTML, CSS, JavaScript, and fonts. Learn more about Speed.

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Get started

  1. Configure Cache Rules
  2. Enable Argo Smart Routing
  3. Enable Speed optimizations
  4. Rewrite HTML at the edge with HTMLRewriter

Add real-time features

Real-time features, such as live chat, collaborative editing, and multiplayer interactions, require persistent connections and strongly consistent state. Cloudflare Durable Objects maintain WebSocket connections and coordinate shared state, while Queues handle background event processing.

Solutions

Durable Objects

Stateful objects with strongly consistent storage and coordination. Learn more about Durable Objects.

Queues

Reliable message queuing and background processing for Workers. Learn more about Queues.

Get started

  1. Durable Objects get started
  2. WebSocket connections with Durable Objects
  3. Queues get started

Secure your application

Web applications face threats at every layer: unencrypted traffic, injection attacks, DDoS floods, credential stuffing bots, and malicious third-party scripts. Cloudflare provides defense in depth from automatic SSL/TLS encryption through application security, DDoS protection, bot scoring, and client-side script monitoring.

Solutions

SSL/TLS

Encrypt all traffic with free, automatic SSL certificates. Learn more about SSL/TLS.

Application security

Get automatic protection from vulnerabilities and create your own custom rules. Learn more about Application security.

DDoS protection

Automatic mitigation of volumetric and application-layer DDoS attacks. Learn more about DDoS protection.

Bot security

Machine learning powered bot detection with granular control over bot traffic. Learn more about Bot security.

Turnstile

Privacy-preserving CAPTCHA alternative for forms and user interactions. Learn more about Turnstile.

Client-side security

Monitor and control third-party scripts and outbound connections on your pages. Learn more about Client-side security.

Get started

  1. Enable SSL/TLS
  2. Configure Application Security managed rules
  3. Add Turnstile to forms

Build serverless backends

Running backend code on traditional servers requires provisioning capacity, managing scaling, and accepting cold starts. Cloudflare Workers runs your server-side code at the edge with fast startup, automatic scaling, and global distribution across 300+ locations.

Solutions

Workers

Build and deploy serverless applications on Cloudflare's global network. Learn more about Workers.

Cron Triggers

Schedule Workers to run on a recurring basis. Learn more about Cron Triggers.

Queues

Reliable message queuing and background processing for Workers. Learn more about Queues.

Get started

  1. Workers get started
  2. Configure Cron Triggers
  3. Queues get started

Store application data

Web applications need different storage types for different workloads — relational data, key-value lookups, file uploads, and real-time state. Cloudflare provides serverless storage options including D1 (SQL), KV (key-value), R2 (object storage), and Durable Objects (strongly consistent state).

Solutions

D1

Serverless SQL database built on SQLite, with global read replication. Learn more about D1.

KV

Globally distributed key-value storage for low-latency reads. Learn more about KV.

R2

S3-compatible object storage with zero egress fees. Learn more about R2.

Durable Objects

Stateful objects with strongly consistent storage and coordination. Learn more about Durable Objects.

Get started

  1. D1 get started
  2. KV get started
  3. R2 get started
  4. Durable Objects get started