{ "name": "Niche trend content planner: rising Google Trends searches to content ideas", "nodes": [ { "parameters": { "content": "## Niche trend content planner\n\n### How it works\nFor creators, marketers and agencies who want content ideas backed by real search demand. Someone describes what they make content about, in any words, through a web form, a weekly Google Sheet or a test run. Gemini turns that into Google Trends search terms, the Apify node fetches what is rising around them, bot and prompt-like searches are dropped, and Gemini writes each idea with a hook, an angle, why it is rising and what to fact-check. Results go to a web page, or to Google Sheets with a Slack or Telegram summary. If an AI step fails, you get the list of rising searches instead. Limits: Trends growth is relative, not volume, and ideas need a fact-check before publishing.\n\n### Setup\n1. Install the verified community node `@apify/n8n-nodes-apify` (tested with 0.9.0 on n8n 2.44): [installation guide](https://docs.n8n.io/integrations/community-nodes/installation/).\n2. **Google Trends** node: create an Apify credential. n8n Cloud: sign in. Self-hosted: set Authentication to API Key first.\n3. **Gemini model** node: add a Google Gemini API key (free in Google AI Studio).\n4. Test: click ▶ on **Run it now**, then open **Weekly summary**.\n5. Form: publish, then share the **Form** node's Production URL.\n6. Weekly sheet (optional): pick your sheet in **Read keyword sheet** (tab `Keywords`) and **Add to Google Sheet** (tab `Ideas`), then turn that node on. Slack and Telegram are optional too.\n\n### Customization\nChange ideas per niche, minimum relevance, country and time range in **Defaults**. Edit the prompt in **Prepare AI request** for scripts or newsletters, or swap Gemini for any chat model.", "width": 660, "height": 900, "color": 1 }, "id": "2ac150c3-0edb-5f8b-bd47-6541cfb76ab7", "name": "Overview", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ -1300, -600 ] }, { "parameters": { "content": "## Web form intake\nOn demand: one free-form question, or a CSV with one row per niche. Results show on the next page.", "width": 700, "height": 290, "color": 7 }, "id": "a40e317d-8be8-5125-9652-6eb391827a80", "name": "Web form intake", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ -600, -600 ] }, { "parameters": { "content": "## Weekly sheet intake\nEvery Monday, reads one row per niche from the `Keywords` tab.", "width": 700, "height": 290, "color": 7 }, "id": "12535d20-794d-56f7-b4d0-daac24556cf6", "name": "Weekly sheet intake", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ -600, -300 ] }, { "parameters": { "content": "## Test run\nRuns the sample request in Test input, so you can check the setup.", "width": 700, "height": 300, "color": 7 }, "id": "c49f830d-e7fe-579f-aada-88c529dee0cf", "name": "Test run", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ -600, 0 ] }, { "parameters": { "content": "## Plan search terms\nGemini turns the request into Google Trends terms: keeps searchable topics, rewrites vague ones, adds more. Settings live in Defaults.", "width": 1360, "height": 900, "color": 7 }, "id": "2bdcdd62-7db3-5fbc-8205-b0230dc4b55e", "name": "Plan search terms", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 140, -600 ] }, { "parameters": { "content": "## Fetch Google Trends data\nGets rising searches and topics for each term. Niches with the same country and time range share a call.", "width": 1100, "height": 900, "color": 7 }, "id": "6b8d5acf-c722-5e14-a771-c141d04587e1", "name": "Fetch Google Trends data", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 1520, -600 ] }, { "parameters": { "content": "## Connect Apify here\nCloud: sign in. Self-hosted: set Authentication to API Key, then paste your token.", "width": 230, "height": 360, "color": 3 }, "id": "ab3c9a1d-52b4-5d3f-828f-f4e2ce5445a8", "name": "Connect Apify here", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 2170, -230 ] }, { "parameters": { "content": "## Pick and write ideas\nDrops bot and prompt-like searches, ranks the rest, and Gemini writes the ideas. If AI fails, the rising searches list is used.", "width": 1320, "height": 900, "color": 7 }, "id": "7c59ad33-fa8f-5a65-961c-de506583a9e7", "name": "Pick and write ideas", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 2640, -600 ] }, { "parameters": { "content": "## Deliver results\nForm runs get a results page. Sheet and test runs get idea rows and a summary for Slack or Telegram.", "width": 1000, "height": 900, "color": 7 }, "id": "b42d4ed6-0e38-5ef9-8c94-9fce5db31ff3", "name": "Deliver results", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 3980, -600 ] }, { "parameters": { "formTitle": "Find your next content ideas", "formDescription": "Tell us what you want to make content about. We'll find what people are starting to search for on Google and turn it into ideas you can post. Takes about 2 minutes.", "formFields": { "values": [ { "fieldLabel": "What do you want to make content about?", "fieldName": "niche", "fieldType": "textarea", "requiredField": false, "placeholder": "In any words, e.g. \"home espresso\" or \"skincare for beginners, mostly retinol and acne scars\"" }, { "fieldLabel": "Where do you want to post?", "fieldName": "formats", "fieldType": "checkbox", "requiredField": false, "fieldOptions": { "values": [ { "option": "Blog" }, { "option": "YouTube" }, { "option": "Shorts / Reels / TikTok" }, { "option": "Instagram carousel" }, { "option": "Newsletter" }, { "option": "LinkedIn" }, { "option": "Podcast" }, { "option": "X (Twitter)" } ] } }, { "fieldLabel": "Where do you want to reach people?", "fieldName": "country", "fieldType": "dropdown", "requiredField": false, "fieldOptions": { "values": [ { "option": "Worldwide" }, { "option": "United States (US)" }, { "option": "United Kingdom (GB)" }, { "option": "Canada (CA)" }, { "option": "Australia (AU)" }, { "option": "India (IN)" }, { "option": "Germany (DE)" }, { "option": "France (FR)" }, { "option": "Spain (ES)" }, { "option": "Italy (IT)" }, { "option": "Netherlands (NL)" }, { "option": "Brazil (BR)" }, { "option": "Mexico (MX)" }, { "option": "Japan (JP)" }, { "option": "South Korea (KR)" }, { "option": "Singapore (SG)" }, { "option": "South Africa (ZA)" }, { "option": "UAE (AE)" } ] } }, { "fieldLabel": "How recent should the trends be?", "fieldName": "timeRange", "fieldType": "dropdown", "requiredField": false, "fieldOptions": { "values": [ { "option": "Last 30 days (recommended)" }, { "option": "Last 7 days, for fast-moving topics" }, { "option": "Last 3 months, for slower niches" }, { "option": "Last 12 months" } ] } }, { "fieldLabel": "Bulk upload help", "fieldName": "bulkHelp", "fieldType": "html", "requiredField": false, "html": "
Several niches at once? Upload a CSV with one row per niche. Only niche is needed, written any way you like. You can add topics (separated by commas), audience and country (two-letter code). Each niche gets its own ideas.
niche,topics,country
skincare for beginners,\"retinol, acne scars\",US
home espresso,,US
Download a template. It takes about 2 minutes per niche, so for more than 5 the Google Sheet version is a better fit.
" }, { "fieldLabel": "Your CSV file", "fieldName": "csv", "fieldType": "file", "requiredField": false, "multipleFiles": false, "acceptFileTypes": ".csv" } ] }, "responseMode": "lastNode", "options": { "buttonLabel": "Get my content ideas", "appendAttribution": false, "path": "rising-in-my-niche" } }, "id": "7c659329-229e-5450-ac2b-fec257fdf670", "name": "Form", "type": "n8n-nodes-base.formTrigger", "typeVersion": 2.6, "position": [ -520, -460 ], "webhookId": "ff42ce3b-a31d-5745-96f6-a03131e55e80" }, { "parameters": { "jsCode": "// Web form -> rows. One free-form answer (niche, topics, audience in any words) and/or a CSV for several niches\n// (one row per niche: niche, topics, audience, country). Questions left empty are filled from Defaults.\nconst f = $input.first();\nconst j = f.json;\nconst get = (...names) => { for (const n of names) if (j[n] !== undefined && j[n] !== '') return j[n]; return ''; };\nconst TIME = { 'Last 7 days': 'now 7-d', 'Last 30 days': 'today 1-m', 'Last 3 months': 'today 3-m', 'Last 12 months': 'today 12-m' };\nconst timeOf = v => { const k = Object.keys(TIME).find(t => String(v || '').startsWith(t)); return k ? TIME[k] : null; };\n// \"Worldwide\" = '' (explicit); nothing chosen = null (Defaults); \"India (IN)\" or \"IN\" = the code\nconst countryOf = v => { const s = String(v || '').trim(); if (!s) return null; if (/^worldwide$/i.test(s)) return '';\n const m = s.match(/\\(([A-Z]{2})\\)\\s*$/); return m ? m[1] : (/^[A-Za-z]{2}$/.test(s) ? s.toUpperCase() : null); };\nconst splitTopics = v => String(v || '').split(/[,;|\\n]+/).map(t => t.trim()).filter(Boolean);\n// one bulk row -> one planner row per topic it lists (or one row for a niche with no topics)\nconst bulkRows = (row, base) => {\n const niche = String(row.niche || row.topic || row.group || '').trim() || base.niche;\n const topics = [...splitTopics(row.topics || row.subtopics), ...splitTopics(row.keyword || row.keywords || row.term)];\n if (!niche && !topics.length) return [];\n return (topics.length ? topics : ['']).map(keyword => ({ ...base, niche, keyword,\n audience: String(row.audience || '').trim() || base.audience || '',\n country: row.country ? (countryOf(row.country) ?? base.country) : base.country,\n formats: row.formats || row['publish on'] || row.platforms || base.formats || null }));\n};\nconst formats = [].concat(get('formats', 'Where do you want to post?') || []).join(', ').toLowerCase() || null;\nconst base = {\n niche: String(get('niche', 'What do you want to make content about?')).trim(),\n audience: '',\n country: countryOf(get('country', 'Where do you want to reach people?')),\n timeRange: timeOf(get('timeRange', 'How recent should the trends be?')),\n formats, source: 'form',\n};\nconst rows = [];\n\n// optional CSV upload: one row per niche\nconst file = Object.keys(f.binary || {})[0];\nif (file) {\n const text = (await this.helpers.getBinaryDataBuffer(0, file)).toString('utf8').replace(/^/, '');\n const lines = text.split(/\\r?\\n/).filter(l => l.trim());\n const sep = (lines[0].match(/;/g) || []).length > (lines[0].match(/,/g) || []).length ? ';' : ',';\n const cells = l => { const out = []; let cur = '', q = false;\n for (let i = 0; i < l.length; i++) { const c = l[i];\n if (q) { if (c === '\"' && l[i + 1] === '\"') { cur += '\"'; i++; } else if (c === '\"') q = false; else cur += c; }\n else if (c === '\"') q = true; else if (c === sep) { out.push(cur); cur = ''; } else cur += c; }\n out.push(cur); return out.map(x => x.trim()); };\n const head = cells(lines[0]).map(h => h.toLowerCase());\n if (!head.some(h => ['niche', 'topic', 'group', 'keyword', 'keywords', 'topics'].includes(h)))\n throw new Error('The CSV needs a \"niche\" column (one row per niche), and optionally topics, audience, country.');\n for (const l of lines.slice(1)) {\n const c = cells(l);\n rows.push(...bulkRows(Object.fromEntries(head.map((h, i) => [h, c[i] || ''])), { ...base, niche: '' }));\n }\n}\n// what they typed is one more niche, unless the CSV already has it\nif (base.niche && !rows.some(r => r.niche.toLowerCase() === base.niche.toLowerCase())) rows.unshift({ ...base, keyword: '' });\nif (!rows.length) throw new Error('Tell us what you want to make content about, or upload a CSV with a \"niche\" column.');\nreturn rows.map(json => ({ json }));" }, "id": "e33f7e94-45ba-58b1-841e-a33619a93af6", "name": "Read form answers", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ -280, -460 ] }, { "parameters": { "rule": { "interval": [ { "field": "weeks", "triggerAtDay": [ 1 ], "triggerAtHour": 8 } ] } }, "id": "03fef9d0-fce4-5c1e-ba37-9b82d81c6e82", "name": "Every Monday at 8:00", "type": "n8n-nodes-base.scheduleTrigger", "typeVersion": 1.2, "position": [ -520, -160 ] }, { "parameters": { "documentId": { "__rl": true, "mode": "url", "value": "" }, "sheetName": { "__rl": true, "mode": "name", "value": "Keywords" }, "options": {} }, "id": "55e9cfb6-a311-5d60-9a9e-17b9b57c0a87", "name": "Read keyword sheet", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [ -280, -160 ] }, { "parameters": { "jsCode": "// Google Sheet -> rows. Same shape as the form's CSV, one row per niche (any order, any case):\n// niche (required, any words) · topics (optional, separated by commas) · audience · country · formats ·\n// active (\"no\" pauses the row). A \"keyword\" column with one topic per row works too.\n// Rows without a niche are skipped and reported in the summary.\nconst countryOf = v => /^[A-Za-z]{2}$/.test(String(v || '').trim()) ? String(v).trim().toUpperCase() : null;\nconst splitTopics = v => String(v || '').split(/[,;|\\n]+/).map(t => t.trim()).filter(Boolean);\n// one bulk row -> one planner row per topic it lists (or one row for a niche with no topics)\nconst bulkRows = (row, base) => {\n const niche = String(row.niche || row.topic || row.group || '').trim() || base.niche;\n const topics = [...splitTopics(row.topics || row.subtopics), ...splitTopics(row.keyword || row.keywords || row.term)];\n if (!niche && !topics.length) return [];\n return (topics.length ? topics : ['']).map(keyword => ({ ...base, niche, keyword,\n audience: String(row.audience || '').trim() || base.audience || '',\n country: row.country ? (countryOf(row.country) ?? base.country) : base.country,\n formats: row.formats || row['publish on'] || row.platforms || base.formats || null }));\n};\nconst rows = [], skipped = [];\nfor (const { json: r } of $input.all()) {\n const row = Object.fromEntries(Object.entries(r).map(([k, v]) => [String(k).trim().toLowerCase(), String(v ?? '').trim()]));\n if (/^(no|false|0|off|paused)$/i.test(row.active || '')) continue;\n if (!row.niche) { const t = row.topics || row.keyword || row.keywords || ''; if (t) skipped.push(t); continue; }\n // null = not given here: filled from Defaults\n rows.push(...bulkRows(row, { niche: '', audience: '', country: null, timeRange: null, formats: null, source: 'sheet' })\n .map(x => ({ ...x, skipped })));\n}\nif (!rows.length) throw new Error('No usable rows in the sheet: it needs a \"niche\" column (one row per niche).');\nreturn rows.map(json => ({ json }));" }, "id": "7510a0e8-1082-5a08-859e-b512155534f0", "name": "Read sheet rows", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ -60, -160 ] }, { "parameters": {}, "id": "6e0ad1f3-d478-5e8a-bc98-f61d460fc558", "name": "Run it now", "type": "n8n-nodes-base.manualTrigger", "typeVersion": 1, "position": [ -520, 140 ] }, { "parameters": { "assignments": { "assignments": [ { "id": "fe08c589-af93-5f34-a395-6befdd1734b4", "name": "contentAbout", "value": "skincare for beginners who want simple, honest advice. Mostly retinol, sunscreen and niacinamide, and how to deal with acne scars", "type": "string" }, { "id": "eca009d7-9d6c-5a30-a2f0-2bbfaa5349ac", "name": "country", "value": "US", "type": "string" } ] }, "options": {} }, "id": "0b0a1aad-1c9f-5e60-9541-c1f77dcd508c", "name": "Test input", "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [ -280, 140 ] }, { "parameters": { "jsCode": "// \"Run it now\" test input -> one row: what you'd type in the form's first box.\nconst m = $input.first().json;\nreturn [{ json: { niche: String(m.contentAbout || '').trim(), keyword: '', audience: '',\n country: m.country == null ? null : String(m.country).toUpperCase(), timeRange: null, formats: null, source: 'manual' } }];" }, "id": "3df40af7-d0ce-53c8-b4d5-baf68319ef70", "name": "Read test input", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ -60, 140 ] }, { "parameters": { "assignments": { "assignments": [ { "id": "cd667bd8-22d7-5761-9a68-371eab6e565f", "name": "ideasPerNiche", "value": 10, "type": "number" }, { "id": "b3c4b423-bbc9-54fe-9e56-7818cf1b9aac", "name": "minRelevance", "value": 6, "type": "number" }, { "id": "e8b3efd7-23d4-5228-b4a4-a603c72b2c38", "name": "topicsPerNiche", "value": 8, "type": "number" }, { "id": "e88ec187-7ca2-55f3-b889-51b44f22b928", "name": "maxTopicsPerNiche", "value": 12, "type": "number" }, { "id": "cc11c525-8dda-5156-afa2-465bb2286627", "name": "includeTopics", "value": true, "type": "boolean" }, { "id": "e7e1e2ed-f3dc-5647-909b-c5760e6c8748", "name": "defaultCountry", "value": "US", "type": "string" }, { "id": "e6c2fa84-e938-5bd9-b29f-e105166a78f1", "name": "defaultTimeRange", "value": "today 1-m", "type": "string" }, { "id": "60b306bc-5653-552c-908f-e99c17e0afda", "name": "defaultFormats", "value": "blog post, short video, carousel, newsletter", "type": "string" }, { "id": "9f6816e4-b355-5101-9e28-a7c24c4c472c", "name": "maxKeywordsPerRun", "value": 300, "type": "number" } ] }, "options": {}, "includeOtherFields": true }, "id": "458c5db4-f53d-5a40-8476-46d9863f3804", "name": "Defaults", "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [ 200, -220 ] }, { "parameters": { "jsCode": "// Rows -> one item per niche (+ country + time range): what the person wrote, plus any topics they listed. What an input\n// didn't give (null) comes from Defaults; an explicit value (even \"worldwide\" = '') is kept.\nconst d = $('Defaults').first().json;\nconst rows = $input.all().map(({ json: r }) => ({ ...r,\n niche: String(r.niche || '').trim(),\n keyword: String(r.keyword || '').trim(),\n country: r.country ?? d.defaultCountry ?? '',\n timeRange: r.timeRange ?? d.defaultTimeRange,\n formats: r.formats || d.defaultFormats }));\nconst groups = new Map();\nfor (const r of rows) {\n if (!r.niche) throw new Error(`\"${r.keyword}\" has no niche. Every topic needs a niche (what you want to make content about).`);\n const group = `${r.niche.toLowerCase()}|${r.country}|${r.timeRange}`;\n const g = groups.get(group) ?? { group, about: r.niche, niche: r.niche, audience: '', country: r.country,\n timeRange: r.timeRange, formats: new Set(), source: r.source, skipped: r.skipped || [], given: [] };\n if (!g.audience && r.audience) g.audience = r.audience;\n String(r.formats).split(',').map(s => s.trim()).filter(Boolean).forEach(x => g.formats.add(x));\n if (r.keyword && !g.given.some(k => k.toLowerCase() === r.keyword.toLowerCase())) g.given.push(r.keyword);\n groups.set(group, g);\n}\nconst max = Number(d.maxKeywordsPerRun) || 300;\nconst perNiche = Math.max(Number(d.maxTopicsPerNiche) || 12, 1);\nif (groups.size * perNiche > max) throw new Error(`This run could search up to ${groups.size * perNiche} topics; `\n + `the limit is ${max} (maxKeywordsPerRun in Defaults). Plan fewer niches at once.`);\nreturn [...groups.values()].map((g, i) => ({ json: { ...g, id: `K${i + 1}`, formats: [...g.formats].join(', ') } }));" }, "id": "7b7c5605-ea06-5cd6-b5be-586977664d48", "name": "Group by niche", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 420, -220 ] }, { "parameters": { "jsCode": "// The AI reads what the person wrote (any words) and plans the search terms to watch. A search term is a seed: Google\n// reports what rises around it, so a good one is a concrete thing people search all the time. People describe a niche\n// (\"ai product roadmap\") differently from how they search it (\"cursor\", \"vibe coding\"), and described phrases have\n// almost no Google data, so their own topics are judged: kept when searchable, turned into search terms when not.\nconst d = $('Defaults').first().json;\nconst want = Math.max(3, Number(d.topicsPerNiche) || 8);\nconst max = Math.max(want, Number(d.maxTopicsPerNiche) || 12);\nreturn $input.all().map(({ json: g }) => ({ json: { ...g, prompt: [\n `Someone wants content ideas from what is rising on Google. This is what they wrote, between the lines:`,\n `---`, g.about, `---`,\n g.given.length ? `Topics they listed: ${g.given.map(t => `\"${t}\"`).join(', ')}.` : null,\n g.audience ? `Who it's for, as they put it: ${g.audience}.` : null,\n `Country: ${g.country || 'worldwide'}.`,\n ``,\n `Return:`,\n `- niche: their niche in 2 to 6 plain words, e.g. \"skincare for beginners\".`,\n `- audience: who it's for, if they said so or it's clearly implied; otherwise \"\".`,\n `- topics: the search terms to watch on Google Trends for them, about ${want} and never more than ${max}.`,\n ` First judge every topic they mentioned, in what they wrote or in the list:`,\n ` - \"kept\": it is already something people type into Google (1 to 3 words, concrete: a product, brand, ingredient, tool, technique or problem). Keep it exactly as they wrote it.`,\n ` - \"rewritten\": it's a description or a long phrase (\"retinol for teens\", \"how PMs should prototype with AI\"). Turn it into the 1 or 2 search terms that carry what they meant (\"retinol\", \"teen acne\"), and put their words in \"from\".`,\n ` - leave a topic out only when it has nothing to do with their niche, and list it in \"dropped\" with a short reason.`,\n ` Then add \"added\" terms until there are about ${want}: what this audience actually searches, a mix of core topics, popular products or brands, and common problems.`,\n ` Every term: plain search language, 1 to 3 words, searched often enough to have Google data in this country. Never a description of the niche and never the niche name itself.`, ``,\n `Set \"nicheId\" to \"${g.id}\".`,\n].filter(l => l !== null).join('\\n') } }));" }, "id": "c051f7f4-3ff2-52fd-babd-89dc263b276a", "name": "Ask AI to plan topics", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 640, -220 ] }, { "parameters": { "promptType": "define", "text": "={{ $json.prompt }}", "hasOutputParser": true, "messages": { "messageValues": [ { "type": "SystemMessagePromptTemplate", "message": "You are a search researcher. You read what a creator wants, in whatever words they use, and turn it into the short, concrete terms ordinary people type into Google. You respect their topics: you keep the ones that are already searchable and translate the rest, and you never use marketing language." } ] }, "batching": {} }, "id": "1844dc6d-a932-585b-9bdb-6977fd6e68da", "name": "Plan topics", "type": "@n8n/n8n-nodes-langchain.chainLlm", "typeVersion": 1.9, "position": [ 880, -220 ], "onError": "continueErrorOutput", "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 5000 }, { "parameters": { "schemaType": "manual", "inputSchema": "{\n \"type\": \"object\",\n \"properties\": {\n \"nicheId\": {\n \"type\": \"string\"\n },\n \"niche\": {\n \"type\": \"string\"\n },\n \"audience\": {\n \"type\": \"string\"\n },\n \"topics\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"term\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"kept\",\n \"rewritten\",\n \"added\"\n ]\n },\n \"from\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"term\",\n \"status\"\n ]\n }\n },\n \"dropped\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\n \"type\": \"string\"\n },\n \"reason\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"text\",\n \"reason\"\n ]\n }\n }\n },\n \"required\": [\n \"nicheId\",\n \"niche\",\n \"audience\",\n \"topics\"\n ]\n}", "autoFix": false }, "id": "870938b2-c282-5e3b-af0d-32982ccac5ad", "name": "Topic plan", "type": "@n8n/n8n-nodes-langchain.outputParserStructured", "typeVersion": 1.3, "position": [ 980, 20 ] }, { "parameters": { "jsCode": "// The AI's plan -> the niche's name, audience and search terms, with where each term came from (shown in the results).\nconst d = $('Defaults').first().json;\nconst max = Math.max(Math.max(3, Number(d.topicsPerNiche) || 8), Number(d.maxTopicsPerNiche) || 12);\nconst asked = $('Ask AI to plan topics').all().map(p => p.json);\nconst clean = k => String(k || '').trim().replace(/^[\"'“”]+|[\"'“”.]+$/g, '').replace(/\\s+/g, ' ').toLowerCase();\nreturn $input.all().map((item, i) => {\n const out = item.json.output || {};\n const g = asked.find(p => p.id === out.nicheId) ?? asked[item.pairedItem?.item] ?? asked[i];\n const niche = String(out.niche || '').trim() || g.about;\n const origin = {}, keywords = [];\n for (const t of out.topics || []) {\n const term = clean(t.term);\n if (!term || term.split(' ').length > 4 || term === niche.toLowerCase() || origin[term]) continue;\n origin[term] = t.status === 'rewritten' && t.from ? `from \"${String(t.from).trim()}\"` : t.status === 'kept' ? 'yours' : 'added';\n keywords.push(term);\n }\n const dropped = (out.dropped || []).filter(x => x && x.text).map(x => `${x.text} (${x.reason || 'not about this niche'})`);\n const { prompt, ...rest } = g;\n return { json: { ...rest, niche, audience: String(out.audience || '').trim() || g.audience,\n keywords: (keywords.length ? keywords : [g.about]).slice(0, max), topicOrigin: origin,\n keywordNote: dropped.length ? `We left out: ${dropped.join('; ')}.` : '' } };\n});" }, "id": "5a3c61b4-f13e-5fb3-8306-36c031b1d987", "name": "Use planned topics", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1120, -340 ] }, { "parameters": { "jsCode": "const reasonFor = error => { const raw = String(error?.message || error || 'unknown error');\n return /402|payment|credit|billing|prepay|exhausted/i.test(raw) ? 'the AI account is out of credit'\n : /bad request|api key|401|403|permission|credential/i.test(raw) ? 'the AI key or model name needs checking'\n : /429|quota|rate/i.test(raw) ? 'the AI service is busy, try again soon' : raw.slice(0, 120); };\n\n// The planner failed: search what the person wrote, split into short terms (their listed topics first), and say why.\nreturn $input.all().map(item => {\n const { prompt, error, ...g } = item.json;\n // split on punctuation and joining words, drop lead-ins (\"how to deal with\", \"I post videos about\"), keep short parts\n const LEAD = /^(i|we)\\s+(make|post|run|write|create|do)\\b.*?\\babout\\s+|^(mostly|especially|including|like|also|plus|how to( deal with| get rid of)?|tips (on|for)|want to cover|cover)\\s+/i;\n const segments = g.about.split(/[\\n,;:.!?()]+|\\b(?:and|or|mostly|especially|including|such as)\\b/i)\n .map(s => (s || '').trim().replace(LEAD, '').replace(LEAD, '').trim().toLowerCase()).filter(Boolean);\n const parts = segments.filter(s => s.split(/\\s+/).length <= 4);\n const keywords = [...new Set([...g.given.map(k => k.toLowerCase()), ...parts])];\n const first = segments[0] || g.about;\n return { json: { ...g, niche: first.split(/\\s+/).length <= 6 ? first : `${first.split(/\\s+/).slice(0, 5).join(' ')}...`,\n keywords: keywords.length ? keywords : [first.split(/\\s+/).slice(0, 4).join(' ')], topicOrigin: {},\n keywordNote: `We couldn't plan topics with AI this time (${reasonFor(error)}), so we searched what you wrote as it is. `\n + 'Results are usually much better when the AI can plan them.' } };\n});" }, "id": "ec0fb567-245f-5927-b0cb-f329dadcc0c8", "name": "Plan without AI", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1120, -100 ] }, { "parameters": { "numberInputs": 2 }, "id": "63b3b867-00ed-59a6-a0f5-0729ba2faf30", "name": "Merge planned niches", "type": "n8n-nodes-base.merge", "typeVersion": 3.2, "position": [ 1340, -220 ] }, { "parameters": { "jsCode": "// Niches -> Google Trends jobs, in chunks of 40 keywords so each call stays short. Two requests the AI read as the same\n// niche (the typed answer and CSV rows, say) become one, so the results don't show it twice.\nconst CHUNK = 40;\nconst byName = new Map();\nfor (const { json: g } of $input.all()) {\n const key = `${g.niche.toLowerCase()}|${g.country}|${g.timeRange}`;\n const same = byName.get(key);\n if (!same) { byName.set(key, { ...g, keywords: [...g.keywords], topicOrigin: { ...g.topicOrigin } }); continue; }\n for (const k of g.keywords) if (!same.keywords.includes(k)) { same.keywords.push(k); same.topicOrigin[k] = g.topicOrigin[k]; }\n same.keywordNote = [same.keywordNote, g.keywordNote].filter(Boolean).join(' ');\n if (!same.audience) same.audience = g.audience;\n if (g.about.length > same.about.length) same.about = g.about; // keep the fullest description of what they want\n}\n// Bulk runs: niches with the same country and time range share Google Trends calls (whole niches packed into calls of\n// up to 40 terms), so ten niches take a few calls instead of ten. Collect routes each term's results back to its niches.\nconst jobs = [];\nfor (const g of byName.values()) {\n const niche = { ...g, keywordsUsed: g.keywords.slice(0, CHUNK) };\n const open = jobs.find(j => j.country === g.country && j.timeRange === g.timeRange\n && new Set([...j.keywords, ...niche.keywordsUsed]).size <= CHUNK);\n if (open) { open.niches.push(niche); open.keywords = [...new Set([...open.keywords, ...niche.keywordsUsed])]; }\n else jobs.push({ country: g.country, timeRange: g.timeRange, keywords: [...niche.keywordsUsed], niches: [niche] });\n}\nreturn jobs.map(json => ({ json }));" }, "id": "ebbfa179-1e9e-5942-af6e-94f00ccdf71d", "name": "Batch terms into Trends calls", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1560, -220 ] }, { "parameters": { "options": {} }, "id": "6c5098a1-3b47-58af-be94-283eb2175b42", "name": "Loop over jobs", "type": "n8n-nodes-base.splitInBatches", "typeVersion": 3, "position": [ 1780, -220 ] }, { "parameters": { "jsCode": "// One job -> the Google Trends Actor's input.\nconst d = $('Defaults').first().json;\nconst job = $input.first().json;\nreturn [{ json: { ...job, actorInput: {\n keywords: job.keywords,\n preset: 'custom',\n components: d.includeTopics === false ? ['relatedQueries'] : ['relatedQueries', 'relatedTopics'],\n geo: job.country || '', // empty = worldwide\n timeRange: job.timeRange,\n maxTopicsWaitMinutes: 3, // keeps runs short; topics Google holds back longer are skipped (and not charged)\n} } }];" }, "id": "fe469737-a848-55fe-92f6-1c843eab48ba", "name": "Build Trends request", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 2000, -40 ] }, { "parameters": { "authentication": "apifyOAuth2Api", "resource": "Actors", "operation": "Run actor and get dataset", "actorSource": "store", "actorId": { "__rl": true, "mode": "id", "value": "CtmSzlDXdn2nGFpTK" }, "actorInputMode": "json", "customBody": "={{ JSON.stringify($json.actorInput) }}", "timeout": 300, "memory": 512 }, "id": "31255418-02f9-51bc-aa1e-fb1eee624f99", "name": "Google Trends", "type": "@apify/n8n-nodes-apify.apify", "typeVersion": 2, "position": [ 2220, -40 ] }, { "parameters": { "jsCode": "// One call's Google Trends results -> one row per rising search or topic, for every niche that watches that term\n// (a call can serve several niches). Terms Google has no data for are kept as \"noData\" rows, so the summary can name them.\nconst job = $('Loop over jobs').first().json;\nconst tagOf = n => ({ group: n.group, about: n.about, niche: n.niche, audience: n.audience, country: n.country,\n timeRange: n.timeRange, formats: n.formats, source: n.source, skipped: n.skipped,\n keywordsUsed: n.keywordsUsed, topicOrigin: n.topicOrigin, keywordNote: n.keywordNote });\nconst watchers = {};\nfor (const n of job.niches) for (const k of n.keywordsUsed) (watchers[k.toLowerCase()] ??= []).push(tagOf(n));\nconst growthNumber = g => /breakout/i.test(g || '') ? 5000 : (parseInt(String(g || '').replace(/[^0-9]/g, ''), 10) || 0);\nconst rows = [];\nfor (const { json: k } of $input.all()) {\n for (const tag of watchers[String(k.keyword || '').toLowerCase()] || []) {\n if (!['complete', 'partial'].includes(k.status)) { rows.push({ ...tag, noData: true, seed: k.keyword }); continue; }\n for (const q of k.relatedQueries?.rising || [])\n rows.push({ ...tag, seed: k.keyword, kind: 'search', text: q.query, topicType: '', growth: q.growth || '', growthNumber: growthNumber(q.growth) });\n for (const t of k.relatedTopics?.rising || [])\n rows.push({ ...tag, seed: k.keyword, kind: 'topic', text: t.title, topicType: /^topic$/i.test(t.type || '') ? '' : (t.type || ''), growth: t.growth || '', growthNumber: growthNumber(t.growth) });\n }\n}\n// every niche in the call shows up in the results, even one Google had nothing for\nfor (const n of job.niches) if (!rows.some(r => r.group === n.group)) rows.push({ ...tagOf(n), noData: true, seed: '' });\nreturn rows.map(json => ({ json }));" }, "id": "d9c59cb4-0211-505a-b1ab-8c0e3afb7877", "name": "Collect rising searches", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 2440, -40 ] }, { "parameters": { "jsCode": "// All jobs' rising searches -> one item per niche with its best candidates. Per niche:\n// 1. Junk out. Google Trends data carries bot and AI-agent traffic: prompt-like searches (\"explain what X is and its\n// main benefits\") and generic Breakouts (\"how to make sushi\") under unrelated keywords.\n// 2. Relevance. The AI judges it later; \"related\" (shares a real word with the niche or its terms) only orders the list\n// and, if the AI is unavailable, decides what goes in the report.\n// 3. Variants merged (\"trader joe's retinol\" = \"trader joes retinol\"; a topic and a search naming the same product).\n// 4. Ranked by growth, boosted when rising under several keywords or as both a search and a topic; a search that is\n// just your keyword again ranks lower.\n// 5. Scheduled runs remember what was sent (8 weeks) and flag what's new since the last run.\n// 6. Spread across keywords; unrelated-looking searches get at most a third of the list (new brands often share no\n// word with your keywords, so the AI gets a chance to keep them).\nconst d = $('Defaults').first().json;\nconst limit = Math.max(1, Number(d.ideasPerNiche) || 10);\n\n// ---- tuning (safe to change) ----\nconst STOP = new Set(['for', 'the', 'and', 'with', 'from', 'that', 'this', 'your', 'you', 'how', 'what', 'when', 'why',\n 'who', 'which', 'can', 'does', 'best', 'top', 'near', 'are', 'was', 'use', 'using', 'new', 'free', 'good', 'get', 'not',\n 'all', 'about', 'into', 'like', 'more', 'most', 'make', 'way', 'ways', 'vs', 'review', 'reviews', 'usa', 'online']);\nconst PROMPT_START = /^(explain|describe|write|list|give me|tell me|summarize|summarise|compare|create|generate|provide|act as)\\b/i;\nconst PROMPT_PHRASE = /\\band (its|their) (main|primary|key|potential)\\b|\\bwhy do you think\\b|\\bin (simple|detail|bullet)/i;\nconst MAX_WORDS = 15; // longer \"searches\" read like prompts; real questions and product names stay under it\nconst ECHO_FACTOR = 0.3; // a search that is just your keyword again (\"AI agent\" under \"ai agents\") says little\nconst JUNK_UNDER_KEYWORDS = 3; // the same unrelated search under this many keywords = bot junk\nconst BOOST_PER_EXTRA_KEYWORD = 0.5, BOOST_SEARCH_AND_TOPIC = 0.2, NOT_NEW_FACTOR = 0.8;\nconst REMEMBER_WEEKS = 8;\n\nconst norm = t => String(t).toLowerCase().replace(/['’]/g, '').replace(/[^\\p{L}\\p{N}]+/gu, ' ').trim();\nconst words = t => norm(t).split(' ').filter(w => w.length > 2 && !STOP.has(w));\nconst stems = t => new Set(words(t).map(w => w.slice(0, 5)));\nconst shares = (a, b) => [...a].some(x => b.has(x));\nconst sig = t => [...new Set(words(t).map(w => w.replace(/(?<=..)s$/, '')))].sort().join(' ') || norm(t);\nconst allStems = t => new Set(norm(t).split(' ').filter(w => w.length > 1).map(w => w.slice(0, 5)));\nconst echoes = (text, seed) => { const a = allStems(text), b = allStems(seed); return a.size > 0 && [...a].every(x => b.has(x)); };\n\nconst byNiche = {};\nfor (const { json: r } of $input.all()) (byNiche[r.group] ??= []).push(r);\nconst memory = $getWorkflowStaticData('global');\nmemory.sent ??= {}; memory.lastRun ??= {};\nconst now = Date.now();\nconst out = [];\n\nfor (const [group, rowsAll] of Object.entries(byNiche)) {\n const info = rowsAll[0];\n const remember = info.source === 'sheet'; // one-off form runs always show everything\n const candidates = Math.min(limit * 4, 40); // the AI is strict, so it gets plenty to choose from\n const all = rowsAll.filter(r => !r.noData);\n const seedsWithData = new Set(all.map(r => r.seed));\n const noData = [...new Set(rowsAll.filter(r => r.noData && r.seed).map(r => r.seed))].filter(k => !seedsWithData.has(k));\n const stats = { risingFound: all.length, junk: 0, offTopic: 0, merged: 0, alreadySent: 0, keywordsWithoutData: noData,\n skippedRows: info.skipped || [] };\n // the niche's own words: its name and all its keywords (not the audience: \"people\", \"work\", \"training\" match too much)\n const nicheStems = stems([info.niche, ...seedsWithData].join(' '));\n\n // 1 + 2\n const under = {};\n for (const r of all) (under[norm(r.text)] ??= new Set()).add(r.seed);\n const kept = all.filter(r => {\n r.related = shares(stems(r.text), nicheStems);\n const promptLike = r.kind === 'search' && (PROMPT_START.test(r.text) || PROMPT_PHRASE.test(r.text)\n || norm(r.text).split(' ').length > MAX_WORDS);\n if (promptLike || (under[norm(r.text)].size >= JUNK_UNDER_KEYWORDS && !r.related)) { stats.junk++; return false; }\n return true;\n });\n\n // seed health: how many usable rising searches each keyword brought (a keyword is a seed; Google reports what rises\n // around it, so a good seed is a core topic people search all the time, not something that must be booming itself)\n const keywordYield = {};\n for (const r of kept) keywordYield[r.seed] = (keywordYield[r.seed] || 0) + 1;\n\n // 3\n const groups = [];\n for (const r of kept.sort((a, b) => b.growthNumber - a.growthNumber)) {\n const g = groups.find(g => g.sig === sig(r.text));\n if (g) {\n stats.merged++;\n g.seeds.add(r.seed); g.kinds.add(r.kind); g.related ||= r.related;\n if (norm(r.text) !== norm(g.text)) g.variants.add(r.text);\n g.topicType ||= r.topicType;\n } else {\n groups.push({ sig: sig(r.text), wordSet: new Set(sig(r.text).split(' ')), text: r.text, growth: r.growth,\n growthNumber: r.growthNumber, topicType: r.topicType, related: r.related, echo: [...seedsWithData, info.niche].some(k => echoes(r.text, k)),\n seeds: new Set([r.seed]), kinds: new Set([r.kind]), variants: new Set() });\n }\n }\n for (const t of groups.filter(g => g.kinds.size === 1 && g.kinds.has('topic') && g.wordSet.size >= 3)) {\n const q = groups.find(g => g !== t && g.kinds.has('search') && [...t.seeds].some(k => g.seeds.has(k))\n && [...t.wordSet].every(w => g.wordSet.has(w)));\n if (!q) continue;\n stats.merged++;\n q.kinds.add('topic'); q.variants.add(t.text); q.topicType ||= t.topicType;\n q.growthNumber = Math.max(q.growthNumber, t.growthNumber);\n t.mergedInto = q;\n }\n const merged = groups.filter(g => !g.mergedInto);\n\n // 4 + 5\n const sent = remember ? (memory.sent[group] ??= {}) : {};\n for (const [k, t] of Object.entries(sent)) if (now - t > REMEMBER_WEEKS * 7 * 86400e3) delete sent[k];\n const lastRun = new Set(remember ? memory.lastRun[group] || [] : []);\n if (remember) memory.lastRun[group] = merged.map(g => g.sig);\n const scored = merged\n .filter(g => { if (sent[g.sig]) { stats.alreadySent++; return false; } return true; })\n .map(g => {\n const isNew = remember ? !lastRun.has(g.sig) : null;\n const score = g.growthNumber * (1 + BOOST_PER_EXTRA_KEYWORD * (g.seeds.size - 1))\n * (g.kinds.size > 1 ? 1 + BOOST_SEARCH_AND_TOPIC : 1) * (isNew === false ? NOT_NEW_FACTOR : 1)\n * (g.echo ? ECHO_FACTOR : 1);\n return { ...g, isNew, score };\n })\n .sort((a, b) => b.score - a.score);\n\n // 6\n const perSeed = Math.max(2, Math.ceil(candidates / Math.max(1, seedsWithData.size)));\n const used = {}, picked = [];\n const take = (list, max) => { for (const g of list) {\n if (picked.length >= max) return;\n if (picked.includes(g)) continue;\n const main = [...g.seeds][0];\n if ((used[main] || 0) < perSeed) { used[main] = (used[main] || 0) + 1; picked.push(g); } } };\n const related = scored.filter(g => g.related), unrelated = scored.filter(g => !g.related);\n take(related, candidates - Math.ceil(candidates / 3));\n take(unrelated, candidates);\n take(related, candidates);\n\n const geo = encodeURIComponent(info.country || ''), date = encodeURIComponent(info.timeRange);\n out.push({ id: `N${out.length + 1}`, group, about: info.about, niche: info.niche, audience: info.audience,\n formats: info.formats, country: info.country, timeRange: info.timeRange, source: info.source, stats,\n nothingNew: picked.length === 0, keywordsUsed: info.keywordsUsed || [...seedsWithData],\n topicOrigin: info.topicOrigin || {}, keywordNote: info.keywordNote || '',\n keywordYield,\n candidates: picked.map((g, i) => ({ n: i + 1, key: g.sig, text: g.text, variants: [...g.variants], related: g.related, echo: g.echo,\n kind: [...g.kinds].sort().join(' + '), topicType: g.topicType, growth: g.growth, seeds: [...g.seeds], isNew: g.isNew,\n googleTrends: `https://trends.google.com/trends/explore?q=${encodeURIComponent(g.text)}&geo=${geo}&date=${date}` })) });\n}\nreturn out.map(json => ({ json }));" }, "id": "b61f8239-b501-5453-8c38-efb41ff8c470", "name": "Clean and rank", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 2680, -220 ] }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "loose", "version": 2 }, "conditions": [ { "id": "049b2dc5-4fa1-5dde-91be-b0bd6d1c86d9", "leftValue": "={{ $json.nothingNew !== true }}", "rightValue": "", "operator": { "type": "boolean", "operation": "true", "singleValue": true } } ], "combinator": "and" }, "looseTypeValidation": true, "options": {} }, "id": "d4a2d589-8d24-5143-a3c5-de710afbcd38", "name": "Anything to write about?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 2900, -220 ] }, { "parameters": { "jsCode": "// One AI request per niche: the model sees the whole list, so it can compare and drop the weak ones.\nreturn $input.all().map(({ json: n }) => {\n const list = n.candidates.map(c =>\n `${c.n}. \"${c.text}\"${c.topicType ? ` [topic: ${c.topicType}]` : ''}: rising ${c.growth}`\n + ` under ${c.seeds.map(k => `\"${k}\"`).join(', ')}${c.variants.length ? `; also searched as ${c.variants.map(v => `\"${v}\"`).join(', ')}` : ''}`\n + `${c.echo ? ' (just my keyword again)' : ''}${c.isNew === false ? ' (was rising last time too)' : ''}`).join('\\n');\n const prompt = [\n `Today is ${new Date().toISOString().slice(0, 10)}.`,\n `I make content about: ${n.niche}.`,\n n.about && n.about.toLowerCase() !== n.niche.toLowerCase() ? `In my own words: \"${n.about}\". Lean towards what I said I want to cover.` : null,\n n.audience ? `My audience: ${n.audience}.` : 'My audience: people interested in this niche.',\n `Formats I publish: ${n.formats || 'blog post, short video'}.`,\n ``,\n `These searches are rising on Google right now (${n.country || 'worldwide'}, ${n.timeRange}), with their growth and the keyword they rose under:`,\n list,\n ``,\n `For every numbered item, return:`,\n `- relevance (0-10): how good a content opportunity it is for my audience right now.`,\n ` 9-10: specific and clearly for my audience: a question they ask, a product, rule, event or story they care about.`,\n ` 6-8: relevant, but broader or less timely.`,\n ` 3-5: a broad name on its own (a company, platform, category, or just my keyword again) that rises for too many reasons to tell what people want; or about the same story or product type as a better item in this list.`,\n ` 0-2: unrelated to my niche, spam, or bot traffic.`,\n ` Judge the search itself, not the idea you could write about it: a broad name stays at 5 or less even if you can think of a good angle for it.`,\n `- whyRising: one sentence starting with \"Likely\" or \"Possibly\": the reason people may be searching it now. You only see Google search data and your knowledge may be out of date, so never state recent events, versions or prices as facts; say \"Unclear\" if you don't know. If the search looks like the title of a specific article, paper, book, video or news story, say so.`,\n `- title, angle (what to cover), hook (the opening line), format (one of my formats; vary them across ideas where it fits).`,\n `- checkBeforePublishing: every fact the idea relies on that must be verified before publishing: numbers, prices, dates, versions, rules, study results, and the original source when the search points to a specific article or story. Empty only when there is nothing to verify.`,\n ``,\n `Rules for title, hook and angle:`,\n `- No numbers, prices, percentages, amounts or time claims unless they are in the search itself or listed in checkBeforePublishing. Counting your own steps or tips (\"3 steps\") is fine.`,\n `- No personal experience (\"I tested\", \"my results\"): the creator hasn't done it yet.`,\n `- Put a year in a title only when the search is about that year.`,\n `- Each idea must be distinct. When several items are about the same story or product type, give the best one an idea that covers them all and score the others 5 or less.`,\n ``,\n `Return one entry per item, using its number as \"n\", and set \"nicheId\" to \"${n.id}\".`,\n ].filter(l => l !== null).join('\\n');\n return { json: { ...n, prompt } };\n});" }, "id": "93d3595c-ea2d-5d7b-826e-e61f96f0105c", "name": "Prepare AI request", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 3120, -340 ] }, { "parameters": { "promptType": "define", "text": "={{ $json.prompt }}", "hasOutputParser": true, "messages": { "messageValues": [ { "type": "SystemMessagePromptTemplate", "message": "You are a practical content strategist. You write specific ideas a creator could publish this week, never generic ones. You never present a fact you aren't sure of: anything that needs checking goes in checkBeforePublishing." } ] }, "batching": {} }, "id": "344993f5-5730-5b2f-acb6-b19be34586ab", "name": "Write content ideas", "type": "@n8n/n8n-nodes-langchain.chainLlm", "typeVersion": 1.9, "position": [ 3360, -340 ], "onError": "continueErrorOutput", "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 5000 }, { "parameters": { "modelName": "models/gemini-flash-latest", "options": { "temperature": 0.6 } }, "id": "92661081-a3f3-5f48-b4ea-b5d6876b5d13", "name": "Gemini model", "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini", "typeVersion": 1.2, "position": [ 780, 20 ] }, { "parameters": { "schemaType": "manual", "inputSchema": "{\n \"type\": \"object\",\n \"properties\": {\n \"nicheId\": {\n \"type\": \"string\"\n },\n \"ideas\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"n\": {\n \"type\": \"integer\"\n },\n \"relevance\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 10\n },\n \"whyRising\": {\n \"type\": \"string\"\n },\n \"title\": {\n \"type\": \"string\"\n },\n \"angle\": {\n \"type\": \"string\"\n },\n \"hook\": {\n \"type\": \"string\"\n },\n \"format\": {\n \"type\": \"string\"\n },\n \"checkBeforePublishing\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"n\",\n \"relevance\",\n \"whyRising\",\n \"title\",\n \"angle\",\n \"hook\",\n \"format\",\n \"checkBeforePublishing\"\n ]\n }\n }\n },\n \"required\": [\n \"nicheId\",\n \"ideas\"\n ]\n}", "autoFix": false }, "id": "591d6e8c-6f25-5cbc-b47d-4f301856ea95", "name": "Idea format", "type": "@n8n/n8n-nodes-langchain.outputParserStructured", "typeVersion": 1.3, "position": [ 3420, -120 ] }, { "parameters": { "jsCode": "// The AI's ideas, matched back to their searches; keeps the relevant ones (minRelevance in Defaults), best first.\nconst d = $('Defaults').first().json;\nconst minRelevance = Number(d.minRelevance) || 6;\nconst limit = Math.max(1, Number(d.ideasPerNiche) || 10);\n// The chain's answer doesn't carry the niche it belongs to, so each niche has an id the AI echoes back (\"nicheId\");\n// n8n's item link and the position are fallbacks.\nconst prepared = $('Prepare AI request').all().map(p => p.json);\nreturn $input.all().map((item, i) => {\n const out = item.json.output || {};\n const n = prepared.find(p => p.id === out.nicheId) ?? prepared[item.pairedItem?.item] ?? prepared[i];\n const byN = Object.fromEntries((out.ideas || []).map(x => [Number(x.n), x]));\n // a search that is just your keyword again tells little about what people want: capped at 5, whatever the AI said\n const scored = n.candidates.map(c => ({ c, a: byN[c.n] && { ...byN[c.n],\n relevance: c.echo ? Math.min(Number(byN[c.n].relevance), 5) : Number(byN[c.n].relevance) } }));\n const relevant = scored.filter(({ a }) => a && Number(a.relevance) >= minRelevance && a.title);\n const keep = [...relevant].sort((x, y) => y.a.relevance - x.a.relevance || x.c.n - y.c.n).slice(0, limit);\n const { prompt, ...rest } = n;\n // aiDropped: judged off-topic or weak; the rest of the list was just past ideasPerNiche\n return { json: { ...rest, mode: 'ideas', aiDropped: scored.length - relevant.length,\n ideas: keep.map(({ c, a }) => ({ ...c, idea: a.title, angle: a.angle || '', hook: a.hook || '', format: a.format || '',\n whyRising: a.whyRising || '', checkBeforePublishing: a.checkBeforePublishing || [], relevance: Number(a.relevance) })) } };\n});" }, "id": "fe45b076-4df2-5ade-b32b-4f47fae35f08", "name": "Add AI ideas", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 3600, -440 ] }, { "parameters": { "jsCode": "const reasonFor = error => { const raw = String(error?.message || error || 'unknown error');\n return /402|payment|credit|billing|prepay|exhausted/i.test(raw) ? 'the AI account is out of credit'\n : /bad request|api key|401|403|permission|credential/i.test(raw) ? 'the AI key or model name needs checking'\n : /429|quota|rate/i.test(raw) ? 'the AI service is busy, try again soon' : raw.slice(0, 120); };\n\n// The AI call failed (bad key, no credit, rate limit, outage): deliver the rising searches report instead of nothing.\n// n8n's error output carries the niche's own data, plus the error.\nreturn $input.all().map(item => {\n const { prompt, error, ...n } = item.json;\n return { json: { ...n, mode: 'report',\n aiNote: `We couldn't write ideas this time (${reasonFor(error)}), so here are the rising searches instead.` } };\n});" }, "id": "183c78b0-062e-521b-b740-a945ade95713", "name": "AI unavailable: report", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 3600, -260 ] }, { "parameters": { "numberInputs": 3 }, "id": "703e1181-8f65-54e4-a1bf-424021708155", "name": "Merge niche results", "type": "n8n-nodes-base.merge", "typeVersion": 3.2, "position": [ 3820, -220 ] }, { "parameters": { "jsCode": "// Every niche -> its rows in one fixed set of columns (the same for ideas and for the report), plus a summary line.\n// Scheduled runs also remember what was sent, so next week brings only new searches.\nconst d = $('Defaults').first().json;\nconst limit = Math.max(1, Number(d.ideasPerNiche) || 10);\nconst memory = $getWorkflowStaticData('global');\nmemory.sent ??= {};\nconst today = new Date().toISOString().slice(0, 10);\nconst COLUMNS = ['date', 'niche', 'mode', 'status', 'idea', 'angle', 'hook', 'format', 'whyRising', 'checkBeforePublishing',\n 'risingSearch', 'growth', 'type', 'alsoSearchedAs', 'newThisWeek', 'yourKeywords', 'relevance', 'googleTrends', 'note'];\nconst row = (n, c, extra) => Object.fromEntries(COLUMNS.map(k => [k, ({\n date: today, niche: n.niche, status: 'to review', risingSearch: c.text, growth: c.growth,\n type: c.kind + (c.topicType ? ` (${c.topicType})` : ''), alsoSearchedAs: c.variants.join('; '),\n newThisWeek: c.isNew === null ? '' : c.isNew ? 'yes' : 'no', yourKeywords: c.seeds.join(', '), googleTrends: c.googleTrends,\n ...extra })[k] ?? '']));\n\nreturn $input.all().map(({ json: n }) => {\n const mode = n.nothingNew ? 'nothing new' : n.mode || 'report';\n let rows = [];\n if (mode === 'ideas') rows = n.ideas.map(c => row(n, c, { mode, idea: c.idea, angle: c.angle, hook: c.hook, format: c.format,\n whyRising: c.whyRising, checkBeforePublishing: (c.checkBeforePublishing || []).join('; '), relevance: c.relevance }));\n // the report prefers word-matched searches: when the AI failed, its list also holds unrelated ones it was meant to judge\n const matched = n.candidates.filter(c => c.related);\n const reportPicks = (matched.length ? matched : n.candidates).slice(0, limit);\n if (mode === 'report') rows = reportPicks.map(c => row(n, c, { mode, note: n.aiNote || '' }));\n if (n.source === 'sheet') { memory.sent[n.group] ??= {};\n for (const c of mode === 'ideas' ? n.ideas : mode === 'report' ? reportPicks : []) memory.sent[n.group][c.key] = Date.now(); }\n const st = n.stats;\n // off-topic: dropped by the word match, judged weak by the AI, or (AI unavailable) left out of the report as unrelated\n const offTopic = st.offTopic + (n.aiDropped || 0) + (mode === 'report' && matched.length ? n.candidates.length - matched.length : 0);\n // which search terms were watched and where each came from (yours / from your words / added), so people see how\n // their request was read and learn which terms work\n const origin = n.topicOrigin || {};\n const added = (n.keywordsUsed || []).filter(w => origin[w] === 'added');\n const keywords = { used: n.keywordsUsed || [], origin, added, noData: st.keywordsWithoutData, yield: n.keywordYield || {} };\n // the summary says what the person got and what to do, not how it was filtered (that stays in `filtering`)\n const headline = mode === 'nothing new' ? (st.alreadySent ? 'nothing new is rising right now; what is rising was sent before'\n : 'nothing new is rising right now')\n : mode === 'ideas' ? `${rows.length} content ideas, picked from ${st.risingFound} rising searches`\n : `${rows.length} rising searches worth a look, out of ${st.risingFound}`;\n const alreadySent = mode !== 'nothing new' && st.alreadySent ? ` ${st.alreadySent} you got before are left out.` : '';\n const noData = st.keywordsWithoutData.length ? ` Not enough Google data for: ${st.keywordsWithoutData.join(', ')}.` : '';\n const noDataAtAll = !st.risingFound && keywords.used.length && st.keywordsWithoutData.length >= keywords.used.length;\n const summary = noDataAtAll ? `${n.niche}: not enough Google data for ${keywords.used.join(', ')}.`\n : `${n.niche}: ${headline}.${alreadySent}${noData}`;\n const filtering = { risingSearches: st.risingFound, junk: st.junk, offTopic, variantsMerged: st.merged, alreadySent: st.alreadySent };\n return { json: { niche: n.niche, about: n.about, source: n.source, mode, rows, skippedRows: st.skippedRows, keywords,\n keywordNote: n.keywordNote, summary, filtering } };\n});" }, "id": "6ecce495-6341-5cd1-9a8b-1c82dfcf72d4", "name": "Format results", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 4020, -220 ] }, { "parameters": { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "loose", "version": 2 }, "conditions": [ { "id": "7ac4b8f4-c370-5c76-9968-e6480b224bd4", "leftValue": "={{ $json.source === 'form' }}", "rightValue": "", "operator": { "type": "boolean", "operation": "true", "singleValue": true } } ], "combinator": "and" }, "looseTypeValidation": true, "options": {} }, "id": "5c372213-05fa-5041-873b-0f617b143ac2", "name": "From the form?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 4240, -220 ] }, { "parameters": { "jsCode": "// The results as a web page for the form.\nconst esc = s => String(s ?? '').replace(/[&<>\"]/g, c => ({ '&': '&', '<': '<', '>': '>', '\"': '"' })[c]);\nconst niches = $input.all().map(i => i.json);\nconst card = r => r.mode === 'ideas'\n ? `Hook: ${esc(r.hook)}
Angle: ${esc(r.angle)}
\n ${r.whyRising ? `Likely why: ${esc(r.whyRising)}
` : ''}\n ${r.checkBeforePublishing ? `Check before publishing: ${esc(r.checkBeforePublishing)}
` : ''}\n See it on Google Trends${esc(n.summary.replace(/^[^:]*:\\s*/, ''))}
`\n + `We watched these on Google, with the rising searches each one found: ${kw(n)}`\n + `${(n.keywords?.added || []).length ? ' · * added by us, keep the ones you like' : ''}`\n + `${(n.keywords?.noData || []).length ? ' · crossed out: not enough Google data' : ''}
`\n + (n.keywordNote ? `${esc(n.keywordNote)}
` : '')\n + (n.mode === 'ideas' ? n.rows.map(card).join('')\n : n.mode === 'report' ? `${n.rows[0]?.note ? `${esc(n.rows[0].note)}
` : ''}| Rising search | Growth | Type | From topic |
|---|
Ideas for ${niches.length} niches: ${niches.map(n => esc(n.niche)).join(' · ')}
` : ''}${niches.map(section).join('')}`;\nreturn [{ json: { html } }];" }, "id": "d0cd989a-a5aa-5608-bedd-94c2d43ebff5", "name": "Build results page", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 4460, -420 ] }, { "parameters": { "operation": "completion", "respondWith": "showText", "responseText": "={{ $json.html }}" }, "id": "0e494c44-9f5d-5250-a613-fc8c217d963a", "name": "Show results", "type": "n8n-nodes-base.form", "typeVersion": 2.5, "position": [ 4700, -420 ], "webhookId": "ea0efac3-0940-5c6d-8bec-2e483e710c42" }, { "parameters": { "fieldToSplitOut": "rows", "options": {} }, "id": "a21675d7-c862-52a5-b7ad-ffd6ea4b5197", "name": "One row per idea", "type": "n8n-nodes-base.splitOut", "typeVersion": 1, "position": [ 4460, -200 ] }, { "parameters": { "operation": "append", "documentId": { "__rl": true, "mode": "url", "value": "" }, "sheetName": { "__rl": true, "mode": "name", "value": "Ideas" }, "columns": { "mappingMode": "autoMapInputData", "value": {}, "matchingColumns": [], "schema": [] }, "options": {} }, "id": "7e46929f-ad8c-54c5-ba52-06095035c499", "name": "Add to Google Sheet", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [ 4700, -200 ], "disabled": true }, { "parameters": { "jsCode": "// A short message for Slack or Telegram covering every niche in this run.\nconst niches = $input.all().map(i => i.json);\nconst blocks = niches.map(n => {\n const top = n.mode === 'ideas' ? n.rows.slice(0, 5).map((r, i) => `${i + 1}. ${r.idea} (\"${r.risingSearch}\" ${r.growth})`).join('\\n')\n : n.mode === 'report' ? n.rows.slice(0, 5).map((r, i) => `${i + 1}. ${r.risingSearch} (${r.growth})`).join('\\n') : '';\n const k = n.keywords || {};\n const keep = k.added?.length ? `\nWe also watched: ${k.added.join(', ')}.${n.source === 'sheet' ? ' Add the ones you like to your sheet to keep them.' : ''}` : '';\n // topics that brought (almost) nothing: worth replacing with more concrete ones\n const weak = (k.used || []).filter(w => !(k.noData || []).includes(w) && ((k.yield || {})[w] || 0) <= 1);\n const weakNote = weak.length && weak.length < (k.used || []).length ? `\\nTopics that found little this time: ${weak.join(', ')}.` : '';\n return `${n.summary}${keep}${weakNote}${n.keywordNote ? `\\n${n.keywordNote}` : ''}${top ? `\\n${top}` : ''}`;\n});\nconst skipped = niches[0]?.skippedRows?.length ? `\\n\\nSkipped these sheet rows because they have no niche: ${niches[0].skippedRows.join(', ')}.` : '';\nreturn [{ json: { text: `What's rising in your niches this week\\n\\n${blocks.join('\\n\\n')}${skipped}` } }];" }, "id": "60093728-a0f7-51b3-9745-d2e51821f265", "name": "Weekly summary", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 4460, 20 ] }, { "parameters": { "select": "channel", "channelId": { "__rl": true, "mode": "name", "value": "#content" }, "text": "={{ $json.text }}", "otherOptions": {} }, "id": "2f068ff7-361c-5dda-9874-3c5c3dae9095", "name": "Send to Slack", "type": "n8n-nodes-base.slack", "typeVersion": 2.2, "position": [ 4700, -10 ], "disabled": true }, { "parameters": { "chatId": "YOUR_CHAT_ID", "text": "={{ $json.text }}", "additionalFields": { "appendAttribution": false } }, "id": "1692af63-40a9-57fc-990c-0a1812c16ebe", "name": "Send to Telegram", "type": "n8n-nodes-base.telegram", "typeVersion": 1.2, "position": [ 4700, 130 ], "disabled": true } ], "connections": { "Form": { "main": [ [ { "node": "Read form answers", "type": "main", "index": 0 } ] ] }, "Read form answers": { "main": [ [ { "node": "Defaults", "type": "main", "index": 0 } ] ] }, "Every Monday at 8:00": { "main": [ [ { "node": "Read keyword sheet", "type": "main", "index": 0 } ] ] }, "Read keyword sheet": { "main": [ [ { "node": "Read sheet rows", "type": "main", "index": 0 } ] ] }, "Read sheet rows": { "main": [ [ { "node": "Defaults", "type": "main", "index": 0 } ] ] }, "Run it now": { "main": [ [ { "node": "Test input", "type": "main", "index": 0 } ] ] }, "Test input": { "main": [ [ { "node": "Read test input", "type": "main", "index": 0 } ] ] }, "Read test input": { "main": [ [ { "node": "Defaults", "type": "main", "index": 0 } ] ] }, "Defaults": { "main": [ [ { "node": "Group by niche", "type": "main", "index": 0 } ] ] }, "Group by niche": { "main": [ [ { "node": "Ask AI to plan topics", "type": "main", "index": 0 } ] ] }, "Ask AI to plan topics": { "main": [ [ { "node": "Plan topics", "type": "main", "index": 0 } ] ] }, "Topic plan": { "ai_outputParser": [ [ { "node": "Plan topics", "type": "ai_outputParser", "index": 0 } ] ] }, "Plan topics": { "main": [ [ { "node": "Use planned topics", "type": "main", "index": 0 } ], [ { "node": "Plan without AI", "type": "main", "index": 0 } ] ] }, "Use planned topics": { "main": [ [ { "node": "Merge planned niches", "type": "main", "index": 0 } ] ] }, "Plan without AI": { "main": [ [ { "node": "Merge planned niches", "type": "main", "index": 1 } ] ] }, "Merge planned niches": { "main": [ [ { "node": "Batch terms into Trends calls", "type": "main", "index": 0 } ] ] }, "Batch terms into Trends calls": { "main": [ [ { "node": "Loop over jobs", "type": "main", "index": 0 } ] ] }, "Loop over jobs": { "main": [ [ { "node": "Clean and rank", "type": "main", "index": 0 } ], [ { "node": "Build Trends request", "type": "main", "index": 0 } ] ] }, "Build Trends request": { "main": [ [ { "node": "Google Trends", "type": "main", "index": 0 } ] ] }, "Google Trends": { "main": [ [ { "node": "Collect rising searches", "type": "main", "index": 0 } ] ] }, "Collect rising searches": { "main": [ [ { "node": "Loop over jobs", "type": "main", "index": 0 } ] ] }, "Clean and rank": { "main": [ [ { "node": "Anything to write about?", "type": "main", "index": 0 } ] ] }, "Anything to write about?": { "main": [ [ { "node": "Prepare AI request", "type": "main", "index": 0 } ], [ { "node": "Merge niche results", "type": "main", "index": 2 } ] ] }, "Prepare AI request": { "main": [ [ { "node": "Write content ideas", "type": "main", "index": 0 } ] ] }, "Gemini model": { "ai_languageModel": [ [ { "node": "Plan topics", "type": "ai_languageModel", "index": 0 }, { "node": "Write content ideas", "type": "ai_languageModel", "index": 0 } ] ] }, "Idea format": { "ai_outputParser": [ [ { "node": "Write content ideas", "type": "ai_outputParser", "index": 0 } ] ] }, "Write content ideas": { "main": [ [ { "node": "Add AI ideas", "type": "main", "index": 0 } ], [ { "node": "AI unavailable: report", "type": "main", "index": 0 } ] ] }, "Add AI ideas": { "main": [ [ { "node": "Merge niche results", "type": "main", "index": 0 } ] ] }, "AI unavailable: report": { "main": [ [ { "node": "Merge niche results", "type": "main", "index": 1 } ] ] }, "Merge niche results": { "main": [ [ { "node": "Format results", "type": "main", "index": 0 } ] ] }, "Format results": { "main": [ [ { "node": "From the form?", "type": "main", "index": 0 } ] ] }, "From the form?": { "main": [ [ { "node": "Build results page", "type": "main", "index": 0 } ], [ { "node": "One row per idea", "type": "main", "index": 0 }, { "node": "Weekly summary", "type": "main", "index": 0 } ] ] }, "Build results page": { "main": [ [ { "node": "Show results", "type": "main", "index": 0 } ] ] }, "One row per idea": { "main": [ [ { "node": "Add to Google Sheet", "type": "main", "index": 0 } ] ] }, "Weekly summary": { "main": [ [ { "node": "Send to Slack", "type": "main", "index": 0 }, { "node": "Send to Telegram", "type": "main", "index": 0 } ] ] } }, "settings": { "executionOrder": "v1" }, "pinData": {}, "meta": { "templateCredsSetupCompleted": false } }