# Verify connection URL: https://developers.cloudflare.com/1.1.1.1/check/ import { PublicStats } from "~/components"; After setting up `1.1.1.1`, you can check if you are correctly connected to Cloudflare's resolver. 1. Open a web browser on a configured device (smartphone or computer) or on a device connected to your configured router. 2. Enter [https://1.1.1.1/help](https://one.one.one.one/help) on the browser address bar. Wait for the page to load and run its tests. The page will present you a summary of the type of connection you have to `1.1.1.1`, as well as the Cloudflare data center you are connected to. --- # FAQ URL: https://developers.cloudflare.com/1.1.1.1/faq/ import { GlossaryTooltip } from "~/components" Below you will find answers to our most commonly asked questions. If you cannot find the answer you are looking for, refer to the [community page](https://community.cloudflare.com/) to explore more resources. ## What is 1.1.1.1? 1.1.1.1 is Cloudflare's fast and secure DNS resolver. When you request to visit an application like `cloudflare.com`, your computer needs to know which server to connect you to so that it can load the application. Computers don’t know how to do this name to address translation, so they ask a specialized server to do it for them. This specialized server is called a DNS recursive resolver. The resolver’s job is to find the address for a given name, like `2400:cb00:2048:1::c629:d7a2` for `cloudflare.com`, and return it to the computer that asked for it. Computers are configured to talk to specific DNS resolvers, identified by IP address. Usually the configuration is managed by your ISP (like Comcast or AT\&T) if you are on your home or wireless Internet, and by your network administrator if you’re connected to the office Internet. You can also change the configured DNS resolver your computer talks to yourself. ## How can I check if my computer / smartphone / tablet is connected to 1.1.1.1? Visit [1.1.1.1/help](https://one.one.one.one/help) to make sure your system is connected to 1.1.1.1 and that it is working. ## What do DNS resolvers do? DNS resolvers are like address books for the Internet. They translate the name of places to addresses so that your browser can figure out how to get there. DNS resolvers do this by working backwards from the top until they find the website your are looking for. Every resolver knows how to find the invisible `.` at the end of domain names (for example, `cloudflare.com.`). There are [hundreds of root servers](http://www.root-servers.org/) all over the world that host the `.` file, and resolvers are [hard coded to know the IP addresses](http://www.internic.net/domain/named.root) of those servers. Cloudflare itself hosts [that file](http://www.internic.net/domain/root.zone) on all of its servers around the world through a [partnership with ISC](https://blog.cloudflare.com/f-root/). The resolver asks one of the root servers where to find the next link in the chain — the top-level domain (abbreviated to TLD) or domain ending. An example of a TLD is `.com` or `.org`. Luckily, the root servers store the locations of all the TLD servers, so they can return which IP address the DNS resolver should go ask next. The resolver then asks the TLD’s servers where it can find the domain it is looking for. For example, a resolver might ask `.com` where to find `cloudflare.com`. TLDs host a file containing the location of every domain using the TLD. Once the resolver has the final IP address, it returns the answer to the computer that asked. This whole system is called the [Domain Name System (DNS)](https://www.cloudflare.com/learning/dns/what-is-dns/). This system includes the servers that host the information (called [authoritative DNS](https://www.cloudflare.com/learning/dns/dns-server-types/)) and the servers that seek the information (the DNS resolvers). ## Does 1.1.1.1 support ANY? Cloudflare [stopped supporting the ANY query](https://blog.cloudflare.com/deprecating-dns-any-meta-query-type/) in 2015 as ANY queries are more often used to perpetuate large volumetric attacks against the DNS system than valid use. 1.1.1.1 returns `NOTIMPL` when asked for `qtype==ANY`. ## How does 1.1.1.1 work with DNSSEC? 1.1.1.1 is a DNSSEC validating resolver. 1.1.1.1 sends the `DO` (`DNSSEC OK`) bit on every query to convey to the authoritative server that it wishes to receive signed answers if available. 1.1.1.1 supports the signature algorithms specified in [Supported DNSKEY signature algorithms](/1.1.1.1/encryption/dnskey/). ## ​Does 1.1.1.1 send EDNS Client Subnet header? 1.1.1.1 is a privacy centric resolver so it does not send any client IP information and does not send the EDNS Client Subnet (ECS) header to authoritative servers. The exception is the single Akamai debug domain `whoami.ds.akahelp.net` to aid in cross-provider debugging. However, Cloudflare does not send ECS to any of Akamai's production domains, such as `akamaihd.net` or similar. ## Does 1.1.1.1 support IPv6? 1.1.1.1 has full IPv6 support. ## What is Purge Cache? 1.1.1.1's Purge Cache tool allows you to refresh 1.1.1.1's DNS cache for domain names. To refresh the cache for a domain name, visit the [Purge Cache page](https://one.one.one.one/purge-cache/). ## What is query name minimization? Cloudflare minimizes privacy leakage by only sending minimal query name to authoritative DNS servers. For example, if a client is looking for foo.bar.example.com, the only part of the query 1.1.1.1 discloses to .com is that we want to know who’s responsible for example.com and the zone internals stay hidden. ## What are root hints? For decreased latency, reduced privacy leakage of queries and lower load on the DNS system, 1.1.1.1 upstreams to [locally hosted root zone files](https://blog.cloudflare.com/f-root/). ## Can IPs used by 1.1.1.1 be allowlisted? Authoritative DNS providers may want to allowlist IP's 1.1.1.1 uses to query upstream DNS providers. The comprehensive list of IP's to allowlist is available at [https://www.cloudflare.com/ips/](https://www.cloudflare.com/ips/). --- # 1.1.1.1 (DNS Resolver) URL: https://developers.cloudflare.com/1.1.1.1/ import { Description, Feature, Plan, RelatedProduct } from "~/components" Speed up your online experience with Cloudflare's public DNS resolver. 1.1.1.1 is Cloudflare’s public DNS resolver. It offers a fast and private way to browse the Internet. [DNS resolvers](https://www.cloudflare.com/learning/dns/what-is-dns/) translate domains like `cloudflare.com` into the IP addresses necessary to reach the website (like `104.16.123.96`). Unlike most DNS resolvers, 1.1.1.1 does not sell user data to advertisers. 1.1.1.1 has also been measured to be the [fastest DNS resolver available](https://www.dnsperf.com/#!dns-resolvers) — it is deployed in [hundreds of cities worldwide](https://www.cloudflare.com/network/), and has access to the addresses of millions of domain names on the same servers it runs on. 1.1.1.1 is completely free. Setting it up takes minutes and requires no special software. *** ## Features 1.1.1.1 for Families has additional protection against malware and adult content. 1.1.1.1 offers an encrypted service through DNS over HTTPS (DoH) or DNS over TLS (DoT) for increased security and privacy. You can also access 1.1.1.1 [as a Tor hidden service](/1.1.1.1/other-ways-to-use-1.1.1.1/dns-over-tor/). *** ## Related products Access the Internet in a more secure and private way. Cloudflare's global DNS platform provides speed and resilience. DNS customers also benefit from free DNSSEC, and protection against route leaks and hijacking. Secure and accelerate your TCP or UDP based applications. --- # IP addresses URL: https://developers.cloudflare.com/1.1.1.1/ip-addresses/ import { Render } from "~/components" Consider the tables below to know which IPv4 or IPv6 addresses are used by the different Cloudflare DNS resolver offerings. For detailed guidance refer to [Set up](/1.1.1.1/setup/). *** ## 1.1.1.1 1.1.1.1 is Cloudflare’s public DNS resolver. It offers a fast and private way to browse the Internet. | IPv4 | IPv6 | | ------------------------ | -------------------------------------------------- | | `1.1.1.1`
`1.0.0.1` | `2606:4700:4700::1111`
`2606:4700:4700::1001` | Refer to [Encryption](/1.1.1.1/encryption/) to learn how to use 1.1.1.1 in an encrypted way. *** ## 1.1.1.1 for Families 1.1.1.1 for Families categorizes destinations on the Internet based on the potential threat they pose regarding malware, phishing, or other types of security risks. For more information, refer to [1.1.1.1 for Families set up](/1.1.1.1/setup/#1111-for-families). ### Block malware | IPv4 | IPv6 | | ------------------------ | -------------------------------------------------- | | `1.1.1.2`
`1.0.0.2` | `2606:4700:4700::1112`
`2606:4700:4700::1002` | ### Block malware and adult content | IPv4 | IPv6 | | ------------------------ | -------------------------------------------------- | | `1.1.1.3`
`1.0.0.3` | `2606:4700:4700::1113`
`2606:4700:4700::1003` | --- # Terms of use URL: https://developers.cloudflare.com/1.1.1.1/terms-of-use/ By using 1.1.1.1 Public DNS Resolver or 1.1.1.1 for Families, you consent to be bound by the [Cloudflare Website and Online Services Terms of Use](https://www.cloudflare.com/website-terms/). --- # Troubleshooting URL: https://developers.cloudflare.com/1.1.1.1/troubleshooting/ import { Render } from "~/components" This guide will help you diagnose and resolve common issues with Cloudflare's DNS Resolver. Before proceeding with manual troubleshooting steps, you can [verify your connection](/1.1.1.1/check/) to automatically gather relevant information. ## Name resolution issues ### Linux/macOS ```sh # Test DNS resolution dig example.com @1.1.1.1 dig example.com @1.0.0.1 dig example.com @8.8.8.8 # Check connected nameserver dig +short CHAOS TXT id.server @1.1.1.1 dig +short CHAOS TXT id.server @1.0.0.1 # Optional: Network information dig @ns3.cloudflare.com whoami.cloudflare.com txt +short ``` ### Windows ```sh # Test DNS resolution nslookup example.com 1.1.1.1 nslookup example.com 1.0.0.1 nslookup example.com 8.8.8.8 # Check connected nameserver nslookup -class=chaos -type=txt id.server 1.1.1.1 nslookup -class=chaos -type=txt id.server 1.0.0.1 # Optional: Network information nslookup -type=txt whoami.cloudflare.com ns3.cloudflare.com ``` **Note:** The network information command reveals your IP address. Only include this in reports to Cloudflare if you are comfortable sharing this information. For additional analysis, you can generate a [DNSViz](http://dnsviz.net/) report for the domain in question. ## Connectivity and routing issues Before reporting connectivity issues: 1. Search for existing reports from your country and ISP. 2. Run traceroutes to both Cloudflare DNS resolvers. ### Linux/macOS ```sh # Basic connectivity tests traceroute 1.1.1.1 traceroute 1.0.0.1 # If reachable, check nameserver identity dig +short CHAOS TXT id.server @1.1.1.1 dig +short CHAOS TXT id.server @1.0.0.1 # TCP connection tests dig +tcp @1.1.1.1 id.server CH TXT dig +tcp @1.0.0.1 id.server CH TXT ``` ### Windows ```sh # Basic connectivity tests tracert 1.1.1.1 tracert 1.0.0.1 # If reachable, check nameserver identity nslookup -class=chaos -type=txt id.server 1.1.1.1 nslookup -class=chaos -type=txt id.server 1.0.0.1 # TCP connection tests nslookup -vc -class=chaos -type=txt id.server 1.1.1.1 nslookup -vc -class=chaos -type=txt id.server 1.0.0.1 ``` ## DNS-over-TLS (DoT) troubleshooting ### Linux/macOS ```sh # Test TLS connectivity openssl s_client -connect 1.1.1.1:853 openssl s_client -connect 1.0.0.1:853 # Test DNS resolution over TLS kdig +tls @1.1.1.1 id.server CH TXT kdig +tls @1.0.0.1 id.server CH TXT ``` ### Windows Windows does not include a standalone DoT client. You can test TLS connectivity using OpenSSL after installing it manually. ## DNS-over-HTTPS (DoH) troubleshooting ### Linux/macOS ```sh curl -H 'accept: application/dns-json' 'https://cloudflare-dns.com/dns-query?name=cloudflare.com&type=AAAA' ``` ### Windows ```powershell (Invoke-WebRequest -Uri 'https://cloudflare-dns.com/dns-query?name=cloudflare.com&type=AAAA').RawContent ``` ## Common issues ### First hop failures If your traceroute fails at the first hop, the issue is likely hardware-related. Your router may have a hardcoded route for 1.1.1.1. When reporting this issue, include: - Router make and model - ISP name - Any relevant router configuration details ## Additional resources - [1.1.1.1 DNS Resolver homepage](https://1.1.1.1) - [DNS over TLS documentation](/1.1.1.1/encryption/dns-over-tls/) - [Diagnostic tool](https://one.one.one.one/help/) --- # Cloudflare Aegis URL: https://developers.cloudflare.com/aegis/ import { CardGrid, Description, GlossaryTooltip, LinkTitleCard, Plan, RelatedProduct } from "~/components" Leverage dedicated IPs to improve your origin security and implement Zero Trust. Cloudflare Aegis provides dedicated egress IPs (from Cloudflare to your origin) for your layer 7 [WAF](/waf/) and CDN services, as well as [Spectrum](/spectrum/). The egress IPs are reserved exclusively for your account so that you can increase your origin security by only allowing traffic from a small list of IP addresses. *** ## Related products Cloudflare Access determines who can reach your application by applying the Access policies you configure. Cloudflare Tunnel provides you with a secure way to connect your resources to Cloudflare without a publicly routable IP address. Authenticated Origin Pulls gives you the ability to perform mutual TLS between Cloudflare and your origin environment, providing cryptographically verifiable proof of the source of the traffic you receive. *** ## More resources Deep dive into use cases where Aegis can help secure enterprise origins. Reference Architecture for multi-vendor application security and performance. --- # Build agents on Cloudflare URL: https://developers.cloudflare.com/agents/ import { CardGrid, Description, Feature, LinkButton, LinkTitleCard, Plan, RelatedProduct, Render, TabItem, Tabs, } from "~/components"; Build AI-powered agents that can autonomously perform tasks, persist state, browse the web, and communicate back to users in real-time over any channel. - **Non I/O bound pricing:** don't pay for long-running processes when your code is not executing. Cloudflare Workers is designed to scale down and [only charge you for CPU time](https://blog.cloudflare.com/workers-pricing-scale-to-zero/), as opposed to wall-clock time. - **Designed for durable execution:** [Durable Objects](/durable-objects/) and [Workflows](/workflows) are built for a programming model that enables guaranteed execution for async tasks like long-running deep thinking LLM calls, human-in-the-loop, or unreliable API calls. - **Scalable, and reliable, without compromising on performance:** by running on Cloudflare's network, agents can execute tasks close to the user without introducing latency for real-time experiences. ## Start building Build agents that can execute complex tasks, progressively save state, and call out to _any_ third party API they need to using [Workflows](/workflows/). Send emails or [text messages](/workflows/examples/twilio/), [browse the web](/browser-rendering/), process and summarize documents, and/or query your database. ```sh npm create cloudflare@latest workflows-starter -- --template "cloudflare/workflows-starter" cd workflows-starter npm i resend ``` ```ts collapse={30-1000} import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; import { Resend } from 'resend'; type Env = { MY_WORKFLOW: Workflow; RESEND_API_KEY: string; }; type Params = { email: string; metadata: Record; }; export class MyWorkflow extends WorkflowEntrypoint { async run(event: WorkflowEvent, step: WorkflowStep) { const files = await step.do('my first step', async () => { // Fetch a list of files from $SOME_SERVICE return { files: [ 'doc_7392_rev3.pdf', 'report_x29_final.pdf', 'memo_2024_05_12.pdf', 'file_089_update.pdf', 'proj_alpha_v2.pdf', 'data_analysis_q2.pdf', 'notes_meeting_52.pdf', 'summary_fy24_draft.pdf', ], }; }); const summaries = await step.do('summarize text', async () => { const results = {}; for (const filename of files.files) { const fileContent = await this.env.MY_BUCKET.get(filename); if (!fileContent) continue; const text = await fileContent.text(); const summary = await this.env.WORKERS_AI.run('@cf/meta/llama-3.2-3b-instruct', { messages: [{ role: 'user', content: `Please summarize the following text concisely: ${text}` }] }); results[filename] = summary.response; } return results; }); await step.sleep('wait on something', '1 minute'); let summaryKey = await step.do( 'store summaries in R2', async () => { const summaryKey = `summaries-${Date.now()}.json`; await this.env.MY_BUCKET.put(summaryKey, JSON.stringify(summaries)); return summaryKey; }, ); await step.do( 'email summaries', { retries: { limit: 3, delay: '5 second', backoff: 'exponential', } }, async () => { const summaryText = Object.entries(summaries) .map(([filename, summary]) => `${filename}:\n${summary}\n\n`) .join(''); const resend = new Resend(this.env.RESEND_API_KEY); await resend.emails.send({ from: 'notifications@yourdomain.com', to: event.payload.email, subject: 'Your Document Summaries', text: summaryText, }); } ); return summaryKey; } } export default { async fetch(req: Request, env: Env): Promise { let id = new URL(req.url).searchParams.get('instanceId'); if (id) { let instance = await env.MY_WORKFLOW.get(id); return Response.json({ status: await instance.status(), }); } let instance = await env.MY_WORKFLOW.create(); return Response.json({ id: instance.id, details: await instance.status(), }); }, }; ``` Use [Durable Objects](/durable-objects/) — stateful, serverless, long-running micro-servers — to ship interactive, real-time agents that can connect to the latest AI models. Stream responses over [WebSockets](/durable-objects/best-practices/websockets/), and don't time out while waiting for the latest chain-of-thought models — including `o1` or `deepseek-r1` — to respond. ```ts npm i openai ``` ```ts collapse={30-1000} import { DurableObject } from "cloudflare:workers"; export interface Env { DURABLE_AGENT: DurableObjectNamespace; OPENAI_API_KEY: string; } export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { if (request.url.endsWith("/agent/chat")) { const upgradeHeader = request.headers.get("Upgrade"); if (!upgradeHeader || upgradeHeader !== "websocket") { return Response.json( { error: "Durable Object expected Upgrade: websocket" }, { status: 426 } ); } const url = new URL(request.url); const agentId = url.searchParams.get("id") || (await crypto.randomUUID()); let id = env.DURABLE_AGENT.idFromName(agentId); let agent = env.DURABLE_AGENT.get(id); return agent.fetch(request); } return Response.json({ message: "Bad Request" }, { status: 400 }); }, }; export class DurableAgent extends DurableObject { constructor(private state: DurableObjectState, private env: Env) { super(); } async fetch(request: Request): Promise { const webSocketPair = new WebSocketPair(); const [client, server] = Object.values(webSocketPair); this.ctx.acceptWebSocket(server); return new Response(null, { status: 101, webSocket: client, }); } async webSocketMessage(ws: WebSocket, message: ArrayBuffer | string) { try { const openai = new OpenAI({ apiKey: this.env.OPENAI_API_KEY, timeout: 10 * 60 * 1000, // Don't let it think TOO long. }); // Stream the response to immediately start sending chunks to the client, // rather than buffering the entire response and making the user wait const stream = await openai.chat.completions.create({ model: "o1", messages: [{ role: "user", content: message.toString() }], stream: true, }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content; if (content) { ws.send(content); } } } catch (error) { ws.send( JSON.stringify({ error: "OpenAI request failed", message: error.message, }) ); } } async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) { ws.close(code, "Durable Object is closing WebSocket"); } } ``` Use the [Browser Rendering API](/browser-rendering/) to allow your agents to search the web, take screenshots, and directly interact with websites. ```sh npm install @cloudflare/puppeteer --save-dev ``` ```ts collapse={30-1000} import puppeteer from "@cloudflare/puppeteer"; interface Env { MYBROWSER: Fetcher; BROWSER_KV_DEMO: KVNamespace; } export default { async fetch(request: Request, env: Env): Promise { const { searchParams } = new URL(request.url); const url = searchParams.get("url"); if (!url) { return new Response("Please add an ?url=https://example.com/ parameter"); } const normalizedUrl = new URL(url).toString(); let img = await env.BROWSER_KV_DEMO.get(normalizedUrl, { type: "arrayBuffer" }); if (img === null) { const browser = await puppeteer.launch(env.MYBROWSER); const page = await browser.newPage(); await page.goto(normalizedUrl); img = await page.screenshot() as Buffer; await env.BROWSER_KV_DEMO.put(normalizedUrl, img, { expirationTtl: 60 * 60 * 24, // 24 hours }); await browser.close(); } return new Response(img, { headers: { "content-type": "image/jpeg", }, }); }, }; ``` Use [AI Gateway](/ai-gateway/) to cache, log, retry and run [evals](/ai-gateway/evaluations/) (evaluations) for your agents, no matter where they're deployed. ```py collapse={30-1000} from anthropic import Anthropic anthropic = Anthropic( api_key="", # Route, cache, fallback and log prompt-response pairs between your app # and your AI model provider. base_url="https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/anthropic" ) message = anthropic.messages.create( model="claude-3-opus-20240229", max_tokens=1000, messages=[{ "role": "user", "content": "Generate a Cloudflare Worker that returns a simple JSON payload based on a query param", }] ) print(message.content) ``` ## Use your favorite AI framework Build agents using your favorite AI frameworks, and deploy it directly to [Cloudflare Workers](/workers/). Use [LangChain](https://js.langchain.com/docs/integrations/text_embedding/cloudflare_ai/) to build Retrieval-Augmented Generation (RAG) applications using [Workers AI](/workers-ai/) and [Vectorize](/vectorize/). Give your agents more context and the ability to search across content, reply to user queries, and expand their domain knowledge. ```sh npm i @langchain/cloudflare hono ``` ```ts collapse={30-1000} import { CloudflareVectorizeStore, CloudflareWorkersAIEmbeddings } from "@langchain/cloudflare"; import { VectorizeIndex } from "@cloudflare/workers-types"; import { Ai } from "@cloudflare/ai"; import { Hono } from "hono"; export interface Env { VECTORIZE_INDEX: VectorizeIndex; AI: Ai; } const app = new Hono<{ Bindings: Env }>(); app.get("/", async (c) => { const embeddings = new CloudflareWorkersAIEmbeddings({ binding: c.env.AI, model: "@cf/baai/bge-small-en-v1.5", }); const store = new CloudflareVectorizeStore(embeddings, { index: c.env.VECTORIZE_INDEX, }); const results = await store.similaritySearch("hello", 5); return c.json(results); }); app.post("/load", async (c) => { const embeddings = new CloudflareWorkersAIEmbeddings({ binding: c.env.AI, model: "@cf/baai/bge-small-en-v1.5", }); const store = new CloudflareVectorizeStore(embeddings, { index: c.env.VECTORIZE_INDEX, }); const documents = [ { pageContent: "hello", metadata: {} }, { pageContent: "world", metadata: {} }, { pageContent: "hi", metadata: {} } ]; await store.addDocuments(documents, { ids: ["id1", "id2", "id3"] }); return c.json({ success: true }); }); app.delete("/clear", async (c) => { const embeddings = new CloudflareWorkersAIEmbeddings({ binding: c.env.AI, model: "@cf/baai/bge-small-en-v1.5", }); const store = new CloudflareVectorizeStore(embeddings, { index: c.env.VECTORIZE_INDEX, }); await store.delete({ ids: ["id1", "id2", "id3"] }); return c.json({ success: true }); }); export default app; ``` Ship faster with the [AI SDK](https://sdk.vercel.ai/docs/introduction): make it easier to generate text, tool call and/or get structured output from your AI models (and then deploy it [Workers](/workers/). ```sh npm i ai workers-ai-provider ``` ```ts collapse={30-1000} import { createWorkersAI } from 'workers-ai-provider'; import { streamText } from 'ai'; type Env = { AI: Ai; }; export default { async fetch(_: Request, env: Env) { const workersai = createWorkersAI({ binding: env.AI }); const result = streamText({ model: workersai('@cf/meta/llama-3.2-3b-instruct'), prompt: 'Write short essay on why you like Cloudflare Durable Objects.', }); return result.toTextStreamResponse({ headers: { 'Content-Type': 'text/x-unknown', 'content-encoding': 'identity', 'transfer-encoding': 'chunked', }, }); }, }; ``` Use any model provider with OpenAI compatible endpoints, including [ChatGPT](https://platform.openai.com/docs/quickstart), [DeepSeek](https://api-docs.deepseek.com/) and [Workers AI](/workers-ai/configuration/open-ai-compatibility/), directly from Cloudflare Workers. ```sh npm i openai ``` ```ts collapse={30-1000} import OpenAI from "openai"; export interface Env { OPENAI_API_KEY: string; } export default { async fetch(request: Request, env: Env) { const url = new URL(request.url); const prompt = url.searchParams.get('prompt') || "Make some robot noises"; const openai = new OpenAI({ apiKey: env.OPENAI_API_KEY }); const chatCompletion = await openai.chat.completions.create({ messages: [{ role: "user", content: prompt }], model: "gpt-3.5-turbo", }); const embeddings = await openai.embeddings.create({ model: "text-embedding-ada-002", input: "Cloudflare Agents documentation", }); return new Response(JSON.stringify({ chatCompletion, embeddings })); } } ``` *** ## All the products you need in one platform Observe and control your AI applications with caching, rate limiting, request retries, model fallback, and more. Build full-stack AI applications with Vectorize, Cloudflare’s vector database. Adding Vectorize enables you to perform tasks such as semantic search, recommendations, anomaly detection or can be used to provide context and memory to an LLM. Run machine learning models, powered by serverless GPUs, on Cloudflare's global network. Build real-time serverless video, audio and data applications with WebRTC running on Cloudflare's network. Build stateful agents that guarantee executions, including automatic retries, persistent state that runs for minutes, hours, days, or weeks. --- # Changelog URL: https://developers.cloudflare.com/ai-gateway/changelog/ import { ProductChangelog } from "~/components"; {/* */} --- # Architectures URL: https://developers.cloudflare.com/ai-gateway/demos/ import { GlossaryTooltip, ResourcesBySelector } from "~/components"; Learn how you can use AI Gateway within your existing architecture. ## Reference architectures Explore the following reference architectures that use AI Gateway: --- # Get started URL: https://developers.cloudflare.com/ai-gateway/get-started/ import { Details, DirectoryListing, LinkButton, Render } from "~/components"; In this guide, you will learn how to create your first AI Gateway. You can create multiple gateways to control different applications. ## Prerequisites Before you get started, you need a Cloudflare account. Sign up ## Create gateway Then, create a new AI Gateway. ## Choosing gateway authentication When setting up a new gateway, you can choose between an authenticated and unauthenticated gateway. Enabling an authenticated gateway requires each request to include a valid authorization token, adding an extra layer of security. We recommend using an authenticated gateway when storing logs to prevent unauthorized access and protect against invalid requests that can inflate log storage usage and make it harder to find the data you need. Learn more about setting up an [Authenticated Gateway](/ai-gateway/configuration/authentication/). ## Connect application Next, connect your AI provider to your gateway. AI Gateway offers multiple endpoints for each Gateway you create - one endpoint per provider, and one Universal Endpoint. To use AI Gateway, you will need to create your own account with each provider and provide your API key. AI Gateway acts as a proxy for these requests, enabling observability, caching, and more. Additionally, AI Gateway has a [WebSockets API](/ai-gateway/configuration/websockets-api/) which provides a single persistent connection, enabling continuous communication. This API supports all AI providers connected to AI Gateway, including those that do not natively support WebSockets. Below is a list of our supported model providers: If you do not have a provider preference, start with one of our dedicated tutorials: - [OpenAI](/ai-gateway/integrations/aig-workers-ai-binding/) - [Workers AI](/ai-gateway/tutorials/create-first-aig-workers/) ## View analytics Now that your provider is connected to the AI Gateway, you can view analytics for requests going through your gateway.
:::note[Note] The cost metric is an estimation based on the number of tokens sent and received in requests. While this metric can help you monitor and predict cost trends, refer to your provider’s dashboard for the most accurate cost details. ::: ## Next steps - Learn more about [caching](/ai-gateway/configuration/caching/) for faster requests and cost savings and [rate limiting](/ai-gateway/configuration/rate-limiting/) to control how your application scales. - Explore how to specify model or provider [fallbacks](/ai-gateway/configuration/fallbacks/) for resiliency. - Learn how to use low-cost, open source models on [Workers AI](/ai-gateway/providers/workersai/) - our AI inference service. --- # Header Glossary URL: https://developers.cloudflare.com/ai-gateway/glossary/ import { Glossary } from "~/components"; AI Gateway supports a variety of headers to help you configure, customize, and manage your API requests. This page provides a complete list of all supported headers, along with a short description ## Configuration hierarchy Settings in AI Gateway can be configured at three levels: **Provider**, **Request**, and **Gateway**. Since the same settings can be configured in multiple locations, the following hierarchy determines which value is applied: 1. **Provider-level headers**: Relevant only when using the [Universal Endpoint](/ai-gateway/providers/universal/), these headers take precedence over all other configurations. 2. **Request-level headers**: Apply if no provider-level headers are set. 3. **Gateway-level settings**: Act as the default if no headers are set at the provider or request levels. This hierarchy ensures consistent behavior, prioritizing the most specific configurations. Use provider-level and request-level headers for more fine-tuned control, and gateway settings for general defaults. --- # Overview URL: https://developers.cloudflare.com/ai-gateway/ import { CardGrid, Description, Feature, LinkTitleCard, Plan, RelatedProduct, } from "~/components"; Observe and control your AI applications. Cloudflare's AI Gateway allows you to gain visibility and control over your AI apps. By connecting your apps to AI Gateway, you can gather insights on how people are using your application with analytics and logging and then control how your application scales with features such as caching, rate limiting, as well as request retries, model fallback, and more. Better yet - it only takes one line of code to get started. Check out the [Get started guide](/ai-gateway/get-started/) to learn how to configure your applications with AI Gateway. ## Features View metrics such as the number of requests, tokens, and the cost it takes to run your application. Gain insight on requests and errors. Serve requests directly from Cloudflare's cache instead of the original model provider for faster requests and cost savings. Control how your application scales by limiting the number of requests your application receives. Improve resilience by defining request retry and model fallbacks in case of an error. Workers AI, OpenAI, Azure OpenAI, HuggingFace, Replicate, and more work with AI Gateway. --- ## Related products Run machine learning models, powered by serverless GPUs, on Cloudflare’s global network. Build full-stack AI applications with Vectorize, Cloudflare’s vector database. Adding Vectorize enables you to perform tasks such as semantic search, recommendations, anomaly detection or can be used to provide context and memory to an LLM. ## More resources Connect with the Workers community on Discord to ask questions, show what you are building, and discuss the platform with other developers. Learn how you can build and deploy ambitious AI applications to Cloudflare's global network. Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Workers. --- # Types of analytics URL: https://developers.cloudflare.com/analytics/types-of-analytics/ import { Badge } from "~/components"; Cloudflare Analytics is a comprehensive product that encompasses all metadata generated by the Cloudflare network. You can access these insights through the Cloudflare dashboard. Depending on where in the dashboard you are, it will show you different aspects from the collected metadata. ## Account-level analytics ### Account Analytics (beta) Available under **Analytics & Logs** in your Cloudflare dashboard when you log in, Account Analytics (beta) shows you an [overview of traffic for all domains](/analytics/account-and-zone-analytics/account-analytics/) under your Cloudflare account, such as requests and bandwidth by country, information related to security, cache, and errors, among others. To access Account Analytics, [log in to the Cloudflare dashboard](https://dash.cloudflare.com/login), select the appropriate account, and go to **Analytics & Logs** > **Account Analytics**. ### Network Analytics Network Analytics provides [visibility into network and transport-layer traffic patterns, and DDoS attacks](/analytics/network-analytics/). The Network Analytics dashboard is only available for customers with an Enterprise domain plan who use [Spectrum](/spectrum/), [Magic Transit](/magic-transit/), or [Bring Your Own IP (BYOIP)](/byoip/). ### Web Analytics Web Analytics (formerly known as Browser Insights) [provides free, privacy-first analytics for your website](/web-analytics/). Web Analytics does not collect your visitor's personal data, and allows you to have a detailed view into the performance of web pages as experienced by your visitors. ### Carbon Impact Report Carbon Impact Report gives you a [report on carbon savings](https://blog.cloudflare.com/understand-and-reduce-your-carbon-impact-with-cloudflare/) from using Cloudflare services versus Internet averages for your usage volume. Cloudflare is committed to use 100% renewable energy sources, but also to [remove all greenhouse gases emitted](https://blog.cloudflare.com/cloudflare-committed-to-building-a-greener-internet/) as a result of powering our network since 2010. ## Analytics related to specific properties Access aggregated traffic, security, and performance metrics for each domain proxied through Cloudflare. To access these analytics, [log in to the Cloudflare dashboard](https://dash.cloudflare.com/login), select your account and domain, and go to the **Analytics & Logs** section. Data available under the **Analytics & Logs** section includes: * **HTTP Traffic** - Requests, Data transfer, Page views, Visits, and [API requests](/api-shield/security/api-discovery/#api-requests). * **Security** - Total Threats, Top Crawlers/Bots, Rate Limiting, Total Threats Stopped. * **Performance** - Origin Performance, Bandwidth Saved. * **Edge Reachability** - [Last mile insights](/network-error-logging/) for Enterprise customers. * **Workers** - [Detailed information](/workers/observability/metrics-and-analytics/) related to your Workers per zone, and Workers KV per account. * **Logs** - [Detailed logs](/logs/) of the metadata generated by Cloudflare products for Enterprise customers. * **Instant logs** - [Live stream of traffic](/logs/instant-logs/) for your domain. Enterprise customers can access this live stream from the Cloudflare dashboard or from a command-line interface (CLI). ## Product analytics Beyond the analytics provided for your properties, you can also access analytics related to specific products: * [Bot Analytics](/bots/bot-analytics/) - Shows which requests are associated with known bots, likely automated traffic, likely human traffic, and more. * [Cache Analytics](/cache/performance-review/cache-analytics/) - Insights to that help determine if resources are missing from cache, expired, or ineligible for caching. * [Security Events](/waf/analytics/security-events/) - Highlights attack and mitigation metrics detected by the Cloudflare WAF and HTTP DDoS protection systems. * [Security Analytics](/waf/analytics/security-analytics/) - Displays information about all incoming HTTP requests, including those not affected by security measures (for example, from the WAF and DDoS protection systems). * [Load Balancing Analytics](/load-balancing/reference/load-balancing-analytics/) - Features metrics to help gain insights into traffic load balancer steering decisions. ## GraphQL APIs If you would like to have more control over how you visualize the analytic and log information available on the Cloudflare dashboard, use the [GraphQL Analytics API](/analytics/graphql-api/) to build customized views. This API replaces and expands on the previous Zone Analytics API. --- # Analytics URL: https://developers.cloudflare.com/analytics/ import { Feature, RelatedProduct } from "~/components" Cloudflare visualizes the metadata collected by our products in the Cloudflare dashboard. Refer to [Types of analytics](/analytics/types-of-analytics/) for more information about the various types of analytics and where they exist in the dashboard. *** ## Features Send unlimited-cardinality data from your Worker to a time-series database. Query it with SQL. Provides details about the requests and traffic related to your Cloudflare accounts and zones. Provides near real-time visibility into network and transport-layer traffic patterns and DDoS attacks. Provides all of your performance, security, and reliability data from one endpoint. Select exactly what you need, from one metric for a domain to multiple metrics aggregated for your account. *** ## Related products Cloudflare Workers allows developers to build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale. Detailed logs that contain metadata generated by Cloudflare products helpful for debugging, identifying configuration adjustments, and creating analytics. --- # API Gateway URL: https://developers.cloudflare.com/api-shield/api-gateway/ API Gateway is a package of features that will do everything for your APIs, including: - **Security**: Protect your API from malicious traffic with [API Discovery](/api-shield/security/api-discovery/), [Schema Validation](/api-shield/security/schema-validation/), [mTLS validation](/api-shield/security/mtls/), and more. - **Management and monitoring**: Streamline API management with [Endpoint Management](/api-shield/management-and-monitoring/) and [tools](https://blog.cloudflare.com/api-gateway/) like analytics, routing, and authentication. - **Logging, quota management, and more**: All of Cloudflare's [established features](https://blog.cloudflare.com/api-gateway/), like caching, load balancing, and log integrations work natively with API Gateway. For more details about API Gateway, refer to the [introductory blog post](https://blog.cloudflare.com/api-gateway/). --- # Changelog URL: https://developers.cloudflare.com/api-shield/changelog/ import { ProductChangelog } from "~/components"; {/* */} --- # FAQ URL: https://developers.cloudflare.com/api-shield/frequently-asked-questions/ ## Why are my API endpoints not found by API Discovery? In most cases, this is due to the system not observing enough valid requests over a continuous period. API Discovery only looks at requests that satisfy all of the following criteria: 1. Requests must return `2XX` response codes from the edge. 2. Requests must not come directly from Cloudflare Workers. 3. At least 500 requests are made to the discovered endpoint within a 10 day period. Endpoints discovered using session identifiers will be labeled as such in the dashboard. If the endpoints are not discovered through session identifiers, they will be discovered using our machine learning-based [API Discovery](/api-shield/security/api-discovery/). --- ## How does Cloudflare calculate the recommended rate limit for my endpoint? Cloudflare uses both the volume and frequency of traffic to guide your recommended rate. We calculate the recommended rate value throughout the day, and the new calculation may equal the existing recommendation due to similar traffic profiles existing on your API. When we recalculate, we look at requests that happened in the last 24 hours. You can view the `P50`/`95`/`99` of your request count for more details under an endpoint’s expanded view. --- ## Will I be able to access an endpoint’s data after I delete it? No. Cloudflare will stop tracking performance data when you delete an endpoint and its previous data will not be stored. This means that if you save this endpoint again, the metrics will start tracking from the point that you save it. --- ### Why do I not receive threshold recommendations for my discovered API endpoints? Thresholds can only be recommended for endpoints that receive sufficient levels of traffic that meet the following criteria: - Only requests with the same criteria as API Discovery are considered. - If traffic has been erratic or intermittent to this endpoint, the threshold might not show up. Cloudflare needs endpoints to receive sufficient valid traffic in any 24-hour period in the last 7 days or since the initial discovery of the endpoint to make statistically safe threshold suggestions. - Cloudflare also requires at least 50 distinct sessions to have accessed the endpoint in any 24-hour period in the last 7 days or since the initial discovery of the endpoint. To detect sessions, you must set up [session identifiers](/api-shield/get-started/#session-identifiers). If you do not receive threshold recommendations for a discovered endpoint, you will see one of the following error codes: - `404 response`: Cloudflare has not seen sufficient valid traffic for this zone to generate recommendations. - `551 response`: Cloudflare has successfully generated recommendations at some point in the past, but we have not seen sufficient recent valid traffic to provide up-to-date recommendations. --- ## Does API Shield work for JDCloud customers? Not currently. --- ## What version of OpenAPI specification do you support? The importing ([Schema Validation](/api-shield/security/schema-validation/)) and exporting ([Schema Learning](/api-shield/management-and-monitoring/#endpoint-schema-learning)) of OpenAPI schemas from our product to customers is done using **OpenAPI v3.0**. Any specifications using patched versions (3.0.x) are compatible as well. --- ## Why am I not seeing latency metrics? Latency metrics currently are not supported when a Cloudflare Worker is running on the URL, as the requests are not passed directly to your origin. Some Cloudflare products such as [Waiting Room](/waiting-room/) are built on top of Workers, so the same limitations apply to applications using these products. --- # Get started with API Shield URL: https://developers.cloudflare.com/api-shield/get-started/ import { GlossaryTooltip, Render } from "~/components" This guide will help you set up API Shield to identify and address API security best practices. :::note Enabling API Shield features will have no impact on your traffic until you choose to move a setting from `log` to `block` mode. ::: ## Session identifiers ### To set up session identifiers ## Upload a schema using Schema Validation (optional) Schema Validation protects your APIs by ensuring only requests matching your API schema are allowed to communicate with your origin. While not strictly required, uploading a pre-existing schema will offer the chance to automatically add endpoints to Endpoint Management. If you already have a schema, you can upload it to [Schema Validation](/api-shield/security/schema-validation/). :::note It is recommended to start with Schema Validation rules set to `log` to review logged requests in **Security** > **Events**. When you are confident that only the correct requests are logged, you should switch the rule to `block`. ::: If you do not have a schema to upload, continue reading this guide to learn how to generate a schema with API Shield. ## Enable the Sensitive Data Detection ruleset and accompanying rules API Shield works with Cloudflare WAF’s [Sensitive Data Detection](/api-shield/management-and-monitoring/#sensitive-data-detection) ruleset to identify API endpoints that return sensitive data such as social security or credit card numbers in their HTTP responses. Monitoring these endpoints can be critical to ensuring sensitive data is returned only when expected. :::note A subscription is required for Sensitive Data Detection. Contact your account team if you are not entitled for Sensitive Data Detection. ::: You can identify endpoints returning sensitive data by selecting the icon next to the path in a row. Expand the endpoint to see details on which rules were triggered and view more information by exploring events in **Firewall Events**. ## Add your discovered endpoints to Endpoint Management Cloudflare’s machine learning models have already inspected your existing traffic for the presence of API endpoints. By adding endpoints from API Discovery to Endpoint Management, you can unlock further security, visibility, and management features of the platform. Endpoint Management monitors the health of your API endpoints by saving, updating, and monitoring performance metrics. :::note Schema Validation, Schema Learning, JWT Validation, Sequence Analytics, Sequence Mitigation, and rate limit recommendations only run on endpoints saved to Endpoint Management. ::: You can save your endpoints directly from [API Discovery](/api-shield/management-and-monitoring/#add-endpoints-from-api-discovery), [Schema Validation](/api-shield/management-and-monitoring/#add-endpoints-from-schema-validation), or [manually](/api-shield/management-and-monitoring/#add-endpoints-manually) by method, path, and host. This will add the specified endpoints to your list of managed endpoints. You can view your list of saved endpoints in the **Endpoint Management** page. Cloudflare will aggregate [performance data](/api-shield/management-and-monitoring/#endpoint-performance-analysis) and security data on your endpoint once it is saved. ### Allow the system to learn your traffic patterns Cloudflare will inspect your API traffic and begin to learn its schema over the next 24 hours after adding an endpoint. Depending on how much traffic an individual endpoint sees, our confidence in the resulting schema may differ. Cloudflare will also use the configured session identifiers to suggest rate limits per endpoint. For best results, allow at least 24 hours after adding endpoints before proceeding to the following steps. We recommend proceeding with [additional configurations](/api-shield/get-started/#additional-configuration) if this is your first time setting up API Shield and have added your first API endpoints to Endpoint Management. ## Add rate limits to your most sensitive endpoints [Rate limiting rules](/waf/rate-limiting-rules/) allow you to define rate limits for requests matching an expression, and choose the action to perform when those rate limits are reached. You can observe Cloudflare suggested rate limits in Endpoint Management for endpoints using session identifiers. Unlike many security tools, these recommended rate limits are per-endpoint and per-session, not site-wide and not based on IP address. When creating a rule, it will be based on only traffic to that specific endpoint from unique visitors during their session. This feature allows you to be very specific and targeted with your rate limit enforcement, both lowering abusive traffic and false positives due to broadly scoped rules. ## Import a learned schema to Schema Validation Cloudflare learns schema parameters via traffic inspection for all endpoints stored in Endpoint Management. You can export OpenAPI schemas in OpenAPI v3.0.0 format by hostname. By importing the learned schema, you can protect API endpoints found via API Discovery that were never previously possible to protect due to not knowing about their presence or schema. You can import the learned schema of an entire hostname using the [Cloudflare dashboard](/api-shield/security/schema-validation/#add-validation-by-applying-a-learned-schema-to-an-entire-hostname). Alternatively, you can [apply learned schemas to individual endpoints](/api-shield/security/schema-validation/#add-validation-by-applying-a-learned-schema-to-a-single-endpoint). Before applying the learned schema, Cloudflare suggests exporting the schema to review what will validate your traffic. ## Export a learned schema from Endpoint Management Learned schemas will always include the listed hostname in the servers section, all endpoints by host, method, and path, and detected path variables. They can also potentially include detected query parameters and their format. You can optionally include API Shield’s rate limit threshold recommendations. You can export your learned schemas in the [Cloudflare dashboard](/api-shield/management-and-monitoring/#export-a-schema) or via the [API](/api/resources/api_gateway/subresources/schemas/methods/list/). ## View and configure Sequence Analytics [Sequence Analytics](/api-shield/security/sequence-analytics/) surfaces a subset of important API request sequences found in your API traffic over time. You can observe the top sequences in your API traffic that contain endpoints stored in Endpoint Management. We rank sequences by Correlation Score. High-scoring sequences contain API requests which are likely to occur together in order. [Sequence Mitigation](/api-shield/security/sequence-mitigation/) allows you to enforce request patterns for authenticated clients communicating with your API. Use Sequence Analytics to better understand the request sequences used by your API clients. You should apply all possible API Shield protections (rate limiting suggestions, Schema Validation, JWT Validation, and mTLS) to API endpoints found in high correlation score sequences that make up the critical request flows in your application. You should also check their specific endpoint order with your development team. For more information, refer to [Detecting API abuse automatically using sequence analysis](https://blog.cloudflare.com/api-sequence-analytics) blog post. ## Additional configuration ### Set up JSON Web Tokens (JWT) Validation Use the Cloudflare API to configure [JSON Web Tokens Validation](/api-shield/security/jwt-validation/), which validates the integrity and validity of JWTs sent by clients to your API or web application. ### Set up GraphQL Malicious Query Protection If your origin uses GraphQL, you may consider setting limits on GraphQL query size and depth. [GraphQL malicious query protection](/api-shield/security/graphql-protection/configure/) scans your GraphQL traffic for queries that could overload your origin and result in a denial of service. Customers can build rules that limit the query depth and size of incoming GraphQL queries in order to block suspiciously large or complex queries. For more information, refer to the [blog post](https://blog.cloudflare.com/protecting-graphql-apis-from-malicious-queries/). ### Mutual TLS (mTLS) authentication If you operate an API that requires or would benefit from an extra layer of protection, you may consider using Mutual TLS (mTLS). [Mutual TLS (mTLS) authentication](/api-shield/security/mtls/) uses client certificates to ensure traffic between client and server is bidirectionally secure and trusted. mTLS also allows requests that do not authenticate via an identity provider, such as Internet-of-things (IoT) devices, to demonstrate they can reach a given resource. --- # Glossary URL: https://developers.cloudflare.com/api-shield/glossary/ import { Glossary } from "~/components" Review the definitions for terms used across Cloudflare's API Shield documentation. --- # Overview URL: https://developers.cloudflare.com/api-shield/ import { Description, Feature, Plan, RelatedProduct, Render } from "~/components" Identify and address your API vulnerabilities. ## Why care about API security? Refer to the [Get started](/api-shield/get-started/) guide to set up API Shield. ## Features Secure your APIs using API Shield's security features. A package of features that will do everything for your APIs. ## Availability Cloudflare API Security products are available to Enterprise customers only, though anyone can set up [Mutual TLS](/api-shield/security/mtls/) with a Cloudflare-managed certificate authority. The full API Shield security suite is available as an Enterprise-only paid add-on, but all customers can access [Endpoint Management](/api-shield/management-and-monitoring/) and [Schema Validation](/api-shield/security/schema-validation/) functionalities. ## Related products Cloudflare DDoS protection secures websites, applications, and entire networks while ensuring the performance of legitimate traffic is not compromised. --- # Plans URL: https://developers.cloudflare.com/api-shield/plans/ Free, Pro, Business, and Enterprise customers without an API Gateway subcription can access [Endpoint Management](/api-shield/management-and-monitoring/) and [Schema Validation](/api-shield/security/schema-validation/), but no other [API Gateway](/api-shield/api-gateway/) features. To subscribe to API Gateway, upgrade to an Enterprise plan and contact your account team. Limits to endpoints apply to Endpoint Management and Schema Validation. Refer to the table below for limits based on your zone plan. | Plan type | Saved endpoints | Uploaded schemas | Total uploaded schema size | Rule action | | --- | --- | --- | --- | --- | | **Free** | 100 | 5 | 200 kB | `Block` only | | **Pro** | 250 | 5 | 500 kB | `Block` only | | **Business** | 500 | 10 | 2 MB | `Block` only | | **Enterprise without API Gateway** | 500 | 5 | 5 MB | `Log` or `Block` | | **Enterprise with API Gateway** | 10,000 | 10+ | 10+ MB | `Log` or `Block` | --- # Analytics URL: https://developers.cloudflare.com/argo-smart-routing/analytics/ Cloudflare provides analytics to show the performance benefits of Argo Smart Routing. You can access Argo analytics for your domain in the [Cloudflare dashboard](https://dash.cloudflare.com/) at **Analytics** > **Performance**. For information on all analytics in the dashboard, refer to [Analytics](/analytics/). ## How it works Analytics collects data based on the time-to-first-byte (TTFB) from your origin to the Cloudflare network. TTFB is the delay between when Cloudflare sends a request to your server and when it receives the first byte in response. Argo Smart Routing optimizes your server's network transit time to minimize this delay. :::note Detailed performance data within **Origin Performance (Argo)** will only display if Argo has routed at least 500 origin requests within the last 48 hours. ::: ## Types of analytics The dashboard displays two different views for performance data: * **Origin Response Time**: A histogram shows response time from your origin to the Cloudflare network. The blue bars show TTFB without Argo, while the orange bars show TTFB where Argo found a Smart Route. * **Geography**: A map shows the improvement in response time at each Cloudflare data center. * A negative value indicates that requests from that location would not have benefited from Argo Smart Routing, so instead would have been routed directly. --- # Argo for Packets URL: https://developers.cloudflare.com/argo-smart-routing/argo-for-packets/ Argo for Packets provides IP layer network optimizations to supercharge your Cloudflare network services products like [Magic Transit](/magic-transit/), [Magic WAN](/magic-wan/), and [Cloudflare for Offices](https://blog.cloudflare.com/cloudflare-for-offices/). Argo for Packets dynamically chooses the best possible path through Cloudflare's network and looks at every path back from every Cloudflare data center back to your origin, down to the individual network path. Argo compares existing Layer 4 traffic and network analytics across all of these unique paths to determine the fastest, most available path. Customers with multiple locations will especially benefit from Argo for Packets because it optimizes complex paths on the Internet and makes them just as fast as the other paths. To begin using Argo for Packets, contact your account manager. --- # Get started URL: https://developers.cloudflare.com/argo-smart-routing/get-started/ import { Render, TabItem, Tabs } from "~/components"; Argo Smart Routing is a one-click solution to speed up your global traffic. To enable [Argo Smart Routing](https://dash.cloudflare.com/?to=/:account/:zone/traffic) in the dashboard: 1. Log in to your [Cloudflare dashboard](https://dash.cloudflare.com/) and select your account and domain. 2. Go to **Traffic** > **Argo Smart Routing**. 3. For **Argo Smart Routing**, switch the toggle to **On**. 4. Provide your billing information. - If you do not have a [billing profile](/fundamentals/subscriptions-and-billing/create-billing-profile/), enter your billing information. - If you have a billing profile, confirm your billing information. To enable or disable Argo Smart Routing with the API, send a [`PATCH`](/api/resources/argo/subresources/smart_routing/methods/edit/) request with the `value` parameter set to your desired setting (`"on"` or `"off"`). You will need to already have a [billing profile](/fundamentals/subscriptions-and-billing/create-billing-profile/) on your account to enable Argo Smart Routing. ## Billing If Cloudflare mitigates attacks on your site - whether through DDoS protection, the WAF, or other mechanisms - that traffic will not be included in any charges for Argo Smart Routing. ## Enable Tiered Cache [Cache](/cache/) works by storing a copy of website content at Cloudflare's data centers. [Tiered Cache](/cache/how-to/tiered-cache/) divides these data centers into a hierarchy based on location. This behavior allows Cloudflare to deliver content from data centers closest to your visitor. Argo Smart Routing and Tiered Cache work together to provide the most efficient connection for visitors to your site. For more information, go to [Tiered Cache](/cache/how-to/tiered-cache/). --- # Argo Smart Routing URL: https://developers.cloudflare.com/argo-smart-routing/ import { CardGrid, Description, Feature, LinkTitleCard, Plan, RelatedProduct, Render } from "~/components" Speed up your global traffic with a single click Argo Smart Routing detects real-time network issues and routes your web traffic across the most efficient network path, avoiding congestion. This results in faster loading times, increased reliability, and reduced costs. These benefits are most apparent for users farthest from your origin server. Learn more about the [benefits of Argo Smart Routing](https://www.cloudflare.com/application-services/products/argo-smart-routing/). *** ## Features Argo Smart Routing includes comprehensive analytics to compare performance improvements with and without Argo enabled. *** ## Related products Increase cache hit ratios to reduce requests to your origin server. Improve security and performance within mainland China. Reduce latency and protect from DDoS attacks using the Cloudflare network. *** ## More resources Compare available Cloudflare plans Explore pricing options for Argo in the dashboard --- # Welcome URL: https://developers.cloudflare.com/automatic-platform-optimization/ Take your WordPress site’s performance to the next level with Automatic Platform Optimizations (APO). APO allows Cloudflare to serve your entire WordPress site from its edge network ensuring consistent, fast performance for visitors no matter where they are. Automatic Platform Optimization is the result of using the power of Cloudflare Workers to intelligently cache dynamic content. By caching dynamic content, Cloudflare can serve the entire website from our edge network to make a site's time to first byte (TTFB) both fast and consistent. To read more about the benefits of using APO with your site, see [The Benefits of Automatic Platform Optimization blog](https://blog.cloudflare.com/automatic-platform-optimizations-starting-with-wordpress/#the-benefits-of-automatic-platform-optimization). You must use the Cloudflare for WordPress plugin to begin using APO. --- # Changelog URL: https://developers.cloudflare.com/bots/changelog/ import { ProductChangelog } from "~/components"; {/* */} --- # Glossary URL: https://developers.cloudflare.com/bots/glossary/ import { Glossary } from "~/components" Review the definitions for terms used across Cloudflare's Bots documentation. --- # Overview URL: https://developers.cloudflare.com/bots/ import { CardGrid, Description, Feature, LinkTitleCard, Plan, RelatedProduct, Render } from "~/components" Identify and mitigate automated traffic to protect your domain from bad bots. While Cloudflare offers several products that relate to bot traffic, this section reviews our bot-specific products, Bot Fight Mode, Super Bot Fight Mode, and Bot Management for Enterprise. ## Which bot solution do I need? ## Features Detect and mitigate bot traffic on your domain. Identify traffic matching patterns of known bots, challenge or block bots, protect static resources, and view analytics to help you understand bot traffic using Super Bot Fight Mode. Use Bot Analytics to dynamically examine bot traffic. Access several new variables within the Firewall expression builder. ## Related products Identify and address API vulnerabilities using API Shield. Detect and mitigate Distributed Denial of Service (DDoS) attacks using Cloudflare's Autonomous Edge. Use Cloudflare's smart CAPTCHA alternative to run less intrusive challenges. Get automatic protection from vulnerabilities and the flexibility to create custom rules. ## More resources Compare available Cloudflare plans --- # Changelog URL: https://developers.cloudflare.com/browser-rendering/changelog/ import { ProductChangelog } from "~/components"; {/* */} --- # FAQ URL: https://developers.cloudflare.com/browser-rendering/faq/ import { GlossaryTooltip } from "~/components"; Below you will find answers to our most commonly asked questions. If you cannot find the answer you are looking for, refer to the [Discord](https://discord.cloudflare.com) to explore additional resources. ##### Uncaught (in response) TypeError: Cannot read properties of undefined (reading 'fetch') Make sure that you are passing your Browser binding to the `puppeteer.launch` api and that you have [Workers for Platforms Paid plan](/cloudflare-for-platforms/workers-for-platforms/platform/pricing/). ##### Will browser rendering bypass Cloudflare's Bot Protection? Browser rendering requests are always identified as bots by Cloudflare. If you are trying to **scan** your **own zone**, you can create a [WAF skip rule](/waf/custom-rules/skip/) to bypass the bot protection using a header or a custom user agent. ## Puppeteer ##### Code generation from strings disallowed for this context while using an Xpath selector Currently it's not possible to use Xpath to select elements since this poses a security risk to Workers. As an alternative try to use a css selector or `page.evaluate` for example: ```ts const innerHtml = await page.evaluate(() => { return ( // @ts-ignore this runs on browser context new XPathEvaluator() .createExpression("/html/body/div/h1") // @ts-ignore this runs on browser context .evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue .innerHTML ); }); ``` :::note Keep in mind that `page.evaluate` can only return primitive types like strings, numbers, etc. Returning an `HTMLElement` will not work. ::: --- # FAQ URL: https://developers.cloudflare.com/bots/troubleshooting/ import { Render, RuleID } from "~/components"; ## Bots ## How does Cloudflare detect bots? Cloudflare uses multiple methods to detect bots, but these vary by plan. For more details, refer to [Plans](/bots/plans). --- ## How do I know what's included in my plan? To know what's included in your plan, refer to our [Plans](/bots/plans). --- ## How do I set up my bot product? To learn how to set up your bot product, refer to [Get started](/bots/get-started). --- ## Yandex bot unexpectedly blocked by the WAF managed rule with ID `...f6cbb163` Yandex updates their bots very frequently, you may see more false positives while these changes are propagated. New and recently updated bots will occasionally be blocked by a Cloudflare WAF managed rule, as the IP list of Yandex bots has not yet synced with Yandex's most recent changes. **Workarounds:** - Create an [exception](/waf/managed-rules/waf-exceptions/) to temporarily skip the managed rule with ID when a request is coming from the **Yandex IP** and the user-agent contains **Yandex.** - Create a [WAF custom rule with the _Skip_ action](/waf/custom-rules/skip/) to temporarily bypass WAF Managed Rules when a request is coming from the **Yandex IP** and the user-agent contains **Yandex.** If you are using the legacy WAF managed rules ([now deprecated](/waf/reference/migration-guides/waf-managed-rules-migration/)), disable the WAF managed rule with ID `100203` temporarily. **Solution:** Once the new Yandex IP is propagated to our system, the requests will not be blocked anymore and you can remove any workaround you configured. This can take up to 48 hours. If you see any Yandex bots still being blocked after 48 hours with no change to the bot, contact [Cloudflare Support](/support/contacting-cloudflare-support/). --- ## How does machine learning work? Supervised machine learning takes certain variables (X) like gender and age and predicts another variable (Y) like income. In Bot Management and Super Bot Fight Mode, the X variables are request features, while the Y variable represents the probability of solving a challenge based on X values. Cloudflare uses data from millions of requests and re-train the system on a periodic basis. You can learn about this data from your own request logs such as Cloudflare Logpull and Logpush as well as the Firewall API. --- ## Why am I seeing a Managed Challenge action for WAF rules? When you choose to challenge different bot categories with Bot Fight Mode or Super Bot Fight Mode, you will see Security Events with an **Action Taken** of **Managed Challenge**. You may also see Managed Challenge due to a triggered [WAF custom rule](/waf/reference/cloudflare-challenges/#managed-challenge-recommended). This does not mean that your traffic was blocked. It is the challenge sent to your user to determine whether they are likely human or likely bot. To understand if the result of the challenge was a success or a failure, you can verify using [Logpush](/logs/about/). ## Does the WAF run before Super Bot Fight Mode? Yes. WAF rules are executed before Super Bot Fight Mode. If a WAF custom rule performs a [terminating action](/ruleset-engine/rules-language/actions/) such as _Block_, your Super Bot Fight Mode configuration will not be evaluated. --- ## What is the difference between the threat score and bot management score? The difference is significant: - Threat score (_cf.threat_score_) is what Cloudflare uses to determine IP Reputation. It goes from 0 (good) to 100 (bad). - Bot management score (_cf.bot_management.score_) is what Cloudflare uses in Bot Management to measure if the request is from a human or a script. The scores range from 1 (bot) to 99 (human). Lower scores indicate the request came from a script, API service, or an automated agent. Higher scores indicate that the request came from a human using a standard desktop or mobile web browser. These fields are available via [WAF custom rules](/waf/custom-rules/) and other products based on the Ruleset Engine. --- ## What is cf.bot_management.verified_bot? A request's _cf.bot_management.verified_bot_ value is a boolean indicating whether such request comes from a Cloudflare allowed bot. Cloudflare has built an allowlist of good, automated bots, e.g. Google Search Engine, Pingdom, and more. This allowlist is large based on reverse DNS verification, meaning that the IPs we allow really match the requesting service. In addition to this, Cloudflare uses multiple validation methods including ASN blocks and public lists. If none of these validation types are available for a customer, we use internal Cloudflare data and machine learning to identify legitimate IP addresses from good bots. To allow traffic from good bots, use the [Verified Bot](/ruleset-engine/rules-language/fields/reference/cf.bot_management.verified_bot/) field in your WAF custom rule. --- ## Why might the ja3hash be empty in HTTP logs? The JA3 Fingerprint can be null or empty in some cases. The most common case is for HTTP requests, because JA3 is calculated in TLS, but can also be empty due to the following: - Orange to Orange zones (Cloudflare Zone proxied to another Cloudflare Zone). - Worker sending requests within the same zone or to a zone that is not proxied (or a 3rd party). --- ## I run a good bot and want for it to be added to the allowlist (cf.bot_management.verified_bot). What should I do? Cloudflare maintains a sample list of verified bots in [Cloudflare Radar](https://radar.cloudflare.com/verified-bots). As a bot operator, in order to be listed by Cloudflare as a Verified Bot, your bot must conform with our [verified bot public policy](/bots/reference/verified-bots-policy/). If your bot meets this criteria, submit this [online application](https://docs.google.com/forms/d/e/1FAIpQLSdqYNuULEypMnp4i5pROSc-uP6x65Xub9svD27mb8JChA_-XA/viewform?usp=sf_link). --- ## What information do I need to troubleshoot my bot issues? If you are experiencing errors with your bot solution and need to submit a Support request, include the following information: :::caution The following information gathering are required when you are experiencing issues (e.g. false positives) with Enterprise Bot Management only (Enterprise plan). Because Bot Fight Mode (BFM) and Super Bot Fight Mode (SBFM) are set at a domain level, we often find that disabling these features is the best solution to false positives. Please follow instructions in the following questions on how to disable BFM and SBFM features. We conduct more thorough investigations for Enterprise Bot Management. ::: - RayIDs - IP addresses - WAF custom rule IDs, rule expression, Challenge solve rates - Common user-agents among false positives - Common ASNs among false positives - Screenshots of strange activity from the WAF, such as a huge spike in challenged traffic on the graph - Problematic URIs or paths - Rough description of how your domain is configured. - Is one zone Cloudflare for SaaS while the others are not? - Is most API traffic sent to a particular URI? - How much mobile traffic do you expect? --- ## What should I do if I am getting False positives caused by Bot Fight Mode (BFM) or Super Bot Fight Mode (SBFM)? :::caution[Important considerations you need to be aware of before turning on BFM or SBFM] - BFM and SBFM are high security features intended to quickly help customers under active attack stop as many bots as possible. Due to the high security threshold, false positives do sometimes happen. - BFM has limited control. You cannot bypass or skip BFM using the _Skip_ action in WAF custom rules or using Page Rules. BFM will be disabled if there are any IP Access rules present. If you turned on BFM during an attack, and the attack has subsided, we recommend either disabling the feature using IP Access rules to bypass BFM, or looking at [Bot Management for Enterprise](/bots/plans/bm-subscription/), which gives you the ability to precisely customize your security threshold and create exception rules as needed. - SBFM can be bypassed with IP Access _Allow_ action rules. You can use the _Skip_ action in [WAF custom rules](/waf/custom-rules/skip/) to specify where Super Bot Fight Mode should not run. ::: **How to disable BFM/SBFM feature?** If you encounter any issues with BFM/SBFM feature (e.g. false positive), you can disable it under **Security** > **Bots**. - For **Free** plans, toggle the **Bot Fight Mode** option to **Off** - For **Pro** plans, click the **Configure Super Bot Fight Mode** link and set each of **Definitely automated** and **Verified bots** features to **Allow**, and toggle the **Static resource protection** and **JavaScript Detections** options to **Off** - For **Business** and **Enterprise** (with no Bot Management add-on) plans, click the **Configure Super Bot Fight Mode** link and set each of **Definitely automated**, **Likely automated** and **Verified bots** features to **Allow**, and toggle the **Static resource protection** and **JavaScript Detections** options to **Off** You cannot bypass or skip Bot Fight Mode using the _Skip_ action in WAF custom rules or using Page Rules. _Skip_, _Bypass_, and _Allow_ actions apply to rules or rulesets running on the [Ruleset Engine](/ruleset-engine/). While Super Bot Fight Mode rules are implemented in the Ruleset Engine, Bot Fight Mode checks are not. This is why you can skip Super Bot Fight Mode, but not Bot Fight Mode. If you need to skip Bot Fight Mode, consider using [Super Bot Fight Mode](/bots/get-started/pro/). Bot Fight Mode can still trigger if you have IP Access rules, but it cannot trigger if an IP Access rule matches the request. For example, the IP Access rule matches the connecting IP. --- ## Super Bot Fight Mode feature (SBFM) is still blocking requests even though the feature is turned off, why? This is a known issue the Bots team is working to resolve in the near future. In the meantime, there is a workaround to resolve such issue. You will need to run the following API command to check and remove the SBFM ruleset: 1. List the existing Rulesets at the zone level. ```bash curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/rulesets" \ --header "Authorization: Bearer " ``` 2. From the output in step 1, find the ruleset ID that is associated with the zone's SBFM configuration. You should be able to see `"kind": "zone"` and `"phase": "http_request_sbfm"` for that ruleset. 3. Use the ruleset ID you found to delete the SBFM ruleset. ```bash curl --request DELETE "https://api.cloudflare.com/client/v4/zones/{zone_id}/rulesets/{ruleset_id}" \ --header "Authorization: Bearer " ``` Note that you need to replace `` with your own [API token](/fundamentals/api/get-started/create-token/). --- # Browser Rendering URL: https://developers.cloudflare.com/browser-rendering/ import { CardGrid, Description, LinkTitleCard, Plan, RelatedProduct, } from "~/components"; Browser automation for [Cloudflare Workers](/workers/). The Workers Browser Rendering API allows developers to programmatically control and interact with a headless browser instance and create automation flows for their applications and products. Once you configure the service, Workers Browser Rendering gives you access to a WebSocket endpoint that speaks the [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). DevTools is what allows Cloudflare to instrument a Chromium instance running in the Cloudflare global network. Use Browser Rendering to: - Take screenshots of pages. - Convert a page to a PDF. - Test web applications. - Gather page load performance metrics. - Crawl web pages for information retrieval. ## Related products Build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale. A globally distributed coordination API with strongly consistent storage. ## More resources Deploy your first Browser Rendering project using Wrangler and Cloudflare's version of Puppeteer. New to Workers? Get started with the Workers Learning Path. Learn about Browser Rendering limits. Connect with the Workers community on Discord to ask questions, show what you are building, and discuss the platform with other developers. Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Workers. --- # Changelog URL: https://developers.cloudflare.com/byoip/changelog/ import { ProductChangelog } from "~/components"; {/* */} --- # Get started URL: https://developers.cloudflare.com/byoip/get-started/ import { GlossaryTooltip } from "~/components" To bring your own IPs, you must work with your account team to understand everything you need to ensure a smooth transition during the onboarding process. :::note BYOIP is ingress only. ::: Cloudflare requires a service-specific configuration for your prefixes, as well as some requirements common to all BYOIP customers regardless of service type. These requirements are common to all products compatible with BYOIP, such as [Magic Transit](/magic-transit/), [Spectrum](/spectrum/), and [CDN services](/cache/). ## Prerequisites There are two major prerequisites before Cloudflare can begin onboarding your IP space. 1. Cloudflare must receive a [Letter of Agency (LOA)](/byoip/concepts/loa/) to announce your prefixes, which we will share with our transit partners as evidence that we are allowed to announce the route. 2. You must verify that your [Internet Routing Registry (IRR)](/byoip/concepts/irr-entries/) records are up to date and contain: - `route` or `route6` objects matching the exact prefixes you want to onboard - `origin` matching the correct ASN you want to onboard :::caution[RPKI validation] You are not required to use Resource Public Key Infrastructure (RPKI). However, if you do, make sure your ROAs are accurate. You can use [Cloudflare's RPKI Portal](https://rpki.cloudflare.com/?view=validator) and a second source such as [Routinator](https://rpki-validator.ripe.net/ui/) to double check your prefixes. ::: After onboarding, [Border Gateway Protocol (BGP)](https://www.cloudflare.com/learning/security/glossary/what-is-bgp/) announcements for customer prefixes can be controlled with the [Dynamic Advertisement](/byoip/concepts/dynamic-advertisement/) API or via the Cloudflare dashboard. ## Cloudflare IPs If you are unable to bring your own IP to Cloudflare, you can use an IP address issued by Cloudflare. Using a Cloudflare IP may be a good option if you: * Have one or a few IPs allocated from home or business class ISPs. * Are an online streamer who could be the target of a DoS attack if your IP is leaked. * Are a business owner with a small number of locations with broadband Internet connections. * Do not own an IP space with a /24 prefix length. * Maintain a large number of locations with a combination of connectivity methods. * Own an IP space with a /24 prefix length but do not advertise prefixes from every location. To protect your network using a Cloudflare IP address, contact your account manager. :::note When you use a Cloudflare-managed IP space, you do not need to provide a Letter of Agency (LOA) and advertise your prefixes that are associated with bringing your own IP. ::: --- # Cloudflare BYOIP URL: https://developers.cloudflare.com/byoip/ import { LinkButton, Plan } from "~/components"; With **Bringing Your Own IPs** (BYOIP), Cloudflare announces your IPs in all our locations. Use your IPs with [Magic Transit](/magic-transit/), [Spectrum](/spectrum/), [CDN services](/cache/), or [Gateway DNS](/cloudflare-one/policies/gateway/dns-policies/). Learn how to [get started](/byoip/get-started/). --- # Glossary URL: https://developers.cloudflare.com/byoip/glossary/ import { Glossary } from "~/components" Review the definitions for terms used across Cloudflare's BYOIP documentation. --- # Route Leak Detection URL: https://developers.cloudflare.com/byoip/route-leak-detection/ import { AvailableNotifications } from "~/components" Route Leak Detection protects your routes on the Internet by notifying you when your traffic is routed somewhere it should not go, which could indicate a possible attack. Route Leak Detection also reduces the amount of time needed to mitigate leaks by providing you with timely notifications. Cloudflare detects route leaks by using several sources of routing data to create a synthesis of how the Internet sees routes to BYOIP users. Cloudflare then watches these views to track any sudden changes that occur on the Internet. If the changes can be correlated to actions Cloudflare has taken, no further action is required. However, if changes have not been made, Cloudflare notifies you to inform you that your routes and users may be at risk. ## Enable Route Leak Detection You must be a user who has brought your own IP address to Cloudflare, which includes Magic Transit, Spectrum, and WAF users. Only prefixes advertised by Cloudflare qualify for Route Leak Detection. 1. Log in to your [Cloudflare dashboard](https://dash.cloudflare.com/) and select your account. 2. Select **Notifications** > **Add**. 3. Locate **Route Leak Detection** from the list > **Select**. 4. Enter a name and description for the notification. 5. Enter one or more email addresses to receive the notifications. 6. Select **Save**. --- # Troubleshooting URL: https://developers.cloudflare.com/byoip/troubleshooting/ import { GlossaryTooltip } from "~/components"; The following topics are useful for troubleshooting BYOIP issues. ## uRPF filtering and packet loss Routers receive IP packets and forward the packets to the destination IP address. Unicast Reverse Path Forwarding (uRPF) is a security feature that can prevent spoofing attacks. uRPF operates under two modes: strict and loose mode. Under **strict mode**, the router performs two checks on incoming packets to look for a matching entry in the source routing table and to determine whether the interface that received the packet can be used to reach the source. If the incoming IP packets pass both checks, the packets are forwarded; if the checks do not pass, the packets are dropped. When uRPF is set to loose mode, the router performs a single check when it receives an IP packet to look for a source's matching entry in the routing table. If you are experiencing packet loss as a result of an upstream ISP implementing uRPF filtering, contact your ISP and request the link be set to **loose mode**. ## Non-SNI support Currently, BYOIP cannot be used with [legacy custom certificates](/ssl/edge-certificates/custom-certificates/uploading/) to support non-SNI requests. Instead, you can use Address Maps to set a default SNI for IPs on your account or zone. Refer to [Setup](/byoip/address-maps/setup/#non-sni-support) for further guidance. --- # Changelog URL: https://developers.cloudflare.com/cache/changelog/ import { ProductChangelog } from "~/components"; {/* */} --- # Get started URL: https://developers.cloudflare.com/cache/get-started/ import { GlossaryTooltip } from "~/components" Cloudflare makes customer websites faster by storing a copy of the website's content on the servers of our globally distributed data centers. Content can be either static or dynamic: static content is “cacheable” or eligible for caching, and dynamic content is “uncacheable” or ineligible for caching. The cached copies of content are stored physically closer to users, optimized to be fast, and do not require recomputing. Cloudflare caches static content based on the following factors: * [Caching levels](/cache/how-to/set-caching-levels/) * [File extension](/cache/concepts/default-cache-behavior/#default-cached-file-extensions) * Presence of [query strings](/cache/advanced-configuration/query-string-sort/) * [Origin cache-control headers](/cache/concepts/cache-control/) * Origin headers that indicate dynamic content * Cache rules that bypass cache on cookie Cloudflare only caches resources within the Cloudflare data center that serve the request. Cloudflare does not cache off-site or third-party resources, such as Facebook or Flickr, or content hosted on [unproxied (grey-clouded)](/dns/manage-dns-records/reference/proxied-dns-records/) DNS records. ## Learn the basics Discover the benefits of caching with Cloudflare's CDN and understand the default cache behavior. * [Understand what is a CDN](https://www.cloudflare.com/learning/cdn/what-is-a-cdn/) * [Understand default cache behavior](/cache/concepts/default-cache-behavior/) * [Understand the default file types Cloudflare caches](/cache/concepts/default-cache-behavior/#default-cached-file-extensions) ## Make more resources cacheable Configure your settings to cache static HTML or cache anonymous page views of dynamic content. * [Customize Caching with Cache Rules](/cache/how-to/cache-rules/) * [Specify which resources to cache](/cache/concepts/customize-cache/) * [Understand Origin Cache Control](/cache/concepts/cache-control/) * [Cache by device type (Enterprise only)](/cache/how-to/cache-rules/examples/cache-device-type/) ## Improve cache hit rates Include or exclude query strings, optimize cache keys, or enable tiered cache to improve hit rates and reduce traffic to your origin. * [Choose a cache level](/cache/how-to/set-caching-levels/) * [Enable Tiered Cache with Argo](/cache/how-to/tiered-cache/#enable-tiered-cache) * [Configure custom cache keys (Enterprise only)](/cache/how-to/cache-keys/) * [Enable Prefetch URLs (Enterprise only)](/speed/optimization/content/prefetch-urls/) ## Secure your cache configuration Control resources a client is allowed to load and set access permissions to allow different origins to access your origin’s resources. Protect your site from web cache deception attacks while still caching static assets. * [Avoid web cache poisoning attacks](/cache/cache-security/avoid-web-poisoning/) * [Configure Cross-Origin Resource Sharing (CORS)](/cache/cache-security/cors/) * [Enable Cache Deception Armor](/cache/cache-security/cache-deception-armor/#enable-cache-deception-armor) ## Cloudflare features that can alter your HTML and cacheable objects To provide Cloudflare services to our customers, we may need to alter your HTML or cached objects to enable the feature or provide optimization. These code alterations only occur on the cacheable objects found at Cloudflare's edge and do not affect the original source. The changes will also be removed if the specific feature is disabled and the cache is purged. Review the list of Cloudflare features that function in this manner: * [Rocket Loader](/speed/optimization/content/rocket-loader/) * [Polish](/images/polish/) * [Mirage](/speed/optimization/images/mirage/) * [Hotlink Protection](/waf/tools/scrape-shield/hotlink-protection/) * [Email address obfuscation](/waf/tools/scrape-shield/email-address-obfuscation/) * [Bot Management JavaScript Detections](/bots/reference/javascript-detections/) ## Troubleshoot Resolve common caching concerns. * [Learn about Cloudflare's cache response statuses](/cache/concepts/cache-responses/) * [Investigate Cloudflare's cache response with cURL](/support/troubleshooting/general-troubleshooting/gathering-information-for-troubleshooting-sites/#troubleshoot-requests-with-curl) * [Diagnose Always Online issues](/cache/troubleshooting/always-online/) --- # Glossary URL: https://developers.cloudflare.com/cache/glossary/ import { Glossary } from "~/components" Review the definitions for terms used across Cloudflare's Cache documentation. --- # Cloudflare Cache URL: https://developers.cloudflare.com/cache/ import { CardGrid, Description, Feature, GlossaryTooltip, LinkTitleCard, Plan, RelatedProduct } from "~/components" Cache content across Cloudflare's global server network. Cache stores copies of frequently accessed content (such as images, videos, or webpages) in geographically distributed data centers that are located closer to end users than origin servers, reducing server load and improving website performance. *** ## Features Learn about default cache behavior, default cached file extensions and cache responses. Configure Cache Rules to optimize your website by specifying which resources should be cached and for how long. Enable Tiered Cache to optimize content delivery by caching frequently accessed content in multiple locations for faster delivery and reduced origin traffic. Use Cloudflare's persistent storage to increase cache times. Instantly purge cached files to force Cloudflare to fetch fresh versions from your web server files. You can purge specific files or all at once. *** ## Related products Cloudflare Load Balancing distributes traffic across your endpoints, reducing endpoint strain and latency and improving the end users experience. A suite of products tailored to your image-processing needs. Cloudflare Workers allows developers to build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale. Cloudflare Rules allows you to make adjustments to requests and responses, configure Cloudflare settings, and trigger specific actions for matching requests. Cloudflare Network Interconnect (CNI) allows you to connect your network infrastructure directly with Cloudflare – rather than using the public Internet – for a more reliable and secure experience. Cloudflare R2 Storage allows developers to store large amounts of unstructured data without the costly egress bandwidth fees associated with typical cloud storage services. Cloudflare Aegis provides dedicated egress IPs (from Cloudflare to your origin) for your layer 7 WAF and CDN services, as well as Spectrum. *** ## More resources Compare available Cloudflare plans Explore pricing options for Cache --- # Plans URL: https://developers.cloudflare.com/cache/plans/ import { ProductFeatures } from "~/components" Cloudflare provides the following features for different [plans](https://www.cloudflare.com/plans/). ## Features --- # Calls vs regular SFUs URL: https://developers.cloudflare.com/calls/calls-vs-sfus/ ## Cloudflare Calls vs. Traditional SFUs Cloudflare Calls represents a paradigm shift in building real-time applications by leveraging a distributed real-time data plane. It creates a seamless experience in real-time communication, transcending traditional geographical limitations and scalability concerns. Calls is designed for developers looking to integrate WebRTC functionalities in a server-client architecture without delving deep into the complexities of regional scaling or server management. ### The Limitations of Centralized SFUs Selective Forwarding Units (SFUs) play a critical role in managing WebRTC connections by selectively forwarding media streams to participants in a video call. However, their centralized nature introduces inherent limitations: * **Regional Dependency:** A centralized SFU requires a specific region for deployment, leading to latency issues for global users except for those in proximity to the selected region. * **Scalability Concerns:** Scaling a centralized SFU to meet global demand can be challenging and inefficient, often requiring additional infrastructure and complexity. ### How is Cloudflare Calls different? Cloudflare Calls addresses these limitations by leveraging Cloudflare's global network infrastructure: * **Global Distribution Without Regions:** Unlike traditional SFUs, Cloudflare Calls operates on a global scale without regional constraints. It utilizes Cloudflare's extensive network of over 250 locations worldwide to ensure low-latency video forwarding, making it fast and efficient for users globally. * **Decentralized Architecture:** There are no dedicated servers for Calls. Every server within Cloudflare's network contributes to handling Calls, ensuring scalability and reliability. This approach mirrors the distributed nature of Cloudflare's products such as 1.1.1.1 DNS or Cloudflare's CDN. ## How Cloudflare Calls Works ### Establishing Peer Connections To initiate a real-time communication session, an end user's client establishes a WebRTC PeerConnection to the nearest Cloudflare location. This connection benefits from anycast routing, optimizing for the lowest possible latency. ### Signaling and Media Stream Management * **HTTPS API for Signaling:** Cloudflare Calls simplifies signaling with a straightforward HTTPS API. This API manages the initiation and coordination of media streams, enabling clients to push new MediaStreamTracks or request these tracks from the server. * **Efficient Media Handling:** Unlike traditional approaches that require multiple connections for different media streams from different clients, Cloudflare Calls maintains a single PeerConnection per client. This streamlined process reduces complexity and improves performance by handling both the push and pull of media through a singular connection. ### Application-Level Management Cloudflare Calls delegates the responsibility of state management and participant tracking to the application layer. Developers are empowered to design their logic for handling events such as participant joins or media stream updates, offering flexibility to create tailored experiences in applications. ## Getting Started with Cloudflare Calls Integrating Cloudflare Calls into your application promises a straightforward and efficient process, removing the hurdles of regional scalability and server management so you can focus on creating engaging real-time experiences for users worldwide. --- # Changelog URL: https://developers.cloudflare.com/calls/changelog/ import { ProductChangelog } from "~/components"; {/* */} --- # DataChannels URL: https://developers.cloudflare.com/calls/datachannels/ Since Cloudflare Calls is basically a pub/sub server for WebRTC that can scale up to many subscribers per publisher, it's fit for arbitrary data besides media too. ## Example An example of DataChannels in action can be found in the [Calls Examples github repo](https://github.com/cloudflare/calls-examples/tree/main/echo-datachannels). --- # Demos URL: https://developers.cloudflare.com/calls/demos/ import { ExternalResources, GlossaryTooltip } from "~/components" Learn how you can use Calls within your existing architecture. ## Demos Explore the following demo applications for Calls. --- # Example architecture URL: https://developers.cloudflare.com/calls/example-architecture/
![Example Architecture](~/assets/images/calls/video-calling-application.png)
1. Clients connect to the backend service 2. Backend service manages the relationship between the clients and the tracks they should subscribe to 3. Backend service contacts the Cloudflare Calls API to pass the SDP from the clients to establish the WebRTC connection. 4. Calls API relays back the Calls API SDP reply and renegotiation messages. 5. If desired, headless clients can be used to record the content from other clients or publish content. 6. Admin manages the rooms and room members. --- # Quickstart guide URL: https://developers.cloudflare.com/calls/get-started/ :::note[Before you get started:] You must first [create a Cloudflare account](/fundamentals/setup/account/create-account/). ::: ## Create your first app Every Calls App is a separate environment, so you can make one for development, staging and production versions for your product. Either using [Dashboard](https://dash.cloudflare.com/?to=/:account/calls), or the [API](/api/resources/calls/subresources/sfu/methods/create/) create a Calls App. When you create a Calls App, you will get: * App ID * App Secret These two combined will allow you to make API Calls from your backend server to Calls. --- # Connection API URL: https://developers.cloudflare.com/calls/https-api/ Cloudflare Calls simplifies the management of peer connections and media tracks through HTTPS API endpoints. These endpoints allow developers to efficiently manage sessions, add or remove tracks, and gather session information. ## API Endpoints * **Create a New Session**: Initiates a new session on Cloudflare Calls, which can be modified with other endpoints below. * `POST /apps/{appId}/sessions/new` * **Add a New Track**: Adds a media track (audio or video) to an existing session. * `POST /apps/{appId}/sessions/{sessionId}/tracks/new` * **Renegotiate a Session**: Updates the session's negotiation state to accommodate new tracks or changes in the existing ones. * `PUT /apps/{appId}/sessions/{sessionId}/renegotiate` * **Close a Track**: Removes a specified track from the session. * `PUT /apps/{appId}/sessions/{sessionId}/tracks/close` * **Retrieve Session Information**: Fetches detailed information about a specific session. * `GET /apps/{appId}/sessions/{sessionId}` [View full API and schema (OpenAPI format)](/calls/static/calls-api-2024-05-21.yaml) ## Handling Secrets It is vital to manage App ID and its secret securely. While track and session IDs can be public, they should be protected to prevent misuse. An attacker could exploit these IDs to disrupt service if your backend server does not authenticate request origins properly, for example by sending requests to close tracks on sessions other than their own. Ensuring the security and authenticity of requests to your backend server is crucial for maintaining the integrity of your application. ## Using STUN and TURN Servers Cloudflare Calls is designed to operate efficiently without the need for TURN servers in most scenarios, as Cloudflare exposes a publicly routable IP address for Calls. However, integrating a STUN server can be necessary for facilitating peer discovery and connectivity. * **Cloudflare STUN Server**: `stun.cloudflare.com:3478` Utilizing Cloudflare's STUN server can help the connection process for Calls applications. ## Lifecycle of a Simple Session This section provides an overview of the typical lifecycle of a simple session, focusing on audio-only applications. It illustrates how clients are notified by the backend server as new remote clients join or leave, incorporating video would introduce additional tracks and considerations into the session.
![Example Lifecycle](~/assets/images/calls/lifecycle-of-a-session.png)
There is also a previously used, but now deprecated way to use the API illustrated below. If you are using this style please consider upgrading to the newer version illustrated above.
![Deprecated Lifecycle](~/assets/images/calls/deprecated-lifecycle-of-a-session.png)
--- # Overview URL: https://developers.cloudflare.com/calls/ import { Description, LinkButton } from "~/components" Build real-time serverless video, audio and data applications. Cloudflare Calls is infrastructure for real-time audio/video/data applications. It allows you to build real-time apps without worrying about scaling or regions. It can act as a selective forwarding unit (WebRTC SFU), as a fanout delivery system for broadcasting (WebRTC CDN) or anything in between. Cloudflare Calls runs on [Cloudflare's global cloud network](https://www.cloudflare.com/network/) in hundreds of cities worldwide. Get started Calls dashboard Orange Meets demo app --- # Introduction URL: https://developers.cloudflare.com/calls/introduction/ Cloudflare Calls can be used to add realtime audio, video and data into your applications. Cloudflare Calls uses WebRTC, which is the lowest latency way to communicate across a broad range of platforms like browsers, mobile and native apps. Calls integrates with your backend and frontend application to add realtime functionality. ## Why Cloudflare Calls exists * **It's difficult to scale WebRTC**: Many struggle scaling WebRTC servers. Operators run into issues about how many users can be in the same "room" or want to build unique solutions that don't fit into the current concepts in high level APIs. * **High egress costs**: WebRTC is expensive to use as managed solutions charge a high premium on cloud egress and running your own servers incur system administration and scaling overhead. Cloudflare already has 300+ locations with upwards of 1,000 servers in some locations. Cloudflare Calls scales easily on top of this architecture and can offer the lowest WebRTC usage costs. * **WebRTC is growing**: Developers are realizing that WebRTC is not just for video conferencing. WebRTC is supported on many platforms, it mature and well understood. ## What makes Cloudflare Calls unique * \**Unopinionated*: Cloudflare Calls does not offer a SDK. It instead allows you to access raw WebRTC to solve unique problems that might not fit into existing concepts. The API is deliberately simple. * **No rooms**: Unlike other WebRTC products, Cloudflare Calls lets you be in charge of each track (audio/video/data) instead of offering abstractions such as rooms. You define the presence protocol on top of simple pub/sub. Each end user can publish and subscribe to audio/video/data tracks as they wish. * **No lock-in**: You can use Cloudflare Calls to solve scalability issues with your SFU. You can use in combination with peer-to-peer architecture. You can use Cloudflare Calls standalone. To what extent you use Cloudflare Calls is up to you. ## What exactly does Cloudflare Calls do? * **SFU**: Calls is a special kind of pub/sub server that is good at forwarding media data to clients that subscribe to certain data. Each client connects to Cloudflare Calls via WebRTC and either sends data, receives data or both using WebRTC. This can be audio/video tracks or DataChannels. * **It scales**: All Cloudflare servers act as a single server so millions of WebRTC clients can connect to Cloudflare Calls. Each can send data, receive data or both with other clients. ## How most developers get started 1. Get started with the echo example, which you can download from the Cloudflare dashboard when you create a Calls App or from [demos](/calls/demos/). This will show you how to send and receive audio and video. 2. Understand how you can manipulate who can receive what media by passing around session and track ids. Remember, you control who receives what media. Each media track is represented by a unique ID. It's your responsibility to save and distribute this ID. :::note[Calls is not a presence protocol] Calls does not know what a room is. It only knows media tracks. It's up to you to make a room by saving who is in a room along with track IDs that unique identify media tracks. If each participant publishes their audio/video, and receives audio/video from each other, you've got yourself a video conference! ::: 3. Create an app where you manage each connection to Cloudflare Calls and the track IDs created by each connection. You can use any tool to save and share tracks. Check out the example apps at [demos](/calls/demos/), such as [Orange Meets](https://github.com/cloudflare/orange), which is a full-fledged video conferencing app that uses [Workers Durable Objects](/durable-objects/) to keep track of track IDs. --- # Limits, timeouts and quotas URL: https://developers.cloudflare.com/calls/limits/ Understanding the limits and timeouts of Cloudflare Calls is crucial for optimizing the performance and reliability of your applications. This section outlines the key constraints and behaviors you should be aware of when integrating Cloudflare Calls into your app. ## Free * Each account gets 1,000GB/month of data transfer from Cloudflare to your client for free. * Data transfer from your client to Cloudflare is always free of charge. ## Limits * **API Calls per Session**: You can make up to 50 API calls per second for each session. There is no ratelimit on a App basis, just sessions. * **Tracks per API Call**: Up to 64 tracks can be added with a single API call. If you need to add more tracks to a session, you should distribute them across multiple API calls. * **Tracks per Session**: There's no upper limit to the number of tracks a session can contain, the practical limit is governed by your connection's bandwidth to and from Cloudflare. ## Inactivity Timeout * **Track Timeout**: Tracks will automatically timeout and be garbage collected after 30 seconds of inactivity, where inactivity is defined as no media packets being received by Cloudflare. This mechanism ensures efficient use of resources and session cleanliness across all Sessions that use a track. ## PeerConnection Requirements * **Session State**: For any operation on a session (e.g., pulling or pushing tracks), the PeerConnection state must be `connected`. Operations will block for up to 5 seconds awaiting this state before timing out. This ensures that only active and viable sessions are engaged in media transmission. ## Handling Connectivity Issues * **Internet Connectivity Considerations**: The potential for internet connectivity loss between the client and Cloudflare is an operational reality that must be addressed. Implementing a detection and reconnection strategy is recommended to maintain session continuity. This could involve periodic 'heartbeat' signals to your backend server to monitor connectivity status. Upon detecting connectivity issues, automatically attempting to reconnect and establish a new session is advised. Sessions and tracks will remain available for reuse for 30 seconds before timing out, providing a brief window for reconnection attempts. Adhering to these limits and understanding the timeout behaviors will help ensure that your applications remain responsive and stable while providing a seamless user experience. --- # Pricing URL: https://developers.cloudflare.com/calls/pricing/ Cloudflare Calls billing is based on data sent from Cloudflare edge to your application. Cloudflare Calls SFU and TURN services cost $0.05 per GB of data egress. There is a free tier of 1,000 GB before any charges start. This free tier includes usage from both SFU and TURN services, not two independent free tiers. Cloudflare Calls billing appears as a single line item on your Cloudflare bill, covering both SFU and TURN. Traffic between Cloudflare Calls TURN and Cloudflare Calls SFU or Cloudflare Stream (WHIP/WHEP) does not get double charged, so if you are using both SFU and TURN at the same time, you will get charged for only one. ### TURN Please see the [TURN FAQ page](/calls/turn/faq), where there is additional information on speficially which traffic path from RFC8656 is measured and counts towards billing. ### SFU Only traffic originating from Cloudflare towards clients incurs charges. Traffic pushed to Cloudflare incurs no charge even if there is no client pulling same traffic from Cloudflare. --- # Sessions and Tracks URL: https://developers.cloudflare.com/calls/sessions-tracks/ Cloudflare Calls offers a simple yet powerful framework for building real-time experiences. At the core of this system are three key concepts: **Applications**, **Sessions** and **Tracks**. Familiarizing yourself with these concepts is crucial for using Calls. ## Application A Calls Application is an environment within different Sessions and Tracks can interact. Examples of this could be production, staging or different environments where you'd want separation between Sessions and Tracks. Cloudflare Calls usage can be queried at Application, Session or Track level. ## Sessions A **Session** in Cloudflare Calls correlates directly to a WebRTC PeerConnection. It represents the establishment of a communication channel between a client and the nearest Cloudflare data center, as determined by Cloudflare's anycast routing. Typically, a client will maintain a single Session, encompassing all communications between the client and Cloudflare. * **One-to-One Mapping with PeerConnection**: Each Session is a direct representation of a WebRTC PeerConnection, facilitating real-time media data transfer. * **Anycast Routing**: The client connects to the closest Cloudflare data center, optimizing latency and performance. * **Unified Communication Channel**: A single Session can handle all types of communication between a client and Cloudflare, ensuring streamlined data flow. ## Tracks Within a Session, there can be one or more **Tracks**. * **Tracks map to MediaStreamTrack**: Tracks align with the MediaStreamTrack concept, facilitating audio, video, or data transmission. * **Globally Unique Ids**: When you push a track to Cloudflare, it is assigned a unique ID, which can then be used to pull the track into another session elsewhere. * **Available globally**: The ability to push and pull tracks is central to what makes Calls a versatile tool for real-time applications. Each track is available globally to be retrieved from any Session within an App. ## Calls as a Programmable "Switchboard" The analogy of a switchboard is apt for understanding Calls. Historically, switchboard operators connected calls by manually plugging in jacks. Similarly, Calls allows for the dynamic routing of media streams, acting as a programmable switchboard for modern real-time communication. ## Beyond "Rooms", "Users", and "Participants" While many SFUs utilize concepts like "rooms" to manage media streams among users, this approach has scalability and flexibility limitations. Cloudflare Calls opts for a more granular and flexible model with Sessions and Tracks, enabling a wide range of use cases: * Large-scale remote events, like 'fireside chats' with thousands of participants. * Interactive conversations with the ability to bring audience members "on stage." * Educational applications where an instructor can present to multiple virtual classrooms simultaneously. ### Presence Protocol vs. Media Flow Calls distinguishes between the presence protocol and media flow, allowing for scalability and flexibility in real-time applications. This separation enables developers to craft tailored experiences, from intimate calls to massive, low-latency broadcasts. --- # FAQ URL: https://developers.cloudflare.com/china-network/faq/ ## Requirements ### What are the requirements to enable the Cloudflare China Network service from Cloudflare? Refer to [Get started](/china-network/get-started/) for more information. ### Can I use my current account to access the Cloudflare China Network service or do I need a separate account? Yes, you can use your current Cloudflare account and dashboard. ### What are the requirements for requesting a Cloudflare China Network PoC? Cloudflare requires that you have a valid [ICP (Internet Content Provider)](/china-network/concepts/icp/) number and content vetting approval from JD Cloud to provide you with a Cloudflare China Network PoC (proof of concept). If you are interested in a PoC, contact your sales team. ## Data storage ### Will my Cloudflare account or configuration information be stored in China? Cloudflare has taken numerous steps to ensure your security and the integrity of your data in China. Your identification information such as email addresses, password hashes, and billing information are never stored on the Cloudflare China Network or shared with the Cloudflare partner except for Zone configuration information and bindings with Cloudflare’s Developer Suite which are stored on the China Network operated by our partners in China upon your enabling the China Service for a particular Zone. ## Licensing and onboarding ### Does Cloudflare have an MIIT license to provide CDN services in China? As a US company, Cloudflare does not have a license from China's Ministry of Industry and Information Technology (MIIT). However, Cloudflare's partner JD Cloud has all the licenses required by the MIIT to operate and provide CDN services in China. ### Can Cloudflare or JD Cloud help me to get the ICP? No, neither Cloudflare nor JD Cloud is responsible for [ICP (Internet Content Provider)](/china-network/concepts/icp/) applications. Cloudflare recommends you to reach out to local agents specialized in ICP applications. For more information, refer to [Obtain an ICP number](/china-network/concepts/icp/#obtain-an-icp-number). ### Why is my ICP filing/license revoked? The application and revocation of ICP filings or licenses is managed by China's local authorities. Usually either the customer or the agency processing the ICP application receive a notification with more details. Cloudflare cannot provide the ICP revocation reasons. ### What would happen if my ICP filing/license got revoked? Cloudflare's partner JD Cloud and the local authorities continuously track the status of the ICP. If your ICP gets revoked, JD Cloud may terminate or suspend your access to the China Service at any time and without liability, in accordance with China local regulations. To mitigate the impact on your Internet properties, Cloudflare would reroute the traffic for the affected domains to the nearest data centers outside of China. ### What is content vetting and why do I need JD Cloud to vet my domain's content before onboarding? The JD Cloud network is proxying content inside of China for customers who have purchased the Cloudflare China Network subscription. To ensure compliance with China’s regulation on Internet information services and with [JD Cloud's service terms](https://docs.jdcloud.com/cn/product-service-agreement/starshield-terms-of-service), JD Cloud must review the content of all the domains before onboarding those domains to their network. They can approve or reject any domain based on the nature of its content. For more information, contact your sales team. ## Technical questions ### How does IPv6 work on the Cloudflare China Network? All sites hosted in mainland China must have IPv6 enabled. The Cloudflare China Network feature automatically enables IPv6 for domains to fulfill this requirement and it is not possible to disable it. According to Cloudflare's tests, IPv6 connections in mainland China are more reliable and offer better latency. ## Other services ### Can Cloudflare provide a private line for cross-border traffic? No. Cloudflare is not licensed to provide such cross-border private line service. --- # Get started URL: https://developers.cloudflare.com/china-network/get-started/ ## 1. Contract required services and agree to supplemental terms 1. Ensure that you have a Cloudflare Enterprise plan. If you do not have an Enterprise plan yet, you must upgrade. 2. Add the Cloudflare China Network package (a separate subscription) to your Enterprise plan. 3. Agree to the [China Service Supplemental Terms](https://www.cloudflare.com/supplemental-terms/#china-service). Contact your sales team for more information on these steps. ## 2. Obtain ICP and vet domain content 1. [Obtain Internet Content Provider (ICP) filings or licenses](/china-network/concepts/icp/#obtain-an-icp-number) for all the apex domains you wish to onboard. 2. Present valid ICP filings or licenses for the zones you are onboarding. 3. Ensure that your websites [display their ICP number in the page footer](/china-network/concepts/icp/#display-your-icp-number). 4. Prepare the required information for JD Cloud to review the content on your domains. JD Cloud, a Cloudflare partner, is required to review and vet the content of all domains on their network before enabling them. You will need to provide the following information: - Customer and company name. - Domain name. - ICP license/filing number. - A general description of the content of each domain (for example, `Marketing website`). - A signed Self Attestation letter (provided by your sales team). ## 3. Onboard your domains to the Cloudflare China Network After content vetting is complete, [add your domains to Cloudflare](/fundamentals/setup/manage-domains/add-site/). It will take a minimum of 24 hours to enable user traffic (that is, until DNS starts answering with JD Cloud's network IP addresses). --- # Cloudflare China Network URL: https://developers.cloudflare.com/china-network/ import { Stream } from "~/components" The [Cloudflare China Network](https://www.cloudflare.com/china-network/) is a package of selected Cloudflare's performance and security products running on data centers located in mainland China and operated by Cloudflare's partner JD Cloud. The data centers cover most populated regions in China. Combining Cloudflare's technological leadership and JD Cloud's local operations expertise, the Cloudflare China Network is designed to meet the needs for secure, reliable, and fast-performing content delivery in China. You can use the same configurations that you use with Cloudflare everywhere else in the world and with the same dashboard experience. ## Main features The Cloudflare China Network provides: - A single solution for both performance improvement and security services such as [WAF](/waf/), [DDoS](/ddos-protection/), and [bot management](/bots/). - An unified experience for managing network traffic and security posture. You can manage all configurations on the same dashboard. - The same customer support capabilities as Cloudflare's global network. You may also have access to premium service and local language support. - [In-China Authoritative DNS and in-China nameservers](/china-network/concepts/china-dns/) to improve the Time to First Byte (TTFB) performance. - [China Express](/china-network/concepts/china-express) is a suite of connectivity, performance offerings and professional services designed to simplify your global assets' deployment in China. ### Video Introduction ## Availability The Cloudflare China Network is available as a separate subscription for customers on an [Enterprise plan](https://www.cloudflare.com/plans/enterprise/). ## Important notes - Not all Cloudflare products are available in the Cloudflare China Network. Refer to [Available products and features](/china-network/reference/available-products/) for details. - IPv6 support is mandatory for all Internet entities operating in mainland China. The Cloudflare China Network feature automatically enables IPv6 for domains to fulfill this requirement. - All the content inside of mainland China is monitored by local authorities and has to comply with local regulations. - You must have a valid [ICP (Internet Content Provider) filing or license](/china-network/concepts/icp/) for each apex domain you wish to onboard to Cloudflare. --- # Get started URL: https://developers.cloudflare.com/client-ip-geolocation/get-started/ :::note Client IP Geolocation is currently in closed Beta testing. ::: There are several things you can do to best handle traffic from Cloudflare VPN and forward-proxy users: * **Origin operators**: * Do not block IP addresses associated with our VPN and proxy products (see the [About section](/client-ip-geolocation/about/) for more details) * To get even more accurate geolocation data, ensure your origin is [reachable via IPv6](/client-ip-geolocation/faq/) * **Geolocation data providers**: * Regularly pull updated geolocation data from the [Cloudflare API](https://api.cloudflare.com/local-ip-ranges.csv) * **Users of WARP and 1.1.1.1**: * Review the [FAQs](/client-ip-geolocation/faq/#cloudflare-vpn-users) and [About section](/client-ip-geolocation/about/) to learn exactly how, how much, and why we share geolocation data --- # Overview URL: https://developers.cloudflare.com/client-ip-geolocation/ import { LinkButton } from "~/components" :::note Client IP Geolocation is currently in closed Beta testing. ::: Cloudflare designed [Cloudflare WARP](/warp-client/) and [1.1.1.1](/1.1.1.1/) to make Internet browsing more private and secure. These applications encrypt last-mile connections and make it more difficult for others to use client IP addresses in user fingerprinting. However, unlike legacy VPN applications, we never designed WARP or 1.1.1.1 to hide user locations or allow users to misrepresent their true geographic location. As a web property operator, you can use **Client IP Geolocation** to map Cloudflare egress IP addresses to specific geolocations. Get started Learn more :::note Client IP Geolocation is different from the [Cloudflare IP Geolocation setting](/network/ip-geolocation/), which helps you capture country codes for visitors. ::: --- # Cloudflare for Platforms URL: https://developers.cloudflare.com/cloudflare-for-platforms/ import { Description, Feature } from "~/components" Cloudflare's offering for SaaS businesses. Extend Cloudflare's security, reliability, and performance services to your customers with Cloudflare for Platforms. Together with Cloudflare for SaaS and Workers for Platforms, your customers can build custom logic to meet their needs right into your application. *** ## Products Cloudflare for SaaS allows you to extend the security and performance benefits of Cloudflare’s network to your customers via their own custom or vanity domains. Workers for Platforms help you deploy serverless functions programmatically on behalf of your customers. --- # Account limits URL: https://developers.cloudflare.com/cloudflare-one/account-limits/ This page lists the default account limits for rules, applications, fields, and other features. These limits may be increased on Enterprise accounts. To request a limit increase, contact your account team. ## Access | Feature | Limit | | --------------------------- | ----- | | Applications count | 500 | | Audit Logpush jobs | 5 | | Email addresses per rule | 1,000 | | Group count | 300 | | Group size | 1,000 | | IP addresses per rule | 1,000 | | mTLS root certificates | 50 | | Service tokens count | 50 | | IdP count | 50 | | Rules count per application | 1,000 | | Rules count per group | 1,000 | | Domains per application | 5 | | Infrastructure targets | 300 | ## Gateway | Feature | Limit | | ----------------------------------------- | ----- | | DNS policies per account | 500 | | Network policies per account | 500 | | HTTP policies per account | 500 | | Egress policies per account | 500 | | Resolver policies per account | 500 | | DNS locations | 250 | | Concurrent streams for HTTP/2 connections | 256 | | Proxy endpoints | 500 | | Source IP CIDRs per proxy endpoint | 2,000 | | Lists | 100 | | Entries per list (Standard users) | 1,000 | | Entries per list (Enterprise users) | 5,000 | | DNS Logpush jobs | 5 | | HTTP Logpush jobs | 5 | ## Data Loss Prevention (DLP) | Feature | Limit | | ---------------------------------------- | --------- | | Custom entries | 25 | | Exact Data Match cells per spreadsheet | 100,000 | | Custom Wordlist keywords per spreadsheet | 200 | | Custom Wordlist keywords per account | 1,000 | | Dataset cells per account | 1,000,000 | ## Cloudflare Tunnel | Feature | Limit | | ---------------------------------------- | ----- | | Tunnels per account | 1,000 | | IP routes per account | 1,000 | | Active `cloudflared` replicas per tunnel | 25 | ## Digital Experience Monitoring | Feature | Limit | | --------------------------------------------- | ----- | | Tests per account | 10 | | Remote captures per day (Free users) | 100 | | Remote captures per day (Pay-as-you-go users) | 200 | | Remote captures per day (Enterprise users) | 800 | ## Certificates | Feature | Limit | | ------------------------------ | ----- | | Active certificates | 10 | | Certificates generated per day | 3 | | Custom certificates | 5 | ## Maximum number of characters | Feature | Character limit | | ----------------------------- | --------------- | | Application name | 350 | | Group name | 350 | | mTLS certificates name | 350 | | Service token name | 350 | | IdP name | 350 | | Target name | 255 | | Application URL | 63 | | Team domain | 63 | | Gateway API policy expression | 140,000 | --- # Glossary URL: https://developers.cloudflare.com/cloudflare-one/glossary/ import { Glossary } from "~/components" Review definitions for Cloudflare Zero Trust terms. --- # Overview URL: https://developers.cloudflare.com/cloudflare-one/ import { GlossaryTooltip, Render } from "~/components"; Cloudflare Zero Trust replaces legacy security perimeters with Cloudflare's global network, making the Internet faster and safer for teams around the world. Refer to our [reference architecture](/reference-architecture/architectures/sase/) to learn how to evolve your network and security architecture to our SASE platform. **Zero Trust access for all of your applications.** - Authenticate users on our global network - Onboard third-party users seamlessly - Log every event and request **A Secure Web Gateway to protect users and devices.** - Enforce your company's Acceptable Use Policy (AUP) - Block risky sites with custom blocklists and built-in threat intel - Enhance visibility and protection into SaaS applications **A fast and reliable solution for remote browsing.** - Execute all browser code in the cloud - Mitigate the impact of attacks - Seamless, lightning-fast end user experience **A Cloud Access Security Broker to safeguard data in the cloud.** - Protect users and sensitive data at rest in SaaS applications - Detect insider threats and unsanctioned application usage, also known as shadow IT - Ensure best practices to prevent data leaks and compliance violations **A Data Loss Prevention solution to safeguard data in transit.** - Detect sensitive data as it moves to and from SaaS applications - Predefined DLP Profiles to quickly get started - Log or block DLP matches **An Email Security solution to protect your email inbox.** - Configure policies to manage your inbox. - Automatically move emails based on a certain disposition. - Use screen criteria to investigate your email. ![Illustrated laptop with a login screen with a data stream flowing to a cloud server.](~/assets/images/cloudflare-one/teams-no-background.png) --- # Roles and permissions URL: https://developers.cloudflare.com/cloudflare-one/roles-permissions/ When creating a Cloudflare Zero Trust account, you will be given the Super Administrator role. As a Super Administrator, you can invite members to join your Zero Trust account and assign them different roles. There is no limit to the number of members which can be added to a given account. Any members with the proper permissions will be able to make configuration changes while actively logged into Zero Trust (unless [read-only mode](/cloudflare-one/api-terraform/#set-dashboard-to-read-only) is enabled). To check the list of members in your account, or to manage roles and permissions, refer to our [Account setup](/fundamentals/setup/manage-members/) documentation. ## Zero Trust roles Only Super Administrators will be able to assign or remove the following roles from users in their account. Scroll to the right to see a full list of permissions for each role. | | Access Read | Access Edit | Gateway Read | Gateway Edit | Gateway Report | Billing Read | Billing Edit | | ------------------------------- | ----------- | ----------- | ------------ | ------------ | -------------- | ------------ | ------------ | | Super Administrator | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Cloudflare Zero Trust | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | Cloudflare Access | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | | Cloudflare Gateway | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | | Cloudflare Zero Trust Read Only | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ❌ | | Cloudflare Zero Trust Reporting | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | :::note The Cloudflare Zero Trust role grants administrator access to all Zero Trust products including Access, Gateway, WARP, Tunnel, Browser Isolation, CASB, DLP, DEX, and Email Security. ::: ### Cloudflare Zero Trust PII By default, only Super Administrators can view end users' PII in the Gateway activity logs, such as Device IDs, Source IPs, or user emails. No other roles will have the ability to read PII unless Super Administrators explicitly assign the **Cloudflare Zero Trust PII** role to them. The Cloudflare Zero Trust PII role should be considered an add-on role, to be combined with any role from the table above. For example, Super Administrators may decide to assign the Cloudflare Gateway role to a user, and add the Cloudflare Zero Trust PII role to allow that user to access PII in the Gateway logs. :::note The Cloudflare Zero Trust PII role does not apply to Access audit logs. PII is always visible in Access logs. ::: --- # Overview URL: https://developers.cloudflare.com/constellation/ import { CardGrid, Description, LinkTitleCard } from "~/components" Run machine learning models with Cloudflare Workers. Constellation allows you to run fast, low-latency inference tasks on pre-trained machine learning models natively on Cloudflare Workers. It supports some of the most popular machine learning (ML) and AI runtimes and multiple classes of models. Cloudflare provides a curated list of verified models, or you can train and upload your own. Functionality you can deploy to your application with Constellation: * Content generation, summarization, or similarity analysis * Question answering * Audio transcription * Image or audio classification * Object detection * Anomaly detection * Sentiment analysis *** ## More resources Connect with the Workers community on Discord to ask questions, show what you are building, and discuss the platform with other developers. Follow @CloudflareDev on Twitter to learn about product announcements, and what is new in Cloudflare Workers. --- # Get started URL: https://developers.cloudflare.com/cloudflare-one/setup/ import { Render } from "~/components"; This guide covers the recommended steps to start securing your users and devices with Cloudflare Zero Trust. :::note To get started with a specific use case, refer to our [implementation guides](/cloudflare-one/implementation-guides/). ::: ## Prerequisites Sign up for a [Cloudflare account](https://dash.cloudflare.com/sign-up). ## Create a Zero Trust organization Welcome to Cloudflare Zero Trust! You can now explore a list of one-click actions we have designed to help you kickstart your Zero Trust experience. ## Install the WARP client on your devices If you want to enable security features such as Browser Isolation, HTTP filtering, AV scanning, and device posture, or connect networks to Cloudflare, here are the next steps you need to take: 1. **Set up a login method.** Configure [One-time PIN](/cloudflare-one/identity/one-time-pin/) or connect a [third-party identity provider](/cloudflare-one/identity/idp-integration/) in Zero Trust. This is the login method your users will utilize when authenticating to add a new device to your Zero Trust setup. 2. **Next, define [device enrollment permissions](/cloudflare-one/connections/connect-devices/warp/deployment/device-enrollment/)**. Create device enrollment rules to define which users in your organization should be able to connect devices to your organization's Zero Trust setup. As you create your rule, you will be asked to select which login method you would like users to authenticate with. 3. **Install the [Cloudflare root certificate](/cloudflare-one/connections/connect-devices/user-side-certificates/) on your devices.** Advanced security features including HTTP traffic inspection require users to install and trust the Cloudflare root certificate on their machine or device. If you are installing certificates manually on all your devices, these steps will need to be performed on each new device that is to be subject to HTTP filtering. 4. **Download and deploy the WARP client to your devices**. Choose one of the [different ways](/cloudflare-one/connections/connect-devices/warp/deployment/) to deploy the WARP client, depending on what works best for your organization. 5. **Log in to your organization's Cloudflare Zero Trust instance from your devices**. On your device, go to the Settings section in the WARP client and insert your organization's team name. Your devices are now connected to Cloudflare Zero Trust through the WARP client. You can go to **My Team** > **Devices** to find a list of your enrolled devices, when they were last seen, and the WARP client version they are running. Next, [enforce security policies](/cloudflare-one/policies/) on your traffic and access requests. --- # Demos and architectures URL: https://developers.cloudflare.com/d1/demos/ import { ExternalResources, GlossaryTooltip, ResourcesBySelector } from "~/components" Learn how you can use D1 within your existing application and architecture. ## Demos Explore the following demo applications for D1. ## Reference architectures Explore the following reference architectures that use D1: --- # Get started URL: https://developers.cloudflare.com/d1/get-started/ import { Render, PackageManagers, Steps, FileTree, Tabs, TabItem, TypeScriptExample, WranglerConfig } from "~/components"; This guide instructs you through: - Creating your first database using D1, Cloudflare's native serverless SQL database. - Creating a schema and querying your database via the command-line. - Connecting a [Cloudflare Worker](/workers/) to your D1 database to query your D1 database programmatically. You can perform these tasks through the CLI or through the Cloudflare dashboard. :::note If you already have an existing Worker and an existing D1 database, follow this tutorial from [3. Bind your Worker to your D1 database](/d1/get-started/#3-bind-your-worker-to-your-d1-database). ::: ## Prerequisites ## 1. Create a Worker Create a new Worker as the means to query your database. 1. Create a new project named `d1-tutorial` by running: This creates a new `d1-tutorial` directory as illustrated below. - d1-tutorial - node_modules/ - test/ - src - **index.ts** - package-lock.json - package.json - testconfig.json - vitest.config.mts - worker-configuration.d.ts - **wrangler.json** Your new `d1-tutorial` directory includes: - A `"Hello World"` [Worker](/workers/get-started/guide/#3-write-code) in `index.ts`. - A [`wrangler.toml / wrangler.json` file](/workers/wrangler/configuration/). This file is how your `d1-tutorial` Worker accesses your D1 database. :::note If you are familiar with Cloudflare Workers, or initializing projects in a Continuous Integration (CI) environment, initialize a new project non-interactively by setting `CI=true` as an environmental variable when running `create cloudflare@latest`. For example: `CI=true npm create cloudflare@latest d1-tutorial --type=simple --git --ts --deploy=false` creates a basic "Hello World" project ready to build on. ::: 1. Log in to your [Cloudflare dashboard](https://dash.cloudflare.com/) and select your account. 2. Go to your account > **Workers & Pages** > **Overview**. 3. Select **Create**. 4. Select **Create Worker**. 5. Name your Worker. For this tutorial, name your Worker `d1-tutorial`. 6. Select **Deploy**. ## 2. Create a database A D1 database is conceptually similar to many other databases: a database may contain one or more tables, the ability to query those tables, and optional indexes. D1 uses the familiar [SQL query language](https://www.sqlite.org/lang.html) (as used by SQLite). To create your first D1 database: 1. Change into the directory you just created for your Workers project: ```sh cd d1-tutorial ``` 2. Run the following `wrangler d1` command and give your database a name. In this tutorial, the database is named `prod-d1-tutorial`: ```sh npx wrangler d1 create prod-d1-tutorial ``` ```sh output ✅ Successfully created DB 'prod-d1-tutorial' [[d1_databases]] binding = "DB" # available in your Worker on env.DB database_name = "prod-d1-tutorial" database_id = "" ``` This creates a new D1 database and outputs the [binding](/workers/runtime-apis/bindings/) configuration needed in the next step. :::note The `wrangler` command-line interface is Cloudflare's tool for managing and deploying Workers applications and D1 databases in your terminal. It was installed when you used `npm create cloudflare@latest` to initialize your new project. ::: 1. Go to **Storage & Databases** > **D1**. 2. Select **Create**. 3. Name your database. For this tutorial, name your D1 database `prod-d1-tutorial`. 4. (Optional) Provide a location hint. Location hint is an optional parameter you can provide to indicate your desired geographical location for your database. Refer to [Provide a location hint](/d1/configuration/data-location/#provide-a-location-hint) for more information. 5. Select **Create**. :::note For reference, a good database name: - Uses a combination of ASCII characters, shorter than 32 characters, and uses dashes (-) instead of spaces. - Is descriptive of the use-case and environment. For example, "staging-db-web" or "production-db-backend". - Only describes the database, and is not directly referenced in code. ::: ## 3. Bind your Worker to your D1 database You must create a binding for your Worker to connect to your D1 database. [Bindings](/workers/runtime-apis/bindings/) allow your Workers to access resources, like D1, on the Cloudflare developer platform. To bind your D1 database to your Worker: You create bindings by updating your Wrangler file. 1. Copy the lines obtained from [step 2](/d1/get-started/#2-create-a-database) from your terminal. 2. Add them to the end of your Wrangler file. ```toml [[d1_databases]] binding = "DB" # available in your Worker on env.DB database_name = "prod-d1-tutorial" database_id = "" ``` Specifically: - The value (string) you set for `binding` is the **binding name**, and is used to reference this database in your Worker. In this tutorial, name your binding `DB`. - The binding name must be [a valid JavaScript variable name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables). For example, `binding = "MY_DB"` or `binding = "productionDB"` would both be valid names for the binding. - Your binding is available in your Worker at `env.` and the D1 [Workers Binding API](/d1/worker-api/) is exposed on this binding. :::note When you execute the `wrangler d1 create` command, the client API package (which implements the D1 API and database class) is automatically installed. For more information on the D1 Workers Binding API, refer to [Workers Binding API](/d1/worker-api/). ::: You can also bind your D1 database to a [Pages Function](/pages/functions/). For more information, refer to [Functions Bindings for D1](/pages/functions/bindings/#d1-databases). You create bindings by adding them to the Worker you have created. 1. Go to **Workers & Pages** > **Overview**. 2. Select the `d1-tutorial` Worker you created in [step 1](/d1/get-started/#1-create-a-worker). 3. Select **Settings**. 4. Scroll to **Bindings**, then select **Add**. 5. Select **D1 database**. 6. Name your binding in **Variable name**, then select the `prod-d1-tutorial` D1 database you created in [step 2](/d1/get-started/#2-create-a-database) from the dropdown menu. For this tutorial, name your binding `DB`. 7. Select **Deploy** to deploy your binding. When deploying, there are two options: - **Deploy:** Immediately deploy the binding to 100% of your audience. - **Save version:** Save a version of the binding which you can deploy in the future. For this tutorial, select **Deploy**. ## 4. Run a query against your D1 database ### Configure your D1 database After correctly preparing your `wrangler.toml / wrangler.json` file, set up your database. Use the example `schema.sql` file below to initialize your database. 1. Copy the following code and save it as a `schema.sql` file in the `d1-tutorial` Worker directory you created in step 1: ```sql DROP TABLE IF EXISTS Customers; CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT); INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name'); ``` 2. Initialize your database to run and test locally first. Bootstrap your new D1 database by running: ```sh npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql ``` 3. Validate your data is in your database by running: ```sh npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT * FROM Customers" ``` ```sh output 🌀 Mapping SQL input into an array of statements 🌀 Executing on local database production-db-backend (5f092302-3fbd-4247-a873-bf1afc5150b) from .wrangler/state/v3/d1: ┌────────────┬─────────────────────┬───────────────────┐ │ CustomerId │ CompanyName │ ContactName │ ├────────────┼─────────────────────┼───────────────────┤ │ 1 │ Alfreds Futterkiste │ Maria Anders │ ├────────────┼─────────────────────┼───────────────────┤ │ 4 │ Around the Horn │ Thomas Hardy │ ├────────────┼─────────────────────┼───────────────────┤ │ 11 │ Bs Beverages │ Victoria Ashworth │ ├────────────┼─────────────────────┼───────────────────┤ │ 13 │ Bs Beverages │ Random Name │ └────────────┴─────────────────────┴───────────────────┘ ``` Use the Dashboard to create a table and populate it with data. 1. Go to **Storage & Databases** > **D1**. 2. Select the `prod-d1-tutorial` database you created in [step 2](/d1/get-started/#2-create-a-database). 3. Select **Console**. 4. Paste the following SQL snippet. ```sql DROP TABLE IF EXISTS Customers; CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT); INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name'); ``` 5. Select **Execute**. This creates a table called `Customers` in your `prod-d1-tutorial` database. 6. Select **Tables**, then select the `Customers` table to view the contents of the table. ### Write queries within your Worker After you have set up your database, run an SQL query from within your Worker. 1. Navigate to your `d1-tutorial` Worker and open the `index.ts` file. The `index.ts` file is where you configure your Worker's interactions with D1. 2. Clear the content of `index.ts`. 3. Paste the following code snippet into your `index.ts` file: ```typescript export interface Env { // If you set another name in the Wrangler config file for the value for 'binding', // replace "DB" with the variable name you defined. DB: D1Database; } export default { async fetch(request, env): Promise { const { pathname } = new URL(request.url); if (pathname === "/api/beverages") { // If you did not use `DB` as your binding name, change it here const { results } = await env.DB.prepare( "SELECT * FROM Customers WHERE CompanyName = ?", ) .bind("Bs Beverages") .all(); return Response.json(results); } return new Response( "Call /api/beverages to see everyone who works at Bs Beverages", ); }, } satisfies ExportedHandler; ``` In the code above, you: 1. Define a binding to your D1 database in your TypeScript code. This binding matches the `binding` value you set in the `wrangler.toml / wrangler.json` file under `[[d1_databases]]`. 2. Query your database using `env.DB.prepare` to issue a [prepared query](/d1/worker-api/d1-database/#prepare) with a placeholder (the `?` in the query). 3. Call `bind()` to safely and securely bind a value to that placeholder. In a real application, you would allow a user to define the `CompanyName` they want to list results for. Using `bind()` prevents users from executing arbitrary SQL (known as "SQL injection") against your application and deleting or otherwise modifying your database. 4. Execute the query by calling `all()` to return all rows (or none, if the query returns none). 5. Return your query results, if any, in JSON format with `Response.json(results)`. After configuring your Worker, you can test your project locally before you deploy globally. You can query your D1 database using your Worker. 1. Go to **Workers & Pages** > **Overview**. 2. Select the `d1-tutorial` Worker you created. 3. Select **Edit Code**. 4. Clear the contents of the `worker.js` file, then paste the following code: ```js export default { async fetch(request, env) { const { pathname } = new URL(request.url); if (pathname === "/api/beverages") { // If you did not use `DB` as your binding name, change it here const { results } = await env.DB.prepare( "SELECT * FROM Customers WHERE CompanyName = ?" ) .bind("Bs Beverages") .all(); return new Response(JSON.stringify(results), { headers: { 'Content-Type': 'application/json' } }); } return new Response( "Call /api/beverages to see everyone who works at Bs Beverages" ); }, }; ``` 5. Select **Save**. ## 5. Deploy your database Deploy your database on Cloudflare's global network. To deploy your Worker to production using Wrangler, you must first repeat the [database configuration](/d1/get-started/#configure-your-d1-database) steps after replacing the `--local` flag with the `--remote` flag to give your Worker data to read. This creates the database tables and imports the data into the production version of your database. 1. Bootstrap your database with the `schema.sql` file you created in step 4: ```sh npx wrangler d1 execute prod-d1-tutorial --remote --file=./schema.sql ``` 2. Validate the data is in production by running: ```sh npx wrangler d1 execute prod-d1-tutorial --remote --command="SELECT * FROM Customers" ``` 3. Deploy your Worker to make your project accessible on the Internet. Run: ```sh npx wrangler deploy ``` ```sh output Outputs: https://d1-tutorial..workers.dev ``` You can now visit the URL for your newly created project to query your live database. For example, if the URL of your new Worker is `d1-tutorial..workers.dev`, accessing `https://d1-tutorial..workers.dev/api/beverages` sends a request to your Worker that queries your live database directly. 4. Test your database is running successfully. Add `/api/beverages` to the provided Wrangler URL. For example, `https://d1-tutorial..workers.dev/api/beverages`. 1. Go to **Workers & Pages** > **Overview**. 2. Select your `d1-tutorial` Worker. 3. Select **Deployments**. 4. From the **Version History** table, select **Deploy version**. 5. From the **Deploy version** page, select **Deploy**. This deploys the latest version of the Worker code to production. ## 6. (Optional) Develop locally with Wrangler If you are using D1 with Wrangler, you can test your database locally. While in your project directory: 1. Run `wrangler dev`: ```sh npx wrangler dev ``` When you run `wrangler dev`, Wrangler provides a URL (most likely `localhost:8787`) to review your Worker. 2. Go to the URL. The page displays `Call /api/beverages to see everyone who works at Bs Beverages`. 3. Test your database is running successfully. Add `/api/beverages` to the provided Wrangler URL. For example, `localhost:8787/api/beverages`. If successful, the browser displays your data. :::note You can only develop locally if you are using Wrangler. You cannot develop locally through the Cloudflare dashboard. ::: ## 7. (Optional) Delete your database To delete your database: Run: ```sh npx wrangler d1 delete prod-d1-tutorial ``` 1. Go to **Storages & Databases** > **D1**. 2. Select your `prod-d1-tutorial` D1 database. 3. Select **Settings**. 4. Select **Delete**. 5. Type the name of the database (`prod-d1-tutorial`) to confirm the deletion. If you want to delete your Worker: Run: ```sh npx wrangler delete d1-tutorial ``` 1. Go to **Workers & Pages** > **Overview**. 2. Select your `d1-tutorial` Worker. 3. Select **Settings**. 4. Scroll to the bottom of the page, then select **Delete**. 5. Type the name of the Worker (`d1-tutorial`) to confirm the deletion. ## Summary In this tutorial, you have: - Created a D1 database - Created a Worker to access that database - Deployed your project globally ## Next steps If you have any feature requests or notice any bugs, share your feedback directly with the Cloudflare team by joining the [Cloudflare Developers community on Discord](https://discord.cloudflare.com). - See supported [Wrangler commands for D1](/workers/wrangler/commands/#d1). - Learn how to use [D1 Worker Binding APIs](/d1/worker-api/) within your Worker, and test them from the [API playground](/d1/worker-api/#api-playground). - Explore [community projects built on D1](/d1/reference/community-projects/). --- # Wrangler commands URL: https://developers.cloudflare.com/d1/wrangler-commands/ import { Render, Type, MetaInfo } from "~/components" D1 Wrangler commands use REST APIs to interact with the control plane. This page lists the Wrangler commands for D1. ## Global commands ## Experimental commands ### `insights` Returns statistics about your queries. ```sh npx wrangler d1 insights --