DEV Community

Cover image for How I built a headless automated seo content pipeline using Node.js and Gemini
Mactrix XR
Mactrix XR

Posted on

How I built a headless automated seo content pipeline using Node.js and Gemini

How I built a headless automated seo content pipeline using Node.js and Gemini
As a solo developer, I love building things. But let us be honest: marketing is hard. When I launched my last SaaS project, I knew that organic search traffic was the best way to get long term users. The problem was that writing high quality, search optimized blog posts took me hours every week. I did not have the budget to hire a writer, and I did not have the time to sit down and write articles myself.

I tried using basic AI writers, but they required too much manual work. I had to copy and paste keywords, generate outlines, write the content, find images, and then manually upload everything to my blog. It was exhausting.

I knew I needed a hands-off approach, which led me to build my own headless automated seo content pipeline.

By combining the power of Node.js with Google Gemini, I created a system that handles keyword research, schedules articles, generates search optimized content, and publishes it directly to my blog. In this post, I will show you exactly how I built this pipeline, the code behind it, and the technical hurdles I had to overcome.


Why a headless automated seo content pipeline is a game-changer
For solo founders and small teams, content marketing often takes a backseat to product development. This is a mistake, but it is also completely understandable. You only have so many hours in a day.

An automated seo content pipeline solves this by turning content creation into a software engineering problem. Instead of spending hours writing, you spend a few hours building a system that writes for you.

Using a headless architecture means your content generation system is completely separated from your front-end blog. Your Node.js script runs in the background (perhaps on a cron job or a serverless function), talks to the Gemini API, and pushes the finished articles straight to your CMS via an API.

Here is why this approach works so well for indie hackers:

Consistency: The system never gets tired or suffers from writer's block. It keeps your blog updated on a set schedule.
Cost efficiency: Running a Node.js script costs pennies, and Gemini API calls are incredibly cheap compared to hiring freelance writers.
SEO optimization: You can program your SEO rules directly into the system's logic, ensuring every post has the right heading structure, keyword placement, and internal links.
If you are running a SaaS or an indie project, setting up this kind of ai content automation is the closest thing to a marketing superpower.


Step-by-step: How I built my automated seo content pipeline
To build a fully functional system, I broke the project down into three main phases: content planning, content generation, and automatic publishing. Let us walk through how each part works.

Step 1: Setting up the automated content calendar
A great blog does not just publish random articles. It needs a plan. The first step was to build an automated content calendar that keeps track of what topics to write about next.

To do this, I created a simple database table (using SQLite for simplicity, though PostgreSQL works great too) to store my targeted keywords, article titles, and publishing status.

The flow is simple:

  1. I seed the database with a list of high-intent keywords related to my SaaS.

  2. A daily cron job queries the database for the next "pending" keyword.

  3. The script passes this keyword to the generation engine.

  4. Once published, the status is updated to "completed."

This ensures that the pipeline always knows what to write next without any manual intervention.

Step 2: Gemini AI content generation
For the writing engine, I chose Google Gemini. I experimented with various models, but gemini ai content generation stood out because of its massive context window, fast speed, and highly competitive pricing. It is an amazing fit for an ai blog writer for saas.

Here is the actual Node.js code I used to set up the Gemini client and generate an SEO-friendly article.

import { GoogleGenAI } from '@google/genai';
import dotenv from 'dotenv';

dotenv.config();

// Initialize the Gemini client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

async function generateArticle(keyword, targetAudience) {
const prompt = `
You are an expert SEO content writer. Write a comprehensive, highly engaging blog post about: "${keyword}".
The target audience is: ${targetAudience}.

Follow these strict SEO guidelines:
- Use clear, conversational language suitable for a 7th-grade reading level.
- Write at least 1200 words.
- Use proper Markdown for formatting (H2, H3, bullet points, and numbered lists).
- Naturally include the primary keyword "${keyword}" in the introduction, at least two subheadings, and the conclusion.
- Do not use generic filler words or fluff.
- Return the output as a clean JSON object with two keys: "title" (the article title) and "body" (the markdown content).
Enter fullscreen mode Exit fullscreen mode

`;

try {
const response = await ai.models.generateContent({
model: 'gemini-2.5-pro',
contents: prompt,
config: {
// Enforce JSON output structure
responseMimeType: 'application/json',
}
});

const resultText = response.text;
const cleanData = JSON.parse(resultText);
return cleanData;
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
console.error('Error generating content with Gemini:', error);
throw error;
}
}
The technical hurdle: Handling JSON formatting bugs
When building this, I hit a frustrating technical constraint. Even when I requested a JSON response, older versions of the API would sometimes wrap the JSON inside markdown code blocks, like this:

{
"title": "My Article Title",
"body": "..."
}
Running JSON.parse() on this raw string would throw a syntax error and crash my entire pipeline.

To fix this, I had to write a helper function to clean the API response before parsing it. Here is the sanitization utility I built:

function cleanJsonResponse(rawString) {
let cleanString = rawString.trim();

// Strip out markdown code block wrappers if they exist
if (cleanString.startsWith('

json')) {
cleanString = cleanString.substring(7);
} else if (cleanString.startsWith('


')) {
cleanString = cleanString.substring(3);
}

if (cleanString.endsWith('


')) {
    cleanString = cleanString.substring(0, cleanString.length - 3);
  }

  return cleanString.trim();
}
Using the newer gemini-2.5-pro or gemini-2.5-flash models with responseMimeType: 'application/json' solves most of this, but keeping a fallback parser in place saved my pipeline from failing in production.

Step 3: Headless publishing via CMS APIs
Once the Node.js script receives the clean title and body from Gemini, it is time to publish. Because this is a headless pipeline, we do not want to log into an admin panel. We want to post it programmatically.

For my blog, I used WordPress. I set up an application password in my WordPress admin dashboard and used the WordPress REST API to post the article automatically. This essentially creates a custom wordpress ai autopilot system.

Here is how you can send the markdown article to WordPress:

import fetch from 'node-node-fetch';

async function publishToWordPress(title, markdownContent) {
  const wpUrl = 'https://yourblog.com/wp-json/wp/v2/posts';
  const username = process.env.WP_USERNAME;
  const applicationPassword = process.env.WP_APP_PASSWORD;

  // Convert username and password to base64 for Basic Auth
  const credentials = Buffer.from(`${username}:${applicationPassword}`).toString('base64');

  const postData = {
    title: title,
    // Note: WordPress accepts HTML, so we convert markdown to HTML first
    content: convertMarkdownToHtml(markdownContent),
    status: 'publish', // Use 'draft' if you want to review before publishing
    categories: [1], // Replace with your target category ID
  };

  const response = await fetch(wpUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Basic ${credentials}`
    },
    body: JSON.stringify(postData)
  });

  if (!response.ok) {
    const errText = await response.text();
    throw new Error(`WordPress API failed: ${errText}`);
  }

  const data = await response.json();
  console.log(`Successfully published! Post URL: ${data.link}`);
}
For the convertMarkdownToHtml helper, you can use a lightweight library like marked or markdown-it. This converts the clean markdown generated by Gemini into web-ready HTML for your CMS.

---

Building your own automated seo content pipeline: Lessons learned
Building this system taught me a lot about content ops for indie hackers. If you are planning to build your own version of this ai seo tool for startups, keep these three lessons in mind:

1. Prompt chaining is better than single prompts: Do not expect Gemini to do keyword research, outline creation, and writing all in one single prompt. It gets overwhelmed, which leads to lower-quality content. Instead, chain your prompts. Use one prompt to generate an outline, review it, and then pass that outline to a second prompt to write the actual paragraphs.

2. Review your drafts first: While my pipeline can publish directly to WordPress, I highly recommend setting the initial post status to draft. Spending five minutes reading through the draft, adding manual internal links, and tweaking the intro adds a layer of human quality that search engines love.

3. Handle API rate limits gracefully: AI APIs can fail or time out. Always wrap your API requests in retry logic. I built a simple backoff algorithm that retries the API call up to three times if it encounters a network error.

After building this manual setup for my own projects, I realized other founders faced the exact same bottleneck. We did not want to spend our weekends coding API integrations, setting up cron jobs, and debugging JSON parsing errors.

I ended up automating this entire workflow into a polished SaaS called SleepPublish. It handles the entire end to end workflow: it researches your keywords, plans a 30-day content calendar, generates SEO-optimized articles with Gemini, and auto-publishes them to WordPress, Ghost, Webflow, Notion, Wix, Shopify, Dev.to, and other CMS destinations.

---

Conclusion
Creating a headless automated seo content pipeline is one of the smartest engineering projects you can build for your startup. It takes the heavy lifting out of content marketing, letting you focus entirely on building your core product while your organic search traffic grows in the background.

With just a bit of Node.js code, a Gemini API key, and a connection to your CMS, you can have a fully functional content engine running on autopilot.

If you want to save time and skip the coding, server setup, and API maintenance, you can use pre-built tools to handle the heavy lifting for you.

Try SleepPublish free for 7 days, it plans, writes, and publishes SEO content straight to your CMS: https://sleeppublish.mactrixxr.space
Enter fullscreen mode Exit fullscreen mode

Top comments (0)