Post

Cloudflare AI Search Setup: Add Semantic Search to Your Website

Add natural-language search to any website with Cloudflare AI Search: crawl the site, test in the Playground, enable the public endpoint, and embed the official snippet. Every step has a dashboard screenshot.

Cloudflare AI Search Setup: Add Semantic Search to Your Website

I wanted readers to be able to type “How do I set up a blog in three languages?” and find my Jekyll post. I used Cloudflare AI Search to crawl my site, then added its search widget to a page. In the Playground, a category page came back ahead of the post.

On 2026-11-29 (Taipei time), I checked the Cloudflare AI Search docs against the Traditional Chinese dashboard. The screenshots use that interface, so some button names may differ in English. The widget settings here are for @cloudflare/ai-search-snippet 0.0.43.

Can I use AI Search on a static site?

Jekyll generates static pages for my blog, so I let the browser send each search straight to Cloudflare’s public endpoint. My site only has to serve the page and its frontend code.

Cloudflare used to call the service AutoRAG. In AI Search, an instance has its own index and settings. I connected the site as a source so the crawler could split its pages into passages and index them. Per the docs, hybrid search is on by default and matches both meaning and keywords.

flowchart LR
  site["Your site"] -->|sitemap| crawler["AI Search crawler"]
  crawler --> index[("Vector and keyword index")]
  reader["Reader's browser"] -->|loads page and snippet| site
  reader -->|"POST /search"| endpoint["Public endpoint"]
  endpoint --> index

The crawl source and the search box can use different domains

According to Cloudflare, AI Search is available on all plans. To crawl a site, add the source domain to the Cloudflare account where you create the instance. The docs specify the account requirement without requiring Proxy (the orange cloud) for the source domain.

The search box can live on a different site. Add that site’s hostname to Authorized hosts in the public endpoint settings. I used my website as the source, but the same search widget can query content stored elsewhere.

Data sourceWhen to use itSetup
Website crawler (Web Crawl)Your content is already published on the webAdd the domain to the same Cloudflare account
Built-in storageYou want to upload Markdown, PDFs, or other filesUpload directly to the instance
R2 bucketYour files are in R2Enable R2. Use a service API token when connecting through the REST API or a Workers binding
D1 database (beta)Your content is in D1 tablesSelect rows with a read-only SQL query. Use a service API token when connecting through the REST API or a Workers binding

Per the docs, Cloudflare creates and registers the service API token for you when you connect R2 through the dashboard or the Wrangler CLI.

Step 1. Create an instance and choose Web Crawl

I opened AI → AI Search in the Cloudflare dashboard. The blue button at the top right said Create namespace. To find Create instance, click the arrow next to it.

The AI Search dashboard with the top-right menu open and Create instance visible

A namespace groups instances. For a single site, the account’s default namespace will do. Keep the name the dashboard generates or enter your own. Names can be up to 64 characters and use lowercase letters, digits, _, and single hyphens.

Every instance comes with built-in storage. I selected Web Crawl below it and clicked Next.

The first step of the wizard with the default namespace and Web Crawl selected. R2 is unavailable.

Enter the URL you want to crawl. When I entered https://justmao.com, a green check appeared and the dashboard confirmed the domain was active in my Cloudflare account.

The dashboard confirms https://justmao.com as the crawl target and shows Sitemap as the parse type.

I also tried https://example.com. The dashboard said it couldn’t find a sitemap and asked me to check robots.txt. For your own site, confirm the domain is on your account first. If you have no sitemap the crawler can use, choose Discover.

Parse typeHow it finds pagesWhen it fetches them again
Sitemap (default)Reads the URLs listed in your sitemapChecks whether <lastmod> changed at sync time
DiscoverFollows links from the starting URL and uses available sitemaps by defaultUses the page’s cache age, which defaults to one day

Per the docs, if you enter URLs under Specific sitemap, the crawler reads only those sitemaps. Otherwise, it looks for Sitemap: in robots.txt. If it can’t find robots.txt, it tries /sitemap.xml. With a complete, up-to-date sitemap, I choose Sitemap mode.

Next, open Show more under the parser options. This is where you can specify sitemaps, add request headers, or include images. Image ingestion is off by default.

The rendering options are Static sites and Rendered sites, with Rendered sites marked as the default.

  • Static sites reads the HTML the server returns. For a Jekyll site like mine, that HTML already contains the post.
  • Rendered sites runs JavaScript in a headless browser, which has no visible window. Choose this if the page needs JavaScript to display its content.

To index only certain pages, set a path filter here. Per the docs, the filter matches the full URL, so use **/blog/** for pages under /blog/.

The crawler uses the Cloudflare-AI-Search user agent and respects robots.txt. The index records blocked_by_robots_txt for pages disallowed there. If your own site’s WAF, bot protection, or Turnstile blocks the crawler, see Cloudflare’s WAF allowlisting steps.

Step 3. Review the defaults and create the instance

The wizard shows the default indexing and retrieval settings. I’d start with these values and adjust them after seeing what comes back in the Playground.

The defaults include hybrid search, 1,024 tokens per chunk, 10% overlap, 10 results, and a 0.4 match threshold. Similarity cache is on.

  • 1,024 tokens per chunk, with 10% overlap. Tokens are the units a model splits text into. Adjacent chunks share a little text.
  • Up to 10 results, with a 0.4 match threshold. The threshold applies to vector similarity, which measures how closely the meaning matches. Hybrid search also uses keyword matches to calculate the score you see.
  • Similarity cache. When two queries are close enough, AI Search can reuse the earlier result.

Confirm the name, namespace, data source, and crawl target, then click Create.

The final review screen shows Web Crawl as the data source and justmao.com as the target.

Per the docs, you can also use Wrangler. --type web-crawler selects Web Crawl. Replace the value of --source with a domain in your own account.

1
npx wrangler ai-search create my-search --type web-crawler --source example.com

Step 4. Try the Playground before narrowing the index

After creating the instance, check Overview for indexing progress. When I took this screenshot, Cloudflare had indexed 198 pages from my site with zero errors. The latest scheduled sync took just under six minutes.

The overview shows 198 indexed pages, zero errors, and a sync that took 5 minutes and 53 seconds.

Per the docs, website sources sync every 24 hours by default. You can also start a sync from the dashboard. On Workers Free, the crawler can fetch up to 500 pages per day.

In the Playground’s Search tab, I asked how to set up a blog in three languages. The Multilingual Sites category page came first, and my Jekyll post came second.

Each result shows a score, its source URL, and the matching passage. The right panel lets you adjust the result count and match threshold.

The category page ranks first with a score of 0.662. The Jekyll post is second with a score of 0.633.

The category page came back because it was in the index alongside my posts. If the instance should only contain posts, add an include rule under Path filtering in Settings. Saving the change reindexes the entire instance.

The path filtering panel shows include and exclude rules and warns that saving triggers a full reindex.

I wanted one index for all three languages, with each page’s search box showing posts in its own language. I ended up filtering at query time.

Step 5. Enable search and set authorized hosts and rate limits

I turned on the main switch in the instance’s Public Endpoints tab so the search box could query directly from the browser. I needed search results, so I enabled only the search endpoint.

Search is enabled at https://search.justmao.com/search. Chat completions and MCP are off.

Per the docs, Cloudflare generates a URL like https://<ID>.search.ai.cloudflare.com/, where <ID> is the public endpoint ID. The screenshot shows my custom domain. I explain how to add one below.

SwitchPathWhat it returns
Search/searchPassages that match the query
Chat completions/chat/completionsA model-generated answer in an OpenAI-compatible format
MCP server/mcpAn interface for AI tools to query the index over the Model Context Protocol

Under Security, enter one allowed origin per line in Authorized hosts. Per the docs, website sources allow the source domain by default. Other data sources allow all origins (*). I kept just justmao.com.

For local testing, also add the address you use, such as http://localhost:3000.

The Authorized hosts list contains only justmao.com.

I checked with curl. The response included an access-control-allow-origin header when I sent Origin: https://justmao.com. With a different origin, that header was absent. Browsers use this CORS header to decide whether the page can read a cross-origin response.

Per the docs, the default rate limit is 120 requests per minute, shared across all enabled public endpoints on the instance. I set mine to 60 requests per minute with a fixed window, so the count resets at one-minute intervals.

The rate limit is set to 60 requests per minute in a fixed window.

Anyone who knows my public endpoint URL can query it with curl or a script without signing in. Those requests count toward my usage. I keep rate limiting on and adjust it for the site’s traffic.

To check the endpoint on its own, try the request below. Replace the URL with your public search endpoint and keep the /search path.

1
2
3
curl -X POST https://<ID>.search.ai.cloudflare.com/search \
  -H 'Content-Type: application/json' \
  -d '{"messages":[{"role":"user","content":"how to limit coding agent permissions"}]}'

The endpoint returns JSON. Look in result.chunks for the matching passages. Each chunk has a score, the passage in text, and the page URL in item.key. The title, description, and preview image are in item.metadata when available.

Step 6. Add the search widget to a page

Cloudflare’s widgets are Web Components, custom HTML tags the browser can use directly. I tried the inline search box first and ended up using the modal in my site’s top bar.

ComponentInterface
search-bar-snippetAn inline search box with a results dropdown
search-modal-snippetA search dialog that opens with Cmd/Ctrl+K
chat-bubble-snippetA floating chat button in the corner
chat-page-snippetA full-page chat interface

For a plain HTML page, paste in the official example and replace both instances of <ID> with your public endpoint ID. Use the base URL for api-url. The component appends /search itself.

1
2
3
4
5
6
7
<script type="module" src="https://<ID>.search.ai.cloudflare.com/assets/v0.0.25/search-snippet.es.js"></script>

<search-bar-snippet
  api-url="https://<ID>.search.ai.cloudflare.com/"
  placeholder="Search..."
  max-results="10">
</search-bar-snippet>

I pasted the example into a page on my site and typed “Claude Code sandbox.” The dropdown showed ten results. With the example’s default settings, category pages and posts in other languages appeared in the list.

The search for Claude Code sandbox returns ten results, including category pages and posts in different languages.

The official example loads v0.0.25. When I checked, the endpoint also served v0.0.43, which was the latest version on npm at the time. If your project uses a bundler, install the npm package.

1
npm install @cloudflare/ai-search-snippet

Add import "@cloudflare/ai-search-snippet" to your frontend entry point and use the same HTML tag.

AttributeWhat it does
api-urlRequired. Set it to the public endpoint’s base URL
placeholderSets the placeholder in the search box
themeAccepts light, dark, or auto. The default is auto, which follows the system
max-resultsSets how many results to request at most
translationsOverrides interface text with JSON
show-url, show-dateShows URLs and dates in results
request-optionsAdds options such as filters to each request
disable-analyticsStops sending separate search-term and click data to /stats

I checked the 0.0.43 source for show-url, show-date, request-options, and disable-analytics. The docs’ common attributes table omits all four.

For colors or corner radii, use CSS custom properties prefixed with --search-snippet-, such as --search-snippet-primary-color.

How I check usage and handle search data

Cloudflare’s Limits & pricing page lists December 1, 2026 as the start of billing. Each account gets the following monthly allowances.

ItemIncluded each monthOverage price
Ingestion5 million tokens$0.75 per million tokens
Storage10 GB-month$2.00 per GB-month
Semantic, vector, and hybrid queries1,000 combined$0.75 per 1,000 queries
Full-text queries1,000$0.10 per 1,000 queries

The same page says image processing shares the 5 million ingestion tokens and costs an extra $0.50 per million image tokens above the allowance.

When I took the November screenshot, the AI Search dashboard showed 16 semantic queries and 1.34 million ingestion tokens for my site. Both figures were within the monthly allowances.

The widget searches as you type. In the 0.0.43 source, it sends a request after you stop typing for about 300 milliseconds. Pausing a few times while typing a sentence can turn it into several requests.

Use debounce-ms to lengthen the delay.

Search terms go to Cloudflare. I added disable-analytics to turn off the separate search-term and click records the widget would otherwise send to /stats, outside my site’s consent flow.

The widget still keeps recent results and favorites in the browser’s localStorage. I listed both keys in my privacy policy in all three languages.

  • Recent results search-snippet:recent-results
  • Favorites search-snippet:favorite-results

I put the public endpoint on my own domain

The screenshots show search.justmao.com. To use your own domain, open Custom domains in the Public Endpoints tab. Per the docs, turn on the public endpoint first, then add a hostname on an active domain in the same Cloudflare account. Each instance accepts one fully qualified hostname. Wildcards are disallowed.

Add a CNAME pointing to <ID>.search.ai.cloudflare.com and set its proxy status to Proxied.

Before disabling the default hostname, point the widget’s api-url to the custom domain and check that search works. My endpoint now answers only on the custom domain. To restrict who can search, Cloudflare recommends adding Access to the custom domain and disabling the default hostname so every request goes through the sign-in check.

How I use one index for three languages

My site generates one sitemap each for Traditional Chinese, Simplified Chinese, and English. I entered all three URLs under Specific sitemap to index the three versions in one instance.

My sitemap URLs are https://justmao.com/zh-CN/sitemap.xml, https://justmao.com/en/sitemap.xml, and https://justmao.com/sitemap.xml.

When someone searches, I pass the current language’s URL range through request-options and filter on the index’s folder field. Here’s what the Traditional Chinese page sends.

1
{"body":{"ai_search_options":{"retrieval":{"filters":{"folder":{"$gte":"https://justmao.com/posts/","$lt":"https://justmao.com/posts0"}}}}}}

In character order, 0 comes right after /. The range from https://justmao.com/posts/ (inclusive) to https://justmao.com/posts0 (exclusive) covers URLs that start with the Traditional Chinese post prefix.

The Simplified Chinese and English pages use /zh-CN/posts/ and /en/posts/. I cover those paths in Jekyll in three languages.

The filter isn’t hard-coded. A Liquid template in the top bar builds the prefix for the current language. It puts the endpoint, UI strings, and filter on the search button as data attributes.

This excerpt is from my _includes/topbar.html, with the button’s SVG icon left out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{%- assign ai_search_posts = site.url | append: site.baseurl -%}
{%- unless site.active_lang == site.default_lang -%}
  {%- assign ai_search_posts = ai_search_posts | append: '/' | append: site.active_lang -%}
{%- endunless -%}
{%- assign ai_search_posts = ai_search_posts | append: '/posts' -%}
{%- capture ai_search_request -%}
  {"body":{"ai_search_options":{"retrieval":{"filters":{"folder":{"$gte":"{{ ai_search_posts }}/","$lt":"{{ ai_search_posts }}0"}}}}}}
{%- endcapture -%}

<button
  type="button"
  id="ai-search-trigger"
  class="btn btn-link"
  aria-label="{{ site.data.locales[include.lang].ai_search.button }}"
  data-widget="{{ site.baseurl }}/assets/lib/ai-search-snippet/search-snippet.umd.js"
  data-api-url="{{ site.ai_search_endpoint }}"
  data-translations="{{ site.data.locales[include.lang].ai_search.modal | jsonify | escape }}"
  data-request-options="{{ ai_search_request | escape }}"
>
</button>

site.active_lang is the current language from jekyll-polyglot, and site.default_lang is the default language set in _config.yml. ai_search_endpoint lives in _config.yml, where I set it to https://search.justmao.com.

The UI strings live in each language’s _data/locales/<lang>.yml, and jsonify turns them into the JSON that translations expects.

I pinned version 0.0.43 in npm and copied the package’s UMD JavaScript bundle into my site. Each page only loads the assets/js/ai-search.js below. It loads the widget the first time a reader clicks the search button or presses Ctrl/⌘+K.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(() => {
  'use strict';

  const button = document.getElementById('ai-search-trigger');
  let modal;

  function load() {
    const el = document.createElement('search-modal-snippet');
    el.setAttribute('api-url', button.dataset.apiUrl);
    el.setAttribute('translations', button.dataset.translations);
    el.setAttribute('request-options', button.dataset.requestOptions);
    el.setAttribute('disable-analytics', '');
    el.setAttribute('show-url', '');
    el.addEventListener('keydown', (event) => {
      if (event.isComposing || event.keyCode === 229) event.stopPropagation();
    }, true);
    document.body.append(el);

    const script = document.createElement('script');
    script.src = button.dataset.widget;
    document.head.append(script);
    return customElements.whenDefined('search-modal-snippet').then(() => el);
  }

  async function openSearch() {
    modal ??= load();
    const el = await modal;
    el.setAttribute('theme', document.documentElement.dataset.bsTheme || 'auto');
    el.open();
  }

  button.addEventListener('click', openSearch);
  document.addEventListener('keydown', (event) => {
    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
      event.preventDefault();
      openSearch();
    }
  });
})();

load() adds the widget to the page with all its attributes, then loads the widget’s script. The element upgrades once the script defines it, so it reads every setting when it starts. If the script fails to load, whenDefined never resolves, and the reader has to reload the page to search again.

disable-analytics keeps search terms and clicks away from /stats, as I explained above. The widget also listens for Ctrl/⌘+K, but it doesn’t block the browser’s default action while the dialog is open. Pressing it again then sends Firefox to its search bar, so my page always blocks the shortcut.

When a reader types Chinese with an input method (IME), the widget searches while the text is still being composed and highlights the first result. Composition is the state where the IME is still waiting for the reader to pick characters. Version 0.0.43 handles keys without checking for it, so pressing Enter to confirm the text opens that article, and pressing Esc to cancel the composition closes the dialog.

In load(), I added a keydown listener to the widget’s tag. The third argument, true, runs it in the capture phase, so key events pass through the tag before they reach the input inside the widget. While the reader is composing, stopPropagation() stops the event there without cancelling the default action, so the IME still commits the text.

Safari ends the composition before it fires the keydown for that Enter, so isComposing is already false. That’s why I also check whether keyCode is 229, the value browsers use for keys handled by the IME.

Before opening the dialog, openSearch() reads data-bs-theme from <html> so the dialog follows the site’s current colors. In 0.0.43, the dark-mode variables only take effect when the system uses dark mode. I copied the widget’s own dark values into my assets/css/jekyll-theme-chirpy.scss.

Page rules on the widget’s tag override the values it sets with :host inside its shadow DOM, the widget’s isolated style scope. That’s why the block below works even when the system uses light mode.

1
2
3
4
5
6
7
8
9
10
11
12
13
search-modal-snippet[theme='dark'] {
  --search-snippet-background: #1a1b1e;
  --search-snippet-surface: #25262b;
  --search-snippet-text-color: #c1c2c5;
  --search-snippet-text-secondary: #909296;
  --search-snippet-text-description: #adb5bd;
  --search-snippet-border-color: #373a40;
  --search-snippet-hover-background: #2c2e33;
  --search-snippet-focus-ring: #4dabf740;
  --search-snippet-error-color: #ff6b6b;
  --search-snippet-error-background: #3d1f1f;
  color-scheme: dark;
}

The full integration is in PR #168.

With this filter in place, I ran the same three-languages query again. My Jekyll post now comes first with its 0.633 score, and neither the category page nor the Simplified Chinese version shows up. Before you open search on your own site, try a few questions your readers would ask and check that the top result is the page you want them to read.

Further reading

This post is licensed under CC BY 4.0 by the author.