惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
博客园_首页
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
美团技术团队
小众软件
小众软件
Jina AI
Jina AI
S
SegmentFault 最新的问题
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Bot Protection in SvelteKit on Cloudflare Pages
Tested.GG · 2026-05-03 · via DEV Community

If you're running a SvelteKit app on Cloudflare Pages and your content is publicly accessible, commodity scrapers will find it eventually. Here's the protection setup we use at Tested.gg - two layers, mostly free, minimal code.

The architecture problem first

If your API is behind Cloudflare Service Bindings (not publicly exposed over HTTP), scrapers can only hit your SvelteKit Pages app. That's your entire attack surface. All protection goes there, not on the API Worker.

This matters because most bot protection tutorials target REST APIs. In a service-binding architecture, the SvelteKit SSR layer is the only thing that faces the public internet.

Layer 1: WAF Rate Limiting (Cloudflare Dashboard, free)

Cloudflare's free tier includes WAF rate limiting rules. These execute at the edge, before your Pages Worker runs, which makes them strictly faster and cheaper than application-level rate limiting.

Dashboard > Security > WAF > Rate limiting rules:

General page limit:

Match: URI Path starts with /
Rate: 60 requests per minute per IP
Action: Block (10 minutes)

Enter fullscreen mode Exit fullscreen mode

Write endpoint limit:

Match: URI Path starts with /site AND Method = POST
Rate: 10 requests per minute per IP
Action: Block (1 hour)

Enter fullscreen mode Exit fullscreen mode

One important property: CDN cache HITs don't count against rate limiting rules because they never reach the Worker. Your thresholds only apply to cache misses - which is exactly the right behavior. A human browsing cached pages won't trip the limit; a scraper busting the cache will.

Layer 2: Threat Score in SvelteKit hooks

Cloudflare populates cf.threatScore on every request - a 0-100 score derived from their IP reputation database. 0 is clean, 100 is worst. It's available on every plan, for free.

First, add cf to your Platform interface in app.d.ts:

namespace App {
  interface Platform {
    env: Cloudflare.Env;
    context: {
      waitUntil(promise: Promise<unknown>): void;
    };
    caches: CacheStorage;
    cf?: IncomingRequestCfProperties;
  }
}

Enter fullscreen mode Exit fullscreen mode

Then create a bot-guard.ts hook:

import type { Handle } from "@sveltejs/kit";

const THREAT_SCORE_THRESHOLD = 30;

export const handleBotGuard: Handle = ({ event, resolve }) => {
  const cf = event.platform?.cf;

  if (!cf) return resolve(event);

  const threatScore =
    "threatScore" in cf && typeof cf.threatScore === "number"
      ? cf.threatScore
      : 0;

  if (threatScore > THREAT_SCORE_THRESHOLD) {
    console.warn(
      `[bot-guard] Blocked: id=${event.locals.requestId} ip=${event.getClientAddress()} score=${threatScore} path=${event.url.pathname}`
    );
    return new Response("Access denied", {
      status: 403,
      headers: {
        "Content-Type": "text/plain",
        "Retry-After": "3600"
      }
    });
  }

  return resolve(event);
};

Enter fullscreen mode Exit fullscreen mode

Wire it into hooks.server.ts after your platform setup, before auth or SSR:

export const handle: Handle = sequence(
  handleRequestId,
  handlePlatform,
  handleBotGuard,
  handleAuth
);

Enter fullscreen mode Exit fullscreen mode

Position matters. Block high-threat requests before spending CPU on auth token validation, database calls, or SSR rendering.

Why not KV-based rate limiting?

The common suggestion is to implement per-IP rate limiting inside the Worker using KV. Skip it:

  • Dashboard WAF rules run at the edge before the Worker - strictly faster
  • KV's get + put pattern is not atomic - two concurrent requests from the same IP can both read count = 59, both write count = 60, and neither gets blocked
  • KV reads add latency and cost on every request

Dashboard rules are always preferable when they're expressive enough for your use case.

Tuning the threshold

Start at THREAT_SCORE_THRESHOLD = 30. Monitor Workers Logs for [bot-guard] entries after deploying. If you see false positives (real users blocked), raise it to 40. If you see continued bot traffic, lower it to 20.


This setup handles commodity scrapers and known-bad IPs. Sophisticated scrapers that rotate clean IPs and mimic browser behavior are a different problem - that's what Cloudflare's paid Bot Management tier is for. But for most content sites, these two layers cover the vast majority of automated traffic.