Homen8n UniversityFacebook Ads Spy Agent
n8n University

Facebook Ads Spy Agent

How to Build a Facebook Ads Spy Agent with n8n (AI-Powered Competitor Analysis)

Running Facebook ads without knowing what your competitors are doing is like showing up to a poker game blindfolded. The Facebook Ads Library is completely public — but manually trawling through it for every competitor, every week, is nobody’s idea of a good time. This n8n workflow fixes that: you enter a competitor’s Facebook Page URL, and an AI agent automatically scrapes their active ads, analyzes each one with Google Gemini, rewrites the copy for your own inspiration, and logs everything to a Google Sheet — hands-free.

Prefer to skip the setup? Grab the ready-made template → and be up and running in under 10 minutes.

What You’ll Build

  1. You open a simple web form and paste a competitor’s Facebook Page URL, choose how many ads to pull, pick a country, and select a date range.
  2. The workflow scrapes that page’s active ads from the Facebook Ads Library using Apify’s actor — no API key from Meta required.
  3. Each ad is classified automatically as a Video, Image, or Text ad, and routed into its own analysis branch.
  4. Google Gemini AI analyzes video and image ads visually — extracting hooks, CTAs, emotional triggers, and conversion insights.
  5. An OpenRouter AI agent writes a full marketing summary and a rewritten version of the ad copy for each ad, then saves everything to your Google Sheet.

How It Works — The Big Picture

This workflow is a single pipeline that fans out into three parallel branches based on ad type, then converges in a shared Google Sheet.

┌────────────────────────────────────────────────────────────────────────────┐
│  FACEBOOK ADS SPY — n8n AI AGENT                                           │
│                                                                             │
│  [Form Trigger]                                                             │
│       │  URL, count, country, period                                        │
│       ▼                                                                     │
│  [Apify Scraper]  ← Facebook Ads Library Scraper actor                     │
│       │  Array of active ads                                                │
│       ▼                                                                     │
│  [Filter: 1,000+ page likes]                                                │
│       │  Quality-filtered ads                                               │
│       ▼                                                                     │
│  [Switch: Ad Type]                                                          │
│       │                                                                     │
│       ├──── Video Ad ────► [Loop] → [Download Video] → [Gemini Analyze]    │
│       │                        → [AI Agent: Summarize + Rewrite]           │
│       │                        → [Google Sheets Append] → [Loop back]      │
│       │                                                                     │
│       ├──── Image Ad ────► [Loop] → [Download Image] → [Gemini Analyze]    │
│       │                        → [AI Agent: Summarize + Rewrite]           │
│       │                        → [Google Sheets Append] → [Loop back]      │
│       │                                                                     │
│       └──── Text Ad ─────► [Loop] → [AI Agent: Summarize + Rewrite]        │
│                                → [Google Sheets Append] → [Loop back]      │
│                                                                             │
│                   ↓↓↓ ALL BRANCHES WRITE TO ↓↓↓                             │
│               [Google Sheet: Facebook Ad Spy]                               │
└────────────────────────────────────────────────────────────────────────────┘
  

What You’ll Need

  • n8n — cloud or self-hosted (v1.0+)
  • Apify account — free tier works; you’ll use the Facebook Ads Library Scraper actor
  • Google account — for Google Sheets (OAuth2)
  • Google Gemini API key — free tier available at Google AI Studio
  • OpenRouter account — pay-per-use; costs pennies per workflow run
  • A Google Sheet set up with the right column headers (schema below)

Estimated build time: 45–60 minutes from scratch, or under 10 minutes with the template.


Part 1 — Scraping Phase

1 On form submission (Form Trigger)

This is the entry point — a hosted web form n8n generates for you automatically. No coding required. Users fill it in and hit Submit.

How to configure it:

  1. Add an n8n Form Trigger node.
  2. Set the Form Title to Facebook Ad Spy.
  3. Add four fields: Ad URL (Text), Ad Count (Number), country (Text), and Ad Period (Dropdown with options: last24h, last7d, last14d, last30d).

What the data looks like after this node:

{
  "Ad URL": "https://www.facebook.com/nike/",
  "Ad Count": 20,
  "country": "US",
  "Ad Period": "last30d"
}
💡

Tip: The Form Trigger gives you a public URL you can bookmark and share with your team. No one else needs to touch n8n — they just open the form in a browser.

2 Run an Actor and get dataset (Apify)

This node calls Apify’s Facebook Ads Library Scraper and returns all active ads for the target page.

How to configure it:

  1. Add an Apify node. Set operation to Run actor and get dataset.
  2. Select actor ID XtaWFhbtfxyzqrFmd (Facebook Ads Library Scraper).
  3. In Custom Body, reference the form fields using n8n expressions to pass count, countryCode, period, and the target url dynamically.
  4. Set Memory to 512 MB and attach your Apify credential.

What each ad object looks like:

{
  "ad_archive_id": "1027384950617283",
  "start_date_formatted": "2026-02-14",
  "advertiser": {
    "ad_library_page_info": {
      "page_info": { "page_name": "Nike", "likes": 34200000 }
    }
  },
  "snapshot": {
    "page_profile_uri": "https://www.facebook.com/nike/",
    "videos": [{ "video_hd_url": "https://cdn.fbcdn.net/.../video.mp4" }],
    "cards": [],
    "body": { "message": "Just Do It. New Spring Collection." }
  }
}
💡

Tip: Apify’s free tier includes $5 in monthly credits — enough to run this workflow dozens of times. A typical 20-ad run costs roughly $0.05–$0.15.

3 Filter (1,000+ Page Likes)

This Filter node drops ads from tiny pages. If a page has fewer than 1,000 likes, the advertiser likely isn’t spending enough to produce tested creative worth analyzing. Configure the condition to check advertiser.ad_library_page_info.page_info.likes is greater than 1000. You can raise this to 10,000 or 100,000 to focus on larger brands.


Part 2 — Routing by Ad Type

4 Switch (Ad Type Router)

This Switch node forks the workflow into three branches based on the type of media in each ad.

  1. Output 0 — Video Ad: checks if snapshot.videos[0].video_hd_url exists.
  2. Output 1 — Image Ad: checks if snapshot.cards[0].original_image_url exists.
  3. Fallback — Text Ad: catches everything else (copy-only ads).
💡

Tip: Order matters — video is checked first. If an ad contains both video and images (carousel), it routes to the Video branch.


Part 3 — Video Ad Branch

5 Loop Over Items (Video)

A SplitInBatches node processes one video ad at a time, preventing Gemini from being overwhelmed with concurrent requests. Connect its output back from the Sheets append node to complete the loop.

6 Download Video (HTTP Request)

Downloads the raw .mp4 file from snapshot.videos[0].video_hd_url as binary data so Gemini can analyze it visually. Set response format to File / Binary.

7 Analyze Video (Google Gemini)

Gemini watches the ad video and extracts 10 marketing data points. Set the resource to Video, model to models/gemini-2.5-flash, and input type to Binary. Use this analysis prompt:

You are a direct response marketing expert.

Analyze this Facebook ad video and extract:
1. Hook (first 3 seconds message)
2. Main problem presented
3. Main solution offered
4. Target audience (who is this ad for)
5. Emotional triggers used
6. Offer details (discount, bonus, urgency)
7. Call to action
8. Video structure breakdown (scene by scene summary)
9. Why this ad might be converting
10. Suggestions to improve this ad

Be concise and structured. Focus only on marketing insights.

8 AI Agent + OpenRouter (Video)

The AI Agent takes the Gemini analysis and the raw ad JSON to produce a structured marketing summary and a rewritten version of the ad copy. Configure the agent prompt to include both the JSON scrape and the Gemini video description. Connect a Structured Output Parser with this schema:

{ "summary": "", "rewrittenAdCopy": "" }

Connect an OpenRouter Chat Model as the language model sub-node. Sample output:

{
  "summary": "Nike targets value-conscious runners with a durability-first message. Hook leads with pain point (shoes falling apart), transitions to stress-test product demo, closes with 30-day return guarantee. High conversion probability due to specific claim + risk reversal combo.",
  "rewrittenAdCopy": "Your running shoes should outlast your excuses. Our React Infinity handles 500 miles of punishment — guaranteed. Try them free for 30 days or your money back."
}

9 Append Row in Sheet (Video)

Saves the full result to your Google Sheet. Map these columns:

Sheet ColumnValue / Expression
ad_archive_idLoop Over Items → ad_archive_id
page_nameadvertiser.ad_library_page_info.page_info.page_name
page_profile_urisnapshot.page_profile_uri
ad typeHardcoded: Video
ad Datestart_date_formatted formatted as yyyy-MM-dd
Summary$json.output.summary
RewrittenAdCopy$json.output.rewrittenAdCopy

Connect the output back to Loop Over Items (port 0) to continue processing the next ad.


Part 4 — Image Ad Branch

The image branch is nearly identical to the video branch, with two key differences:

  1. Download Image — the HTTP Request uses snapshot.cards[0].original_image_url.
  2. Analyze Image (Gemini) — set resource to Image and tailor the prompt to ask for visual structure analysis (headline placement, design elements, layout) instead of scene-by-scene breakdown.

The loop, AI Agent, Structured Output Parser, OpenRouter model, and Sheets append are all configured identically to the video branch.


Part 5 — Text Ad Branch

Text ads contain no video or image, so Gemini isn’t needed here. The loop goes straight to the AI Agent, which analyzes the raw ad JSON (body copy, headline, CTA text) and produces the same summary + rewrittenAdCopy output. The agent works purely from the structured ad data — no media description step required.


The Data Structure

Every branch writes to the same Google Sheet. Create a sheet named Sheet1 with these columns in row 1:

ColumnTypeExampleDescription
ad_archive_idText1027384950617283Unique Facebook ad ID — useful for deduplication
page_nameTextNikeThe advertiser’s Facebook Page name
page_profile_uriTexthttps://facebook.com/nike/Link back to the advertiser’s page
ad typeTextVideoOne of: Video, Image, Text
ad DateDate2026-02-14When the ad started running
SummaryText (long)AI marketing analysis…Gemini + OpenRouter combined analysis
RewrittenAdCopyText (long)Rewritten copy…Swiped and repurposed ad copy

Sample rows:

ad_archive_idpage_namead typead DateSummary (excerpt)
1027384950617283NikeVideo2026-02-14Hook leads with pain point, strong risk reversal…
9182736450192837AdidasImage2026-02-10Bold visual with product closeup, seasonal urgency…
4561728394017263Under ArmourText2026-01-30Copy-heavy, targets gym-goers, performance focus…
📌

Important: Column names must match exactly — including capitalization and spaces. The workflow maps to these exact headers. If you rename any column, update the corresponding expression in the Google Sheets node for that branch.


Full System Flow

┌───────────────────────────────────────────────────────────────────────────┐
│  USER INPUT                                                                  │
│  Form → { url, count: 20, country: "US", period: "last30d" }               │
└─────────────────────────────────┴──────────────────────────────────────────┘
                                 │
                                 ▼
┌───────────────────────────────────────────────────────────────────────────┐
│  SCRAPING                                                                    │
│  Apify Actor → 20 active ad objects from Facebook Ads Library               │
│  Filter → drops pages with < 1,000 likes                                   │
└─────────────────────────────────┴──────────────────────────────────────────┘
                                 │
                                 ▼
┌───────────────────────────────────────────────────────────────────────────┐
│  ROUTING (Switch by ad type)                                                 │
│    ├── Video → Loop → Download MP4 → Gemini vision → AI Agent             │
│    ├── Image → Loop → Download JPG → Gemini vision → AI Agent             │
│    └── Text  → Loop ───────────────────→ AI Agent             │
└─────────────────────────────────┴──────────────────────────────────────────┘
                                 │
                                 ▼
┌───────────────────────────────────────────────────────────────────────────┐
│  OUTPUT                                                                      │
│  Google Sheets row per ad: metadata + AI summary + rewritten copy            │
└───────────────────────────────────────────────────────────────────────────┘
  

Testing Your Workflow

  1. Open the Form Trigger URL in a browser (find it under the node settings → Test URL).
  2. Enter a well-known brand URL such as https://www.facebook.com/nike/, set Ad Count to 3, country to US, and Ad Period to last30d.
  3. Submit the form and watch the n8n execution log in real time.
  4. After it completes, open your Google Sheet and check for new rows.
  5. Confirm all 7 columns have data — especially Summary and RewrittenAdCopy.
ProblemLikely CauseFix
Apify returns 0 adsPage URL is wrong or page has no active adsVerify the URL; try a large brand page
All ads filtered outPage has < 1,000 likesLower the Filter threshold to 100
Gemini error on videoVideo URL expired or isn’t a direct MP4Re-run the workflow; Apify CDN URLs can expire
output.summary is emptyStructured Output Parser failedCheck that OpenRouter model is connected to AI Agent
Google Sheets auth errorOAuth token expiredRe-connect your Google credential in n8n
ad Date shows wrong formatn8n date expression issueConfirm start_date_formatted is a date string, not a timestamp

Frequently Asked Questions

Do I need a Facebook API key or special access from Meta?

No. The workflow uses Apify’s Facebook Ads Library Scraper, which pulls from Meta’s publicly available Ads Library. You don’t need any developer credentials from Facebook or Meta — just an Apify account.

How much does it cost to run?

The main cost is Apify (roughly $0.05–$0.15 per run for 20 ads) and OpenRouter (fractions of a cent per AI call). Google Gemini has a generous free tier. A typical 20-ad run costs less than $0.25 total.

Can I spy on multiple competitors in one run?

The current workflow processes one Facebook Page URL per form submission. For multiple competitors, run the form once per URL — results accumulate in the same Sheet. You could also modify the Apify node to accept an array of URLs.

What if an ad has both a video and images (carousel)?

The Switch node checks for a video URL first. If snapshot.videos[0].video_hd_url exists, the ad routes to the Video branch regardless of whether images are also present. Carousel-only ads (no video) hit the Image branch via cards[0].original_image_url.

Can I change the AI model?

Yes — the OpenRouter node accepts any model on openrouter.ai. Swap in anthropic/claude-3-haiku or openai/gpt-4o-mini for different speed/quality trade-offs. The Gemini vision nodes are fixed to Gemini for multimodal analysis, but the text generation step is fully swappable.

Can I run this automatically on a schedule?

Absolutely. Replace the Form Trigger with a Schedule Trigger, hardcode the competitor URL and settings in the Apify node, and set it to run weekly. You’ll have a fully automated competitor monitoring system that updates your Sheet every seven days without any manual input.


🚀 Get the Facebook Ads Spy Agent Template

Import the workflow, add your credentials, and start pulling AI-analyzed competitor ads into your Google Sheet in under 10 minutes — no build time required.

Get the Template →

Instant download · Works on n8n Cloud and self-hosted

What’s Next?

  • Add a Slack or email notification when the workflow finishes — get a digest of the top 3 most interesting ads delivered straight to your inbox.
  • Add a deduplication step before the Sheets append to check ad_archive_id against existing rows, preventing duplicates when re-running the same competitor.
  • Schedule it weekly per competitor and track which ads are still running after 30+ days — longevity is the strongest signal of a high-converting creative.
  • Add a sentiment scoring node to automatically flag ads using high-urgency language or deep discounts — a sign your competitor may be pushing hard on a particular angle.
  • Store in Airtable instead of Google Sheets for richer filtering, gallery views, and team collaboration on creative insights.
n8n Facebook Ads Apify Google Gemini OpenRouter Google Sheets AI Agent marketing automation competitor research ad spy