✦

SAAD ELGHABA

Portfolio

Loading... 0%

Automation / AI Integration • Personal Project

AI Blog Generation & Publishing Pipeline (n8n + Gemini)

AI Blog Generation & Publishing Pipeline (n8n + Gemini)

An end-to-end n8n automation workflow that generates, formats, and publishes SEO-optimized blog posts directly to a custom Next.js portfolio. It uses Gemini AI for content generation and handles complex session-cookie authentication and strict Zod schema validation.

Category

Automation / AI Integration

Technologies

—

The Challenge

Publishing technical content is time-consuming. I needed an automated way to generate blog posts with AI and publish them directly to my portfolio backend without manually handling JSON formatting, Zod schema validation, or session-cookie authentication.

Strategic Approach

Built an advanced n8n pipeline that uses Google Gemini to generate JSON content based on a strict schema. It includes a custom JavaScript normalization layer to fix AI output inconsistencies, captures session cookies for authentication, and uses JSON.stringify to safely POST the data to the Next.js API.

Measurable Outcomes

Achieved a fully automated blog generation and publishing workflow. Solved complex authentication and schema validation blockers, including Zod null-rejection issues and n8n JSON body formatting bugs.

Overview

The Vision: Automating the Content Engine

Writing technical blog posts takes time. Between outlining the idea, writing the code snippets, formatting the HTML, and uploading it to my CMS, hours vanish. I wanted to build a system where all I have to provide is a topic, and the pipeline handles the rest—from AI generation to database insertion.

To achieve this, I built a robust automation workflow using n8n and the Google Gemini API. It acts as an autonomous digital employee that writes, formats, authenticates, and publishes blog posts to my Next.js portfolio.


The Architecture

The pipeline is designed as a strict sequence of data transformations and HTTP requests. Here is the high-level flow:

Form Trigger (Topic + Schema File + Prompt)\n ↓\nContext Builder (Code) — Builds instruction string with schema from binary\n ↓\nGemini HTTP Request (Raw API, responseMimeType: application/json)\n ↓\nExtractor (Code) — Parses response, normalizes to exact Zod shape\n ↓\nLogin HTTP Request (POST /api/login, capture Set-Cookie)\n ↓\nCookie Extractor (Code) — Pulls session cookie from headers\n ↓\nInsert HTTP Request (POST /api/blog-posts, authenticated JSON body)

Technical Challenges Solved

This wasn't just a simple \"connect AI to an API\" task. It required dealing with several complex integration issues:

  • Strict Zod Validation: My backend uses Zod for schema validation. Zod .optional() means a key can be absent or a string, but it rejects null values. I had to write the Extractor to strip out all unexpected fields (like _id, createdAt, authorId) and ensure optional fields were either strings or completely omitted.
  • Gemini's Inconsistent JSON: Even when asked for a specific schema, Gemini often wraps the JSON in arbitrary keys (e.g., blog_article, post, data). I built a defensive parser that unwraps any top-level wrapper and validates the prompt token count (usageMetadata.promptTokenCount > 2000) to prove the AI actually received the instructions.
  • Session Cookie Auth: The portfolio API uses session-cookie authentication, not standard Bearer tokens. I had to configure the n8n HTTP node to capture the Set-Cookie header during login, extract the admin_session value, and pass it as a custom header in the subsequent POST request.
  • n8n Expression Quirks: Hand-writing JSON bodies in n8n breaks when the AI generates HTML content with quotes. I resolved this by using JSON.stringify() inside n8n expressions to safely escape all content.

Data Normalization (The Extractor)

To ensure the backend never returned a 400 Bad Request, I built an alias layer in the code node that maps unpredictable AI outputs to the exact schema required by the database.

const blogPost = {\n title,\n slug,\n excerpt,\n content,\n coverImageId: null, // Nullable is allowed here\n category: raw.category ?? undefined, // Undefined is required for .optional()\n tags: Array.isArray(tags) ? tags : [],\n featured: raw.featured === true,\n status: ['DRAFT', 'PUBLISHED', 'ARCHIVED'].includes(raw.status) ? raw.status : 'DRAFT',\n // Fields like authorId and createdAt are intentionally omitted\n};

Key Lessons Learned

  • Never trust AI JSON: Always set responseMimeType: \"application/json\" on the API call, and always write a normalization layer to handle rogue field names.
  • Zod vs. TypeScript: Your database schema and your API validation schema are two different things. You must test what the API actually accepts, not just what the model expects.
  • n8n Header Management: When dealing with cookies, enable \"Include Response Headers\" and \"Follow Redirects: OFF\" on the login node, or the Set-Cookie header will be lost.

The Result

I can now generate a complete, perfectly formatted, SEO-ready blog post in under 2 minutes simply by filling out a form in n8n. The workflow handles the AI generation, the HTML wrapping, the authentication, and the database insertion automatically.

Related Services

Business Automation

Let's Create Something Extraordinary

Have a project in mind? Let's discuss how we can bring your vision to life.

Start a Project