Support Article
KB · Cloudflare · rev 2026-11 ·
Edge security · SaaS and API workloads

Cloudflare for a SaaS app: ten changes that matter

Most Cloudflare deployments are configured for browsers. A SaaS app’s most important traffic comes from code. The first five changes close the gaps that hurt API-driven apps most. The next five are the baseline every zone should have. The last section covers geo controls, which are a business decision as much as a security one.

All plansPro+Enterprise Plan needed for each change. Cloudflare moves features between plans, so confirm against our current plan before committing.
0 of 11 changes taken
Before you start

Almost everything here is done in the Cloudflare dashboard. No Cloudflare CLI is needed. The commands are for verification, plus two optional origin tasks. The one real prerequisite: the zone is active on Cloudflare’s nameservers and the app records are proxied. If traffic doesn’t pass through Cloudflare, nothing below applies.

Access to arrange first
Tools on the workstation
Terminal · install tools
# macOS
brew install jq

# Ubuntu / WSL
sudo apt install -y curl jq dnsutils openssl
Set once per session

Replace the highlighted values with ours.

Terminal · set once
export CF_API_TOKEN="your-scoped-api-token"
export ZONE_ID="your-zone-id"
export APP_HOST="app.example.com"
export API_HOST="api.example.com"

Top 5 · The changes that matter for APIs

1Bypass cache for authenticated and API trafficAll plans

This is the one that turns a performance setting into a data exposure. If a “Cache Everything” rule touches the app, an authenticated JSON response can be cached at the edge and served to a different customer. The fix is an explicit bypass rule, placed last so nothing overrides it.

  1. Go to Caching → Cache Rules → Create rule. Name it “Bypass authenticated and API”.
  2. Choose Custom filter expression → Edit expression and paste the expression below.
  3. Set Cache eligibility → Bypass cache. Deploy, then drag the rule to the bottom of the list. Later rules win.
  4. Check Rules → Page Rules for any legacy “Cache Level: Cache Everything” rule matching the app or API hostnames. Remove or narrow it to static paths.
Rule expression
(http.host eq "api.example.com")
or starts_with(http.request.uri.path, "/api/")
or any(lower(http.request.headers.names[*])[*] == "authorization")
or http.cookie contains "session="
Verifyexpect DYNAMIC or BYPASS, never HIT
Terminal · run twice
curl -s -o /dev/null -D - -H "Authorization: Bearer $TEST_TOKEN" \
  "https://$API_HOST/v1/me" | grep -i cf-cache-status
2Lock the origin so Cloudflare can’t be bypassedAll plans

If the origin answers anyone who knows its IP, every rule on this page is optional for an adversary. SaaS teams often point the API hostname straight at a load balancer “for performance”. Route everything through Cloudflare, then make the origin refuse anything that didn’t come from it. If the origin IP was public before Cloudflare, assume it’s known.

  1. Inventory exposure. In DNS → Records, every record serving the app or API should be Proxied (orange cloud). Check MX and dev or staging records that share the same host.
  2. Preferred: run a Cloudflare Tunnel. In Zero Trust → Networks → Tunnels, create a tunnel, copy its install token and run the command below on the origin. The origin then needs no inbound ports at all.
  3. If a tunnel isn’t practical: restrict the origin firewall or AWS security group to Cloudflare’s published ranges, and remove the open rule.
  4. Add Authenticated Origin Pulls (SSL/TLS → Origin Server) so the origin also requires Cloudflare’s client certificate. An IP allowlist alone admits any Cloudflare customer’s traffic.
Option A · Tunnel on the origin
sudo cloudflared service install TUNNEL_TOKEN_FROM_DASHBOARD
Option B · AWS security group allowlist
SG=sg-0123456789abcdef0
for cidr in $(curl -s https://www.cloudflare.com/ips-v4); do
  aws ec2 authorize-security-group-ingress --group-id "$SG" \
    --ip-permissions "IpProtocol=tcp,FromPort=443,ToPort=443,IpRanges=[{CidrIp=$cidr,Description=cloudflare}]"
done
for cidr in $(curl -s https://www.cloudflare.com/ips-v6); do
  aws ec2 authorize-security-group-ingress --group-id "$SG" \
    --ip-permissions "IpProtocol=tcp,FromPort=443,ToPort=443,Ipv6Ranges=[{CidrIpv6=$cidr,Description=cloudflare}]"
done
# then close the open door
aws ec2 revoke-security-group-ingress --group-id "$SG" --protocol tcp --port 443 --cidr 0.0.0.0/0
Option B · nginx, require Authenticated Origin Pulls
# CA file: download from Cloudflare's Authenticated Origin Pulls docs
ssl_client_certificate /etc/nginx/certs/authenticated_origin_pull_ca.pem;
ssl_verify_client on;
Verifydirect hit should time out or fail TLS
Terminal
curl -sk -m 10 -o /dev/null -w "%{http_code}\n" \
  --resolve "$APP_HOST:443:ORIGIN_IP" "https://$APP_HOST/"
# expect: 000 (blocked) or a TLS error. A 200 means the origin is still open.
3Keep bot checks off API clients, focus them on loginPro+

A customer’s integration script can’t solve a challenge. Bot Fight Mode applied to API paths breaks integrations and webhooks, and the support tickets arrive before anyone connects the cause. Skip bot checks for authenticated API calls and known webhook paths. Keep them on login, signup and password reset, where credential stuffing happens. The skip only removes bot checks. The app still rejects invalid tokens, and rate limiting in change 4 still applies.

  1. Security → Bots → Configure Super Bot Fight Mode: definitely automated → Block, verified bots → Allow, JavaScript detections on.
  2. Security → WAF → Custom rules → Create rule named “Skip bot checks for API clients”. Paste the expression below.
  3. Action Skip, then tick All Super Bot Fight Mode rules. Place it first in the custom rules list.
  4. For webhooks, the app must verify the provider’s signature. A path match is not authentication.
  5. Enterprise only: add the bot score rule below for login paths.
Skip rule expression
(starts_with(http.request.uri.path, "/api/")
  and any(lower(http.request.headers.names[*])[*] == "authorization"))
or http.request.uri.path in {"/webhooks/stripe" "/webhooks/github"}
Enterprise · block low bot scores on login (action: Block)
http.request.uri.path in {"/login" "/api/auth/login" "/signup"}
and cf.bot_management.score lt 30
and not cf.bot_management.verified_bot
4Rate limit auth endpoints, and the API by keyPro+Enterprise for per-key

IP-based limits fail in both directions. One enterprise customer behind a corporate NAT looks like an attack, and an adversary rotating residential proxies looks like many polite users. Pro and Business count by IP, which is still worth having on auth endpoints. Enterprise Advanced Rate Limiting can count by API key or header, which is what a SaaS API needs. On Pro, the app should enforce its own per-key limits.

  1. Security → WAF → Rate limiting rules → Create rule named “Auth endpoints”.
  2. Paste the auth expression. Characteristics: IP. Start at 10 requests per 1 minute, action Block for 10 minutes. Use the closest values our plan offers.
  3. Enterprise: add a second rule for the API with characteristic Header value of authorization (or x-api-key). Set the threshold from real traffic, not a guess. Pull the busiest key’s peak from analytics and add headroom.
  4. Enterprise: on the auth rule, add a counting expression so only failed logins count toward the limit.
Auth rule expression
http.request.method eq "POST"
and http.request.uri.path in {"/login" "/api/auth/login" "/api/auth/password-reset"}
Enterprise · counting expression (failed logins only)
http.response.code in {401 403}
Verifyrun from a test IP, it will block you
Terminal
for i in $(seq 1 15); do
  curl -s -o /dev/null -w "%{http_code} " -X POST \
    -H "Content-Type: application/json" -d '{}' "https://$APP_HOST/api/auth/login"
done; echo
# expect: the early requests return 4xx from the app, then 429 from Cloudflare
5Validate the API at the edge with API Shield and mTLSEnterprisemTLS: check plan

Schema validation drops any request that doesn’t match our OpenAPI spec before it reaches the app. That stops a whole class of injection and mass-assignment attempts without writing WAF rules by hand. For partner or machine-to-machine integrations, mTLS means a stolen API key alone isn’t enough. The caller also needs the client certificate.

  1. Security → API Shield: add endpoints from discovery or by importing the spec. Upload the OpenAPI v3 schema.
  2. Set schema validation to Log for a week. Review what would have been blocked, fix the spec or the client, then switch to Block.
  3. For mTLS: SSL/TLS → Client Certificates → Create, issue one certificate per partner, and enable mTLS on the partner hostname.
  4. Add a WAF custom rule with the expression below, action Block.
mTLS enforcement expression
http.host eq "partners-api.example.com"
and not cf.tls_client_auth.cert_verified
Verify403 without cert, 200 with
Terminal
curl -s -o /dev/null -w "%{http_code}\n" https://partners-api.example.com/v1/health
curl -s -o /dev/null -w "%{http_code}\n" --cert client.pem --key client.key \
  https://partners-api.example.com/v1/health

Five more · The baseline every zone should have

6TLS done properlyAll plans

“Flexible” mode encrypts traffic to Cloudflare and sends it to the origin in plaintext. The padlock still shows. Full (strict) encrypts both legs and validates the origin certificate. HSTS is worth having, but a mistake persists in browsers for the full max-age, so start short.

  1. SSL/TLS → Origin Server → Create Certificate. Install the Origin CA certificate on the origin.
  2. SSL/TLS → Overview: set encryption mode to Full (strict).
  3. SSL/TLS → Edge Certificates: Always Use HTTPS on, Minimum TLS Version 1.2, TLS 1.3 on.
  4. Enable HSTS with a max-age of one day and no preload. Raise it to six months once every subdomain is confirmed on HTTPS. Add preload only when we’re certain.
VerifyTLS 1.1 refused, HSTS present
Terminal
openssl s_client -connect "$APP_HOST:443" -tls1_1 </dev/null 2>&1 | grep -iE "alert|no protocols"
curl -sI "https://$APP_HOST" | grep -i strict-transport-security
7WAF managed rules, deployed and tunedPro+

The Cloudflare Managed Ruleset is low-noise and safe to turn on. The OWASP Core Ruleset is noisier, especially against JSON request bodies, so it needs a tuning period. Enterprise can deploy it in Log mode. On Pro and Business, start at the least sensitive settings and tighten from there.

  1. Security → WAF → Managed rules: deploy the Cloudflare Managed Ruleset with default actions.
  2. Deploy the OWASP Core Ruleset at paranoia level PL1 with the lowest anomaly score sensitivity. Enterprise: use Log first.
  3. Review Security → Events daily for a week. Add exceptions scoped to the specific path and rule, never a blanket skip.
  4. Raise sensitivity one step at a time. Stop when false positives start.
  5. Turn on leaked credentials detection for the login endpoint so the origin is told when a submitted password is already known to be compromised. The app can then force a reset or MFA.
8Account and token hygieneAll plans

Whoever controls the Cloudflare account controls DNS, certificates and every rule on this page. It deserves the same protection as the AWS root account. The Global API Key grants full access to everything and should not exist in any script.

  1. Require SSO for the account, or security-key 2FA for every member.
  2. Manage Account → Members: give each person the narrowest role that works. Remove people who left.
  3. My Profile → API Tokens: replace any Global API Key use with scoped tokens limited to one zone and the permissions needed. Then roll the Global API Key.
  4. Review Manage Account → Audit Log monthly for rule, DNS and member changes.
Verifytoken is scoped and active
Terminal
curl -s https://api.cloudflare.com/client/v4/user/tokens/verify \
  -H "Authorization: Bearer $CF_API_TOKEN" | jq '.result.status'
9DNS hygieneAll plans

Unproxied records leak origin IPs. Stale CNAMEs pointing at deleted cloud resources invite subdomain takeover. DNSSEC stops spoofed answers, and CAA records limit which certificate authorities can issue for our domain.

  1. Run the audit below. Every unproxied record needs a reason. Delete records pointing at resources that no longer exist.
  2. DNS → Settings → Enable DNSSEC, then add the DS record at the registrar. Cloudflare shows the values.
  3. Add CAA records for the CAs we use. Cloudflare adds its own CA entries automatically once any CAA record exists.
Terminal · list unproxied records
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?per_page=500" \
  -H "Authorization: Bearer $CF_API_TOKEN" \
  | jq -r '.result[] | select(.proxied==false) | "\(.type)\t\(.name)\t\(.content)"'
VerifyDNSSEC and CAA in place
Terminal
dig +short DS example.com
dig +short CAA example.com
10Logging and alertsAlerts: all plansLogpush: Enterprise

The dashboard keeps security events for a short window. Incident questions tend to arrive weeks later. Logpush sends HTTP and firewall events to our SIEM or S3, which also becomes SOC 2 evidence instead of screenshots. Without Enterprise, alerts are the minimum.

  1. Notifications → Add: certificate expiry, DDoS attack alerts, and origin health or error-rate alerts where our plan offers them. Send to a shared channel, not one inbox.
  2. Enterprise: Analytics & Logs → Logpush. Create jobs for HTTP requests and Firewall events to the SIEM or an S3 bucket with a retention policy.
  3. Without Enterprise: export Security Events during any incident on day one, before they age out.
VerifyEnterprise · jobs exist and are enabled
Terminal
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/logpush/jobs" \
  -H "Authorization: Bearer $CF_API_TOKEN" | jq '.result[] | {name, dataset, enabled}'

Optional · Geo controls

11Block high-threat countries, challenge outside North AmericaAll plans

Geo rules cut background noise from opportunistic scanning and credential stuffing. They are not a strong control on their own, because any VPN or residential proxy gets around them. They do have a real business cost: a block list can quietly lock out a customer, a contractor or our own support vendor. So we check traffic before we block. The challenge rule must exclude API and webhook paths, for the same reason as change 3: code can’t solve a challenge.

  1. Check before blocking. In Security → Analytics (or Analytics & Logs → Traffic), filter the last 30 days by country. Any legitimate traffic from the listed countries, such as customers, offshore developers or a support provider, needs a decision before the rule goes live. Ukraine, India, Brazil and Romania are the usual surprises.
  2. Security → WAF → Custom rules → Create rule named “Block high-threat countries”. Paste the block expression. Action Block. T1 is Cloudflare’s code for Tor exit nodes.
  3. Create a second rule named “Challenge outside North America”. Paste the challenge expression. Action Managed Challenge. Place it below the block rule.
  4. If a known partner or office sits outside North America, add their IPs to an IP list (Manage Account → Configurations → Lists) and append and not ip.src in $partner_ips to both rules.
  5. Watch Security → Events for a week, filtered to these two rules, and review anything that looks like a real user.
Block rule expression · action: Block
ip.src.country in {"RU" "BR" "CN" "KP" "IR" "NG" "RO" "SY" "SD" "UA" "IN" "T1"}
Challenge rule expression · action: Managed Challenge
ip.src.continent ne "NA"
and http.host ne "api.example.com"
and not starts_with(http.request.uri.path, "/api/")
and not http.request.uri.path in {"/webhooks/stripe" "/webhooks/github"}
and not cf.client.bot

The block expression is the same list written as one set. It’s easier to maintain, and ip.src.country replaces the older ip.geoip.country field. The original form still works if pasted as written.

Verifyfrom a VPN exit outside North America
Terminal · from a non-NA VPN exit
curl -sI "https://$APP_HOST/" | grep -i cf-mitigated
# expect: cf-mitigated: challenge
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $TEST_TOKEN" "https://$API_HOST/v1/me"
# expect: 200. A 403 means the API exclusion is missing.