{
  "name": "Analyze the Meta ads running for any keyword with Vexqo, Gemini and Google Sheets",
  "nodes": [
    {
      "parameters": {
        "content": "## Analyze the Meta ads running for any keyword\n\nType a keyword. This workflow reads the ads that are live for it in the Meta Ad Library, through the [Vexqo API](https://vexqo.dev), and keeps the advertisers with a real following. Gemini then studies each ad's video, image or text, and one row for each ad goes to a Google Sheet: a summary, the angle, the offer, the hook, what the media shows, and the copy rewritten for your brand.\n\n### Set up\n\n1. **Get a Vexqo API key** at [vexqo.dev](https://vexqo.dev).\n2. Open **Search the Meta Ad Library** and create a **Header Auth** credential: name `X-API-Key`, value your key.\n3. Open **Watch the video**, **Look at the image** and **Read the text**, and pick a **Google Gemini** credential in each. A key from Google AI Studio works.\n4. Connect **Add to the sheet** to a Google Sheet whose first row holds the column names listed in note 4.\n5. Open **What to look for** and set your keyword, your country and a sentence about your brand.\n\n### What it costs\n\nVexqo charges 1 credit for every 10 ads it returns: 20 credits for a run of 200 ads. Gemini charges for each ad it studies, and a video costs more than an image.\n\n### What you do not need\n\nA scraper to rent, a Drive folder or an upload step. The search is one node, and the Gemini nodes take each video and image from its link.",
        "height": 660,
        "width": 500
      },
      "id": "07ea730f-4752-5e6f-9845-892b9506be10",
      "name": "About",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -780,
        -340
      ]
    },
    {
      "parameters": {
        "content": "### 1. What to look for\n\n`keyword` is what you would type into the Ad Library. `country` is a two-letter code or `ALL`. `max_ads` is how many live ads to read. `min_page_likes` drops advertisers with a smaller following. `your_brand` is what the rewrite is written for. `model` is the Gemini model. `pause_seconds` is the wait between two ads.",
        "height": 600,
        "width": 480,
        "color": 7
      },
      "id": "28aac319-c966-5ef8-8ef4-b7dd32d1779c",
      "name": "Note: what",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -260,
        -340
      ]
    },
    {
      "parameters": {
        "content": "### 2. Search and filter\n\nOne request reads up to 100 ads, and the next one reads on from where it stopped, 7 seconds later. A failed request is tried three times. Then each ad becomes one item with the fields worth keeping, the link of its video or image, and the brief for the model.\n\n**Only ads not seen before** is switched off. Switch it on once the workflow runs every week: n8n then remembers the ads it has passed, and each run studies only the new ones.",
        "height": 600,
        "width": 1380,
        "color": 7
      },
      "id": "13f610a9-ff16-5675-9984-0b59c3ca7ba3",
      "name": "Note: search",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        240,
        -340
      ]
    },
    {
      "parameters": {
        "content": "### 3. Study each ad\n\nOne ad at a time. A video ad goes to **Watch the video**, an image ad to **Look at the image**, and an ad with neither to **Read the text**. Each node gets the same brief and answers in JSON. When Gemini cannot study an ad, the row is still written, with the reason in `note`.",
        "height": 720,
        "width": 800,
        "color": 7
      },
      "id": "1b2cd27d-ce9b-5453-a481-054e2c6f3760",
      "name": "Note: study",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1640,
        -340
      ]
    },
    {
      "parameters": {
        "content": "### 4. Write the row\n\nThe sheet needs these column names in its first row:\n\n`found_on` `advertiser` `page_likes` `format` `started` `days_running` `text` `title` `cta` `link` `platforms` `summary` `angle` `offer` `hook` `media_analysis` `rewritten_copy` `media_url` `ad_library_url` `page_url` `ad_id` `note`\n\nThe pause keeps the run inside the requests a minute your Gemini key allows. Lower `pause_seconds` on a paid key.",
        "height": 600,
        "width": 680,
        "color": 7
      },
      "id": "25707aff-6dee-5687-b23a-d670eb49fd63",
      "name": "Note: write",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2460,
        -340
      ]
    },
    {
      "parameters": {},
      "id": "dc8ec413-af21-56a6-b6c8-ce3a40c9d051",
      "name": "Run it now",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -200,
        -100
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8
            }
          ]
        }
      },
      "id": "2809ae97-fec7-563d-9d0e-f3e59c991d50",
      "name": "Every Monday",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -200,
        100
      ]
    },
    {
      "parameters": {
        "mode": "raw",
        "jsonOutput": "{\n  \"keyword\": \"collagen powder\",\n  \"country\": \"US\",\n  \"max_ads\": 200,\n  \"min_page_likes\": 1000,\n  \"your_brand\": \"Write one sentence about your brand and product here, so the rewrite fits it.\",\n  \"model\": \"models/gemini-3.6-flash\",\n  \"pause_seconds\": 6\n}",
        "options": {}
      },
      "id": "b196ba9f-322b-5437-84bd-826ec3b81778",
      "name": "What to look for",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        40,
        0
      ]
    },
    {
      "parameters": {
        "url": "https://api.vexqo.dev/facebook/ads",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "specifyQuery": "json",
        "jsonQuery": "={{ JSON.stringify({ q: $json.keyword, country: $json.country, active_status: 'active', limit: Math.min(100, $json.max_ads) }) }}",
        "options": {
          "timeout": 120000,
          "pagination": {
            "pagination": {
              "paginationMode": "updateAParameterInEachRequest",
              "parameters": {
                "parameters": [
                  {
                    "type": "qs",
                    "name": "cursor",
                    "value": "={{ $response.body.search_information.next_cursor }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !$response.body.search_information.next_cursor }}",
              "limitPagesFetched": true,
              "maxRequests": "={{ Math.ceil($json.max_ads / 100) }}",
              "requestInterval": 7000
            }
          }
        }
      },
      "id": "1b0fe1d5-c96b-53ca-bca5-b4246cda07d9",
      "name": "Search the Meta Ad Library",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        340,
        0
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "fieldToSplitOut": "ads",
        "options": {}
      },
      "id": "ffb93e73-c791-5c57-b017-4cd3390f8dec",
      "name": "One item per ad",
      "type": "n8n-nodes-base.splitOut",
      "typeVersion": 1,
      "position": [
        560,
        0
      ]
    },
    {
      "parameters": {
        "maxItems": "={{ $('What to look for').first().json.max_ads }}"
      },
      "id": "d82b9b4f-a41f-5983-b4b6-500fc3a3d9aa",
      "name": "Up to max_ads",
      "type": "n8n-nodes-base.limit",
      "typeVersion": 1,
      "position": [
        780,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// One item for each ad: the fields worth keeping, the media to study and the brief for the model.\nconst settings = $('What to look for').first().json;\n\n// A catalog ad carries placeholders such as {{product.name}}; its first card holds the real words.\nconst usable = (value) => (value && !String(value).includes('{{') ? String(value) : '');\n\nreturn $input.all().map(({ json: ad }) => {\n  const snapshot = ad.snapshot ?? {};\n  const card = (snapshot.cards ?? [])[0] ?? {};\n  const video = (snapshot.videos ?? [])[0] ?? card;\n  const image = (snapshot.images ?? [])[0] ?? card;\n\n  const videoUrl = video.video_sd_url || video.video_hd_url || '';\n  const imageUrl = image.original_image_url || image.resized_image_url || '';\n  const kind = videoUrl ? 'video' : imageUrl ? 'image' : 'text';\n\n  const started = (ad.start_date_formatted || '').slice(0, 10);\n  const row = {\n    advertiser: ad.page_name ?? snapshot.page_name ?? '',\n    page_likes: snapshot.page_like_count ?? 0,\n    format: snapshot.display_format ?? '',\n    started,\n    days_running: started ? Math.floor($now.diff(DateTime.fromISO(started), 'days').days) : '',\n    text: usable(snapshot.body?.text) || usable(card.body),\n    title: usable(snapshot.title) || usable(card.title),\n    cta: snapshot.cta_text || card.cta_text || '',\n    link: snapshot.link_url || card.link_url || '',\n    platforms: (ad.publisher_platform ?? []).join(', '),\n    media_url: videoUrl || imageUrl,\n    ad_library_url: ad.ad_library_url ?? '',\n    page_url: snapshot.page_profile_uri ?? '',\n    ad_id: String(ad.ad_archive_id ?? ''),\n  };\n\n  const brief = [\n    'You study one ad from the Meta Ad Library for a marketer who competes with its advertiser.',\n    kind === 'video'\n      ? 'The video of the ad is attached. Watch it and listen to it.'\n      : kind === 'image'\n        ? 'The image of the ad is attached. Look at it.'\n        : 'The ad has no image or video to study.',\n    '',\n    'Answer with one JSON object and nothing else. Its keys:',\n    '\"summary\": what the ad says and who it speaks to, in two sentences.',\n    '\"angle\": the main selling angle, in a few words.',\n    '\"offer\": the offer, discount or price it names, or \"none\".',\n    '\"hook\": its opening line or opening seconds, and why they would stop a reader.',\n    '\"media_analysis\": what the image or video shows: the scenes, the people, the words on screen and the sound. Write \"none\" when there is nothing to study.',\n    '\"rewritten_copy\": the text of the ad rewritten for the brand described below, with the same angle and about the same length.',\n    '',\n    'The ad',\n    `Advertiser: ${row.advertiser}`,\n    `Format: ${row.format}`,\n    `Running since: ${row.started}`,\n    `Text: ${row.text || 'none'}`,\n    `Title: ${row.title || 'none'}`,\n    `Button: ${row.cta || 'none'}`,\n    `Link: ${row.link || 'none'}`,\n    '',\n    `The brand to rewrite for: ${settings.your_brand}`,\n  ].join('\\n');\n\n  return { json: { ...row, kind, brief } };\n});"
      },
      "id": "37fa04c4-6ce1-5d1e-bb12-d44eed4dfe02",
      "name": "Tidy each ad",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1000,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "a2095349-0853-5b6b-8319-8bc2af563b2b",
              "leftValue": "={{ $json.page_likes }}",
              "rightValue": "={{ $('What to look for').first().json.min_page_likes }}",
              "operator": {
                "type": "number",
                "operation": "gte"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "f537864f-a0ed-5268-b29b-38d4d044eeb2",
      "name": "Only pages with enough likes",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        1220,
        0
      ]
    },
    {
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "dedupeValue": "={{ $json.ad_id }}",
        "options": {}
      },
      "id": "500c570c-3657-550e-91bb-dce126807a93",
      "name": "Only ads not seen before",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        1440,
        0
      ],
      "disabled": true
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "99ad7ac7-e2c7-545e-92a0-fcfb1ea6a72b",
      "name": "Loop over the ads",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        1720,
        0
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "799c19cc-c67a-5a79-b8f8-3a38ad6a3323",
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "video",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "video"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "bd705dc0-1dad-5c57-8d94-9ab11dc7dffa",
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "image",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "image"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "f45d329a-85cd-512a-9e85-fb23629daa87",
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "text",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "text"
            }
          ]
        },
        "options": {}
      },
      "id": "02d4d9cf-122b-5dfe-9d04-a1d1095befc3",
      "name": "What kind of ad",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1940,
        0
      ]
    },
    {
      "parameters": {
        "resource": "video",
        "operation": "analyze",
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('What to look for').first().json.model }}"
        },
        "text": "={{ $json.brief }}",
        "inputType": "url",
        "videoUrls": "={{ $json.media_url }}",
        "simplify": true,
        "options": {
          "maxOutputTokens": 2500
        }
      },
      "id": "232b679e-c9b2-5f27-ace4-18a854fc310a",
      "name": "Watch the video",
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1,
      "position": [
        2200,
        -200
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "resource": "image",
        "operation": "analyze",
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('What to look for').first().json.model }}"
        },
        "text": "={{ $json.brief }}",
        "inputType": "url",
        "imageUrls": "={{ $json.media_url }}",
        "simplify": true,
        "options": {
          "maxOutputTokens": 2500
        }
      },
      "id": "29f1b40b-d0fa-5de1-99df-ff9d9cfd4956",
      "name": "Look at the image",
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1,
      "position": [
        2200,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "resource": "text",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('What to look for').first().json.model }}"
        },
        "messages": {
          "values": [
            {
              "content": "={{ $json.brief }}",
              "role": "user"
            }
          ]
        },
        "simplify": true,
        "jsonOutput": true,
        "options": {
          "maxOutputTokens": 2500
        }
      },
      "id": "c57bf444-8608-5d40-b7d1-2f00362fa54e",
      "name": "Read the text",
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1,
      "position": [
        2200,
        200
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Join what the model answered to the ad it was asked about.\nconst { brief, kind, ...ad } = $('Loop over the ads').item.json;\n\nconst parts = $json.content?.parts ?? [];\nconst raw = parts.map((part) => part.text ?? '').join('').trim();\n\nlet answer = {};\nif (raw) {\n  try {\n    // The model sometimes wraps its JSON in a code fence.\n    answer = JSON.parse(raw.replace(/^```(?:json)?\\s*/i, '').replace(/\\s*```$/, ''));\n  } catch (error) {\n    answer = { summary: raw };\n  }\n}\nconst say = (value) => (value == null ? '' : typeof value === 'string' ? value : JSON.stringify(value));\nconst failure = $json.error ? say($json.error.message ?? $json.error) : '';\n\nconst { ad_library_url, page_url, ad_id, media_url, ...shown } = ad;\n\nreturn {\n  json: {\n    found_on: $now.toFormat('yyyy-MM-dd'),\n    ...shown,\n    summary: say(answer.summary),\n    angle: say(answer.angle),\n    offer: say(answer.offer),\n    hook: say(answer.hook),\n    media_analysis: say(answer.media_analysis),\n    rewritten_copy: say(answer.rewritten_copy),\n    media_url,\n    ad_library_url,\n    page_url,\n    ad_id,\n    note: failure || (raw ? '' : 'The model gave no answer for this ad.'),\n  },\n};"
      },
      "id": "c7f88fb7-abbc-5958-b727-3263448f5615",
      "name": "Make the row",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2540,
        0
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "1b972b43-63d4-5191-bd35-4f4c34596d8b",
      "name": "Add to the sheet",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        2760,
        0
      ]
    },
    {
      "parameters": {
        "amount": "={{ $('What to look for').first().json.pause_seconds }}",
        "unit": "seconds"
      },
      "id": "13c677c6-b9c6-5821-82d5-fc94eb99863b",
      "name": "Pause",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        2980,
        0
      ],
      "webhookId": "e68380de-d774-5ab3-a00b-98d6c2bf9ce0"
    }
  ],
  "connections": {
    "Run it now": {
      "main": [
        [
          {
            "node": "What to look for",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every Monday": {
      "main": [
        [
          {
            "node": "What to look for",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "What to look for": {
      "main": [
        [
          {
            "node": "Search the Meta Ad Library",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search the Meta Ad Library": {
      "main": [
        [
          {
            "node": "One item per ad",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "One item per ad": {
      "main": [
        [
          {
            "node": "Up to max_ads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Up to max_ads": {
      "main": [
        [
          {
            "node": "Tidy each ad",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tidy each ad": {
      "main": [
        [
          {
            "node": "Only pages with enough likes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Only pages with enough likes": {
      "main": [
        [
          {
            "node": "Only ads not seen before",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Only ads not seen before": {
      "main": [
        [
          {
            "node": "Loop over the ads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop over the ads": {
      "main": [
        [],
        [
          {
            "node": "What kind of ad",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "What kind of ad": {
      "main": [
        [
          {
            "node": "Watch the video",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Look at the image",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read the text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Watch the video": {
      "main": [
        [
          {
            "node": "Make the row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Look at the image": {
      "main": [
        [
          {
            "node": "Make the row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the text": {
      "main": [
        [
          {
            "node": "Make the row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Make the row": {
      "main": [
        [
          {
            "node": "Add to the sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add to the sheet": {
      "main": [
        [
          {
            "node": "Pause",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pause": {
      "main": [
        [
          {
            "node": "Loop over the ads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "active": false,
  "tags": []
}
