100 free credits. No credit card required. Get a key

How to scrape Facebook Ad Library search with JavaScript

Search the Meta Ad Library (ads on Facebook, Instagram, Messenger, WhatsApp, Threads and Audience Network) by keyword: 30 ads a page with the creative (text, title, link, call to action, images, videos, carousel cards), the advertiser, delivery dates and placements, in the library’s own JSON. Filters: country, active or inactive, media type, special ad category, language, placement and a delivery date window.

The examples use the fetch built into Node.js 18+ (and every browser and edge runtime), with AbortSignal.timeout and top-level await, and no dependencies.

GET /v1/facebook/ads/search2 credits per callRefunded on failureBeta

Before you start

  1. Get an API keySign up for 100 free credits, no card. Keys start with gs_live_.
  2. Put it in the environmentEvery example reads it from GROUNDSOCIAL_API_KEY: export GROUNDSOCIAL_API_KEY=gs_live_…
  3. Set up JavaScriptnode --version # 18 or newer: fetch is built in, nothing to install

Call Facebook Ad Library search API from JavaScript

GET /v1/facebook/ads/search. Save this as main.mjs and run node main.mjs. It reads the items in ads and prints page_name and collation_count for each.

main.mjs
// main.mjs: Node.js 18+, no dependencies
const url = new URL('https://api.groundsocial.dev/v1/facebook/ads/search')
url.searchParams.set('q', 'running shoes')
url.searchParams.set('country', 'US')

const res = await fetch(url, {
  headers: {
    Authorization: `Bearer ${process.env.GROUNDSOCIAL_API_KEY}`,
  },
  signal: AbortSignal.timeout(60_000),
})
if (!res.ok) {
  const { error } = await res.json()
  throw new Error(`${error.code}: ${error.hint ?? error.message}`)
}
const data = await res.json()

for (const item of data.ads) {
  console.log(item.page_name, item.collation_count)
}

console.log('credits charged:', res.headers.get('x-credits-charged'))

The response

A real Facebook response to this call, recorded from the live source and shortened for display: arrays keep their first items and … marks every cut. The recorded page had 4 items in ads. Live calls return current data in the same shape.

200 OK
{
  "ads": [
    {
      "ad_archive_id": "1339489931715040",
      "page_id": "71740214065",
      "page_name": "KURU Footwear",
      "is_active": true,
      "start_date": 1783321200,
      "end_date": 1795507200,
      "publisher_platform": [
        "FACEBOOK",
        "INSTAGRAM",
        "… 1 more"
      ],
      "collation_count": 1,
      "collation_id": "1962576714495079",
      "categories": [
        "UNKNOWN"
      ],
      "currency": "",
      "spend": null,
      "impressions_with_index": {
        "impressions_text": null,
        "impressions_index": -1
      },
      "reach_estimate": null,
      "…": "16 more fields"
    },
    {
      "ad_archive_id": "2087216342231765",
      "page_id": "380039845369159",
      "page_name": "SHEIN",
      "is_active": true,
      "start_date": 1784271600,
      "end_date": 1795507200,
      "publisher_platform": [
        "FACEBOOK",
        "INSTAGRAM"
      ],
      "collation_count": null,
      "collation_id": null,
      "categories": [
        "UNKNOWN"
      ],
      "currency": "",
      "spend": null,
      "impressions_with_index": {
        "impressions_text": null,
        "impressions_index": -1
      },
      "reach_estimate": null,
      "…": "16 more fields"
    },
    "… 2 more"
  ],
  "count": 50001,
  "page_info": {
    "has_next_page": true,
    "end_cursor": "AQHTENf1iSXzN3Of5tndjGUMLkaZgZ136jt8lT5WV_l52Al2qA9KQ9L1c5a9PV0OHq9G"
  }
}

Top-level fields

FieldTypeDescription
adsFacebookAd[]–
countinteger | nullMeta’s estimate of how many ads match, on the first page (null on later pages). Meta caps it at 50,001.
page_infoobject–

Parameters

NameInTypeDescription
q (required)querystringKeyword or phrase. Example: running shoes.
search_typequery"keyword_unordered" | "keyword_exact_phrase"keyword_unordered (default: all the words, any order) or keyword_exact_phrase. One of keyword_unordered, keyword_exact_phrase.
countryquerystringISO 3166-1 alpha-2 country the ads reached (US, GB, DE…), or ALL (default).
statusquery"active" | "inactive" | "all"active (default), inactive, or all. One of active, inactive, all.
media_typequery"all" | "image" | "video" | "meme" | "image_and_meme" | "none"all (default), image, video, meme (image with text), image_and_meme, none (text only). One of all, image, video, meme, image_and_meme, none.
ad_typequery"all" | "political_and_issue_ads" | "housing" | "employment" | "credit" | "financial"all (default), or one of Meta’s special ad categories: political_and_issue_ads, housing, employment, credit, financial. One of all, political_and_issue_ads, housing, employment, credit, financial.
sort_byquery"total_impressions" | "relevancy_monthly_grouped" | "total_active_time"total_impressions (default, high to low), relevancy_monthly_grouped (most recent), or total_active_time (longest-running first, within each page of 30). One of total_impressions, relevancy_monthly_grouped, total_active_time.
languagequerystringComma-separated ISO 639-1 languages of the ad text (en,es).
publisher_platformsquerystringComma-separated placements: facebook, instagram, audience_network, messenger, whatsapp, threads, oculus.
start_datequerystringYYYY-MM-DD: only ads delivered on or after this day.
end_datequerystringYYYY-MM-DD: only ads delivered on or before this day.
afterquerystringThe previous page’s page_info.end_cursor; keep the other filters the same.

Pagination

Each page carries the next cursor in page_info.end_cursor; pass it back as after and stop when it is empty. Every page is a separate call at 2 credits per call, so cap the pages you read. Add it to the same file.

Every page
// Each page is one call; stop when there is no next cursor.
async function* pages(maxPages = 5) {
  const url = new URL('https://api.groundsocial.dev/v1/facebook/ads/search')
  url.searchParams.set('q', 'running shoes')
  url.searchParams.set('country', 'US')
  for (let i = 0; i < maxPages; i++) {
    const res = await fetch(url, {
      headers: {
        Authorization: `Bearer ${process.env.GROUNDSOCIAL_API_KEY}`,
      },
      signal: AbortSignal.timeout(60_000),
    })
    if (!res.ok) throw new Error((await res.json()).error.hint)
    const page = await res.json()
    yield page
    const cursor = page.page_info?.end_cursor
    if (!cursor) return
    url.searchParams.set('after', cursor)
  }
}

for await (const page of pages()) {
  for (const item of page.ads ?? []) {
    console.log(item.page_name, item.collation_count)
  }
}

Errors and retries

Every error is JSON with error.code (stable: branch on it), message, hint (what to do next), docs_url and retryable. A failed call is never charged. Retry only when retryable is true, after the Retry-After header.

Errors
async function call(url, init = {}, attempt = 0) {
  const res = await fetch(url, {
    ...init,
    headers: { Authorization: `Bearer ${process.env.GROUNDSOCIAL_API_KEY}`, ...init.headers },
    signal: AbortSignal.timeout(60_000),
  })
  if (res.ok) return res.json()
  const { error } = await res.json()
  // Branch on error.code (stable); error.hint says what to do next.
  if (error.retryable && attempt < 2) {
    const wait = Number(res.headers.get('retry-after') ?? 2)
    await new Promise((r) => setTimeout(r, wait * 1000))
    return call(url, init, attempt + 1)
  }
  throw Object.assign(new Error(error.hint ?? error.message), { code: error.code })
}
StatusMeaning
200A page of ads, with the next cursor.
400Invalid input. Nothing was charged.
401Missing or invalid API key.
402Not enough credits, a spend cap was reached, or payment is required.
403The target is private, or the account is suspended.
404The ad, Page or advertiser is not in the Meta Ad Library.
429Too many requests. Wait for Retry-After seconds.
503Facebook is temporarily unavailable. Retryable; nothing was charged.

Every error code and what to do about it.

Pricing

Cost
Per call2 credits per call
1,000 calls$2.00 on the starter pack, $0.80 at volume
No key (MPP or x402)$0.02 per call
Failed callRefunded, never charged

Every response has x-credits-charged and x-credits-remaining headers. Credits never expire. Packs and calculator.

From an AI agent (MCP)

The same call is the facebook_ads_search tool on the hosted MCP server, so Claude, Cursor or any MCP client can make it without code. Add the server once:

bash
claude mcp add --transport http groundsocial https://api.groundsocial.dev/mcp

Then ask for it in words (“Search the Meta Ad Library by keyword: 30 ads a page with country, status, media, category, language, placement and date filters”), or call the tool directly:

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "facebook_ads_search",
    "arguments": {
      "q": "running shoes",
      "country": "US"
    }
  }
}

MCP setup for Claude Desktop, Cursor, VS Code and ChatGPT.

Spy on the creatives in your niche

Search your keyword with sort_by=total_impressions and keep the snapshot of each ad: the first pages are the ads Meta has shown most. collation_count says how many copies of a creative an advertiser runs, a good sign it works.

Questions

How do I get the next page?

Pass page_info.end_cursor as after with the same filters. The first page also carries count, Meta’s estimate of all matches (capped at 50,001).

Is this the official Ad Library API?

No. It reads what the public Ad Library website shows anyone, logged out, for every country and every ad type, not only political ads. Not affiliated with Meta Platforms, Inc.

Keep going

Run it on your own data

One key for Facebook and 76 more platforms, over REST or MCP. Free credits on signup, no card.

Facebook is a trademark of Meta Platforms, Inc. We are not affiliated with or endorsed by Meta.