{
  "name": "Alert in Slack when new pages are still not indexed by Google (GSC Magic)",
  "nodes": [
    {
      "id": "c46989ce-fd88-4e0e-a1ed-b49d7a5e5e1e",
      "name": "Every day at 09:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "triggerAtHour": 9
            }
          ]
        }
      }
    },
    {
      "id": "c851d72f-5a36-496f-a180-96455fa05fd5",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        308,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b3ec14b3-771a-424e-a6ca-aa61b73a6cd2",
              "name": "site",
              "value": "example.com",
              "type": "string"
            },
            {
              "id": "53d9dd91-0f81-4e7e-aaf1-ccf783f4e2da",
              "name": "sitemapUrl",
              "value": "https://example.com/sitemap.xml",
              "type": "string"
            },
            {
              "id": "e1bb6a7b-bf12-4038-aad5-42ce04d002bf",
              "name": "checkAfterDays",
              "value": 3,
              "type": "number"
            },
            {
              "id": "0b79957d-3318-4a12-af89-6693879b7db1",
              "name": "giveUpAfterDays",
              "value": 30,
              "type": "number"
            },
            {
              "id": "761e8757-83fe-40be-a7c6-c7ffbaad2dae",
              "name": "maxUrlsPerRun",
              "value": 20,
              "type": "number"
            },
            {
              "id": "7a5701a4-9027-4072-a6a0-27c2de91f6bf",
              "name": "slackChannel",
              "value": "#seo-alerts",
              "type": "string"
            },
            {
              "id": "2f29a1f3-21ca-41a9-a892-fd9f9627b4e5",
              "name": "testUrl",
              "value": "",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "442a07a4-e85f-4a16-a567-f3a5def2bc3b",
      "name": "Download sitemap",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        616,
        0
      ],
      "parameters": {
        "url": "={{ $json.sitemapUrl }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "text",
              "outputPropertyName": "xml"
            }
          },
          "timeout": 60000
        }
      }
    },
    {
      "id": "67d9e94f-1742-441b-a39a-336224501af5",
      "name": "Find URLs due for a check",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        924,
        0
      ],
      "parameters": {
        "jsCode": "const cfg = $('Settings').first().json;\nconst xml = String($input.first().json.xml || '');\nconst DAY = 24 * 60 * 60 * 1000;\nconst now = Date.now();\n\nif (/<sitemapindex[\\s>]/i.test(xml)) {\n  throw new Error('sitemapUrl points to a sitemap index. Use one of the child sitemaps listed in it, e.g. post-sitemap.xml.');\n}\nconst decode = (s) => s.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '\"').replace(/&apos;/g, \"'\");\nconst inSitemap = [...xml.matchAll(/<loc>\\s*(?:<!\\[CDATA\\[)?\\s*([^<\\]\\s]+)/gi)].map((m) => decode(m[1]));\nif (!inSitemap.length && !cfg.testUrl) throw new Error('No <loc> entries found in ' + cfg.sitemapUrl);\n\n// Remembered between active runs: url -> { first, state: 'known' | 'pending' | 'alerted' | 'indexed' }\nconst store = $getWorkflowStaticData('global');\nconst firstRun = !store.urls;\nstore.urls = store.urls || {};\nconst seen = new Set(inSitemap);\n\nfor (const url of inSitemap) {\n  if (!store.urls[url]) store.urls[url] = { first: now, state: firstRun ? 'known' : 'pending' };\n}\nfor (const url of Object.keys(store.urls)) {\n  const entry = store.urls[url];\n  if (!seen.has(url)) delete store.urls[url];\n  else if ((entry.state === 'pending' || entry.state === 'alerted') && now - entry.first > cfg.giveUpAfterDays * DAY) entry.state = 'expired';\n}\n\nlet due = Object.entries(store.urls)\n  .filter(([, e]) => (e.state === 'pending' || e.state === 'alerted') && now - e.first >= cfg.checkAfterDays * DAY)\n  .sort((a, b) => a[1].first - b[1].first)\n  .map(([url]) => url);\n\nif (cfg.testUrl) due = [cfg.testUrl, ...due.filter((u) => u !== cfg.testUrl)];\ndue = due.slice(0, Math.min(20, Math.max(1, Number(cfg.maxUrlsPerRun) || 20)));\nif (!due.length) {\n  return [{ json: { skip: true, reason: firstRun\n    ? 'First run: recorded ' + inSitemap.length + ' URLs already in the sitemap. New URLs are checked from the next run on.'\n    : 'No new URL is due for a check (' + Object.values(store.urls).filter((e) => e.state === 'pending').length + ' waiting for ' + cfg.checkAfterDays + ' days).' } }];\n}\nreturn [{ json: { urls: due, firstRun } }];\n"
      }
    },
    {
      "id": "3d1eb2ae-bb18-4c50-a541-11aef169ddb2",
      "name": "GSC Magic: inspect due URLs",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1540,
        -20
      ],
      "onError": "continueRegularOutput",
      "parameters": {
        "method": "POST",
        "url": "https://mcp.gscmagic.com/mcp",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'gsc_inspect_urls_batch', arguments: { site: $('Settings').first().json.site, urls: $json.urls } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "2bd100f1-ebf8-4d6f-a60e-f5cfef6ba7de",
      "name": "Decide what to report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1848,
        -20
      ],
      "parameters": {
        "jsCode": "// Turns a GSC Magic response (MCP JSON-RPC) into { ok, data, error, image }.\nfunction unwrap(res) {\n  const result = res && res.result;\n  if (result && Array.isArray(result.content)) {\n    const text = result.content.filter((b) => b.type === 'text').map((b) => b.text).join('\\n');\n    if (result.isError) return { ok: false, error: text || 'GSC Magic reported an error' };\n    let data;\n    try { data = JSON.parse(text); } catch (e) { data = { text }; }\n    const image = result.content.find((b) => b.type === 'image' && b.data);\n    return { ok: true, data, image };\n  }\n  const err = res && res.error;\n  const message = typeof err === 'string' ? err : (err && (err.message || err.description)) || 'No response from GSC Magic';\n  if (/401|unauthori[sz]ed|Authorization failed/i.test(message)) {\n    return { ok: false, error: 'GSC Magic rejected the access token (wrong, expired or revoked). Create a new one in the GSC Magic dashboard: Connect > Access tokens.' };\n  }\n  return { ok: false, error: String(message) };\n}\n\nconst cfg = $('Settings').first().json;\nconst res = unwrap($input.first().json);\nif (!res.ok) {\n  return [{ json: { text: ':warning: *Indexing check failed* for ' + cfg.site + ': ' + res.error } }];\n}\n\nconst store = $getWorkflowStaticData('global');\nstore.urls = store.urls || {};\nconst DAY = 24 * 60 * 60 * 1000;\nconst newProblems = [];\nconst fixed = [];\nconst testLines = [];\n\nfor (const r of res.data.results || []) {\n  const entry = store.urls[r.url];\n  const indexed = r.verdict === 'PASS';\n  const isTest = r.url === cfg.testUrl;\n  const canonicalNote = r.googleCanonical && r.userCanonical && r.googleCanonical !== r.userCanonical\n    ? ' Google picked another canonical: ' + r.googleCanonical : '';\n  const line = '<' + r.url + '|' + r.url.replace(/^https?:\\/\\/[^/]+/, '') + '>: ' + (r.coverageState || r.error || 'unknown')\n    + (r.lastCrawlTime ? ', last crawl ' + r.lastCrawlTime.slice(0, 10) : ', never crawled') + '.' + canonicalNote;\n\n  if (isTest) testLines.push((indexed ? ':large_green_circle: ' : ':red_circle: ') + line);\n  if (indexed) {\n    if (entry && entry.state === 'alerted') fixed.push(line);\n    if (entry) entry.state = 'indexed';\n  } else {\n    const age = entry ? Math.floor((Date.now() - entry.first) / DAY) : null;\n    if (entry && entry.state !== 'alerted') newProblems.push(line + (age !== null ? ' In the sitemap for ' + age + ' days.' : ''));\n    if (entry) entry.state = 'alerted';\n  }\n}\n\nconst skipped = (res.data.requested || 0) - (res.data.inspected || 0);\nif (!newProblems.length && !fixed.length && !testLines.length && skipped <= 0) {\n  return [{ json: { skip: true, reason: 'Checked ' + (res.data.results || []).length + ' URLs; nothing changed since the last report.' } }];\n}\n\nconst lines = ['*Indexing watchdog* for ' + cfg.site];\nif (newProblems.length) lines.push('', ':red_circle: *Not indexed yet* (' + newProblems.length + ')', ...newProblems.map((l) => '- ' + l));\nif (testLines.length) lines.push('', '*Test URL* (from Settings > testUrl)', ...testLines);\nif (fixed.length) lines.push('', ':large_green_circle: *Now indexed* (' + fixed.length + ')', ...fixed.map((l) => '- ' + l));\nif (skipped > 0) lines.push('', '_' + skipped + ' URLs were not inspected (daily URL Inspection quota). They are retried tomorrow._');\nif (newProblems.length || testLines.some((l) => l.startsWith(':red_circle:'))) lines.push('', '_What to do: \"Discovered\" or \"unknown\" usually means weak internal links; \"Crawled, currently not indexed\" usually means Google did not find the page useful enough yet._');\nreturn [{ json: { text: lines.join('\\n') } }];\n"
      }
    },
    {
      "id": "52305453-2f69-435f-a838-6fc583375de6",
      "name": "Post to Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        2464,
        -40
      ],
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Settings').first().json.slackChannel }}"
        },
        "text": "={{ $json.text }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      }
    },
    {
      "id": "73f814e4-1807-4963-af88-ea8b2534f495",
      "name": "Any URL due?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1232,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "b928eb32-0954-426c-a48a-a327cd453a61",
              "leftValue": "={{ $json.skip === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "3f41b6e0-7928-4038-a8a5-38e86efc87c9",
      "name": "Nothing to check today",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1232,
        200
      ],
      "parameters": {}
    },
    {
      "id": "34e59b5d-fb8c-4667-ac75-6f175e246b6e",
      "name": "Anything to report?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2156,
        -20
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "6c1fcf54-fc7f-445e-a849-5bfcbc721c92",
              "leftValue": "={{ $json.skip === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "cb3bfa99-740b-47df-a2e1-5d820aecca48",
      "name": "No change to report",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        2156,
        180
      ],
      "parameters": {}
    },
    {
      "id": "7edbd534-615a-42a5-a0ba-c9ef02e5a7e2",
      "name": "Step 1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -373
      ],
      "parameters": {
        "content": "## Step 1: Configure\n- **site**: the Search Console property or domain.\n- **sitemapUrl**: a plain sitemap (`<urlset>`). For a sitemap index, use the child sitemap that holds your posts, e.g. `post-sitemap.xml`. Gzipped sitemaps are not supported.\n- **checkAfterDays**: how long Google gets before the first check.\n- **giveUpAfterDays**: stop checking a URL after this many days.\n- **maxUrlsPerRun**: inspections per run, at most 20 (Google checks about one URL every 7 seconds and a GSC Magic request is cut after 3 minutes). The rest wait for the next day.\n- **testUrl**: inspect this URL now and report it, for testing.",
        "width": 488,
        "height": 763,
        "color": 7
      }
    },
    {
      "id": "aa4b585a-76e1-4dee-afb8-3f447370a56a",
      "name": "Step 2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        576,
        -373
      ],
      "parameters": {
        "content": "## Step 2: Track new sitemap URLs\nDownloads the sitemap, remembers when each URL first appeared and picks the ones older than `checkAfterDays`. A quiet day ends on **Nothing to check today**.",
        "width": 796,
        "height": 763,
        "color": 7
      }
    },
    {
      "id": "6d57ccef-9ebd-42af-aa1f-48e286a706cc",
      "name": "Step 3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1500,
        -373
      ],
      "parameters": {
        "content": "## Step 3: Ask Google\nOne batch URL Inspection call. Each URL is reported once when it is not indexed and once when it gets indexed, never twice.",
        "width": 796,
        "height": 763,
        "color": 7
      }
    },
    {
      "id": "4e5b77d5-d454-4245-a6b0-82cbddd4ac9a",
      "name": "Step 4",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2374,
        -373
      ],
      "parameters": {
        "content": "## Step 4: Alert in Slack\nPosts what changed, with Google's reason and the last crawl date.",
        "width": 280,
        "height": 763,
        "color": 7
      }
    },
    {
      "id": "08b6b435-099b-466b-ad98-9003c66aed53",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -740,
        -373
      ],
      "parameters": {
        "content": "## New page indexing watchdog\nPublishing a page does not mean Google indexed it. This workflow watches your sitemap, waits a few days after a URL first appears, asks Google's URL Inspection API whether it is indexed and tells you in Slack when it is not. It also tells you when a page it warned about gets indexed later.\n\n**Who it is for:** content teams, publishers and agencies who publish often and find out weeks later that a page never made it into Google.\n\n**How it works**\n1. Every day it downloads the sitemap and remembers when each URL first appeared (n8n workflow static data).\n2. URLs older than `checkAfterDays` are inspected in one batch call.\n3. Not indexed: one alert with Google's reason (crawled but not indexed, discovered, unknown, duplicate canonical). Indexed later: one follow-up.\n4. A URL stops being checked after `giveUpAfterDays`, and is forgotten when it leaves the sitemap.\n\n**Connect GSC Magic** (about 2 minutes)\n1. In the [GSC Magic dashboard](https://app.gscmagic.com) open **Connect > Access tokens** and create a token. Copy the `gsm_...` value (shown once).\n2. Open the first node whose name starts with **GSC Magic:**, and under **Credential for Bearer Auth** create a new credential. Paste the token into **Bearer Token**. In every other **GSC Magic:** node, select that same credential.\n3. Never paste the token into a URL, a prompt or a Code node.\n\n**Then**\n4. Fill in **Settings** and add a Slack credential to **Post to Slack**.\n5. To test, put one of your URLs into `testUrl` and click **Execute workflow**. Empty `testUrl` again before you activate.\n\n**Important:** the first active run only records the URLs already in the sitemap, it does not inspect them. n8n saves static data only for active (production) runs, not for manual test runs.\n\nSchedule times use the workflow time zone (Workflow settings > Timezone), which defaults to the instance time zone.\n\n**Calls per run:** 0 or 1 (one batch call). Each URL uses one URL Inspection request from Google's quota of 2,000 a day per property.\n\n### Errors and limits\n- A quiet day ends on **Nothing to check today** or **No change to report**; the node before it says why.\n- A broken sitemap URL or a sitemap index stops the run with a clear error.\n- A GSC Magic failure (token, plan limit, Google quota) is posted to Slack instead of the report.\n- Each URL is reported once when it fails and once when it gets indexed, so repeated runs do not repeat alerts.\n- The verdict comes from Google's URL Inspection API, which can lag a day behind what Search Console shows.",
        "width": 640,
        "height": 1045
      }
    }
  ],
  "connections": {
    "Every day at 09:00": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Download sitemap",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download sitemap": {
      "main": [
        [
          {
            "node": "Find URLs due for a check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find URLs due for a check": {
      "main": [
        [
          {
            "node": "Any URL due?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Any URL due?": {
      "main": [
        [
          {
            "node": "GSC Magic: inspect due URLs",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Nothing to check today",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: inspect due URLs": {
      "main": [
        [
          {
            "node": "Decide what to report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide what to report": {
      "main": [
        [
          {
            "node": "Anything to report?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Anything to report?": {
      "main": [
        [
          {
            "node": "Post to Slack",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "No change to report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "active": false
}
