What You Will Build

You will build a closed-loop AI video ad automation pipeline. It starts with a product brief. Seedance or Kling generates the video automatically. n8n orchestrates the handoff, creates the ad, implants UTM tracking at the campaign level, deploys it to Facebook or Google, and then loads performance data into a Postgres database. Metabase sits on top giving you a real-time dashboard of CPA, ROAS, and video completion rates.

This is not a theoretical architecture. It is a deployable system built with free tier APIs and open source tools that costs you essentially nothing in hosting. The only cost is your time.

Prerequisites

  • A Seedance account with API access
  • A Kling account with API access
  • n8n (self-hosted or cloud). Self-hosted gives you better rate limit control.
  • A Meta Business account or Google Ads account
  • Postgres database (Supabase free tier works perfectly)
  • Metabase instance (can run on the same server as n8n)
Before going further, understand the architecture. The pipeline does four things. It generates video, creates ads with tracking, ingests performance data, and visualizes it. Each piece is modular. You can swap out Seedance for Pika later. You can replace Metabase with Superset. The workflow logic stays the same.

Step 1: Pipeline Overview and Core Components

Most people approach ad creation as a series of disjointed manual tasks. Write copy. Brief a video editor. Wait 2 days. Download the file. Upload to Meta. Guess at the UTM tags. Check the dashboard the next morning.

That workflow is fragile and slow. It leaks budget because you cannot react fast enough.

The AI video ad automation pipeline collapses that cycle into a single trigger. You define your campaign variables once. The system handles the rest. Here is how the stack fits together.

Seedance and Kling are the video engines. They accept a text prompt and return a 5 to 15 second video clip. Both offer REST APIs which is the only thing that matters for automation. If they only had a web UI they would be useless here.

n8n is the central nervous system. It receives the trigger, calls the video APIs, waits for the video to render, stores the URL, then calls the Facebook Marketing API to create the ad. It also runs on a schedule to pull performance data.

Postgres stores two things. The video metadata and the performance metrics. Separating storage from your ad platform gives you historical data that Meta would delete after 90 days.

Metabase reads from Postgres and lets you build interactive dashboards without writing a lot of SQL. You can give a link to your team and they can filter by campaign or date range without touching the database.

This pipeline removes the lag between creative production and performance feedback. That lag is where money disappears. You will know if a video is working within hours, not days.

Step 2: Prerequisites and n8n API Setup for Ad Automation

Before writing any workflows you need your credentials organized in one place. I strongly recommend using environment variables in your n8n instance. Hard coding API keys into nodes is a security risk and it makes debugging miserable.

Seedance API Key: Log into Seedance, navigate to the developer panel, and generate a token. The key format is a bearer token. You will use it in the HTTP Request node.

Kling API Key: Kling uses a client ID and client secret pair. You call their auth endpoint first to get an access token, then call the video generation endpoint. This is a two-step process but n8n handles it cleanly with multiple HTTP nodes.

Meta App and Access Token: You need a Facebook App with the Marketing API permission. Generate a long-lived access token. The token needs the ads_management permission to create ads and ads_read to pull performance data.

Postgres Database: Create two tables. videos for metadata and ad_metrics for performance data.

CREATE TABLE videos (
    id SERIAL PRIMARY KEY,
    campaign_name TEXT,
    prompt TEXT,
    source TEXT,
    video_url TEXT,
    status TEXT DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE ad_metrics (
    id SERIAL PRIMARY KEY,
    date DATE,
    campaign_id TEXT,
    ad_id TEXT,
    impressions INT,
    clicks INT,
    spend NUMERIC(10, 2),
    conversions INT,
    video_views INT,
    utm_source TEXT,
    utm_campaign TEXT,
    created_at TIMESTAMP DEFAULT NOW()
);

Now configure n8n. In the n8n UI, go to Settings and add your credentials. Use the "HTTP Request" credential type for Seedance and Kling. Use the "Facebook Graph API" credential type for Meta. Store your Postgres connection string in the environment variables.

Test each credential before building the full pipeline. A single failed API key will block the entire chain and you will waste time debugging the wrong node.

Step 3: Building the AI Video Generation Workflow in n8n

This workflow is the creative engine. It receives a campaign brief and generates the video files. I recommend triggering it from a simple webhook. You POST a JSON payload with the campaign name, product description, and target audience. n8n does the rest.

Create a new workflow. Add a Webhook node as the trigger. The webhook URL is your endpoint. You will send data like this to it.

{
    "campaign_name": "Summer Sale 2026",
    "product_description": "Ergonomic standing desk with wireless charging",
    "target_audience": "remote workers aged 25-45",
    "call_to_action": "Shop Now"
}

Add an HTTP Request node to call the Seedance API. The endpoint is POST https://api.seedance.ai/v1/videos. Set the header to Authorization: Bearer YOUR_API_KEY. Use the product description as the prompt.

The polling pattern is critical here. Video generation takes 30 seconds to 2 minutes. The API returns a video ID immediately but the video URL is empty until processing finishes. You cannot rush this.

Add a Loop Over Items node or a Wait node followed by another HTTP Request node that checks the status. Wait 15 seconds, then call GET https://api.seedance.ai/v1/videos/{id}. Check if status equals completed. If not, wait and try again. Set a maximum number of retries, maybe 10 attempts, to avoid infinite loops.

Once the video URL comes back, store it in your Postgres database using the Postgres node. Insert the campaign name, prompt, source, and the video URL into the videos table.

INSERT INTO videos (campaign_name, prompt, source, video_url, status)
VALUES ('{{$node["Webhook"].json["campaign_name"]}}', '{{$node["Webhook"].json["product_description"]}}', 'seedance', '{{$node["HTTP Request"].json["video_url"]}}', 'completed');

Repeat the exact same steps for Kling but in a parallel branch. You want to generate one video from Seedance and one from Kling using the same prompt. This gives you a built-in A/B test before you even deploy the ad. n8n allows parallel branches easily. Split the output of the webhook into two HTTP Request nodes.

The result of this workflow is a database populated with video URLs and a clear trigger for the next step.

Step 4: Automating Ad Creation and Deployment with UTM Tracking

Now you have video files. The next workflow picks them up and turns them into live ads. This is where the automated ad deployment with UTM tracking happens.

Create a second n8n workflow. Trigger it from a Cron node or manually. The first step is a Postgres node that selects videos where status = 'completed' and ad_created = false. You only want to process each video once.

For each video, call the Facebook Marketing API node. You need to create three objects. An ad creative, an ad set, and an ad.

// Ad Creative JSON
{
    "object_type": "VIDEO",
    "video_id": "{{$node["Postgres"].json["video_url"]}}",
    "name": "AI Generated Video {{$node["Postgres"].json["id"]}}",
    "call_to_action_type": "SHOP_NOW",
    "link_url": "https://yourshopify.com/product?utm_source=facebook&utm_medium=video_ad&utm_campaign={{$node["Postgres"].json["campaign_name"] | urlencode}}&utm_content=video_{{($node["Postgres"].json["id"] | urlencode)}}"
}

Study that link_url closely. The UTM parameters are injected dynamically. utm_source is facebook. utm_medium is video_ad. utm_campaign is the campaign name from your original brief. utm_content includes the database ID of the video so you can trace which exact creative drove the conversion.

Most people forget the UTM entirely or use a static one. That is the difference between knowing that "Video A outperformed Video B by 40%" and guessing which creative worked because you only tracked the campaign level. Granular UTM tracking at the creative level is the difference between a growth engine and a black box.

After creating the ad creative, create the ad set. Define the budget (e.g., $50/day), the schedule (start immediately), and the targeting. Use the same campaign name variable to keep everything organized. Then create the ad by linking the ad creative and ad set.

Finally, update the videos table. Set ad_created = true so the workflow ignores it next time. Store the ad_id returned from Meta. You will need that to pull performance data later.

UPDATE videos SET ad_created = true, ad_id = '{{$node["Facebook Marketing API"].json["id"]}}' WHERE id = {{$node["Postgres"].json["id"]}};

This workflow runs on a loop, picking up new videos and deploying them as ads. No manual uploading. No copy paste errors in UTM strings. Every video gets consistent tracking.

Step 5: Setting Up the Real-Time BI Dashboard

Generating and deploying ads is only half the job. The other half is measuring what works and killing what does not. This is where the real-time ad performance dashboard Metabase comes in.

Create a third n8n workflow. Trigger it on a Cron schedule every 60 minutes. This workflow pulls data from the Facebook Marketing API using the ads_insights endpoint. It requests fields like impressions, clicks, spend, and conversions for the last 24 hours.

GET /v20.0/act_{ad_account_id}/insights
    ?fields=impressions,clicks,spend,actions,inline_link_clicks
    &level=ad
    &time_range={"since":"2026-07-01","until":"2026-07-02"}

The API returns an array of ad objects. Use n8n to map each object into a row for your ad_metrics table. The insert should use ON CONFLICT to handle duplicates gracefully if the workflow runs more than once for the same day.

INSERT INTO ad_metrics (date, campaign_id, ad_id, impressions, clicks, spend, conversions)
VALUES ('{{$node["HTTP Request"].json["date_start"]}}', '{{$node["HTTP Request"].json["campaign_id"]}}', '{{$node["HTTP Request"].json["ad_id"]}}', {{$node["HTTP Request"].json["impressions"]}}, {{$node["HTTP Request"].json["clicks"]}}, {{$node["HTTP Request"].json["spend"]}}, {{$node["HTTP Request"].json["actions"][0]["value"]}})
ON CONFLICT (date, ad_id) DO UPDATE SET impressions = EXCLUDED.impressions, clicks = EXCLUDED.clicks, spend = EXCLUDED.spend;

Now open Metabase. Connect it to the same Postgres database. Create a new dashboard. Add a filter widget for date range and campaign name. Then write SQL queries for your KPIs.

SELECT 
    date,
    ad_id,
    spend,
    clicks,
    CASE WHEN clicks > 0 THEN (spend / clicks) * 100 ELSE 0 END AS CPC,
    conversions,
    CASE WHEN conversions > 0 THEN spend / conversions ELSE 0 END AS CPA,
    CASE WHEN impressions > 0 THEN (clicks * 100.0 / impressions) ELSE 0 END AS CTR
FROM ad_metrics
WHERE date = current_date
ORDER BY spend DESC;

Build a bar chart showing CPA by ad over time. Build a table showing ROAS (revenue / spend). This dashboard updates every hour automatically. You will open it and see which creatives are profitable and which ones need to be paused.

Step 6: Orchestrating Error Handling and Scalability

A pipeline that breaks silently is worse than no pipeline. You will assume it works, spend money on broken creatives, and find out a week later. n8n error handling ad pipeline setup is not optional.

Add an Error Trigger node to a separate workflow. In n8n, you can set any active workflow to send errors to a dedicated error handler. When an API call fails, the error workflow sends a notification to Slack or email.

Read the error message. If it says "rate limit exceeded", implement backoff. Seedance and Kling have strict rate limits, usually 5 to 10 requests per minute. Use the n8n Wait node to pause 60 seconds before retrying.

Meta also has rate limits. If you send too many requests in a short window, Meta blocks your access token for an hour. Spread your data ingestion calls across the hour. The cron schedule of 60 minutes is intentional. It stays under the rate limit.

Structure your main workflow into sub workflows. Use the Execute Workflow node to call a separate workflow for video generation, ad deployment, and data ingestion. This makes the system modular. If the video generator fails, the ad deployment is not blocked. Sub workflows also make debugging easier because you can test each piece independently.

Monitor your API costs. Seedance and Kling charge per video generation. Set up a simple cost tracking table in Postgres. Log every API call and the cost. If you accidentally trigger 1000 video generations overnight, you will know exactly how much it cost and you can add circuit breakers to prevent it from happening again.

Step 7: Advanced Optimizations and Scale

Once the basic pipeline is stable, you can turn it into a true optimization machine. The goal is to scale AI ad pipeline optimization by letting the data drive decisions automatically.

A/B Testing at Scale. Your current setup generates one video per prompt. Modify it to generate three videos from slightly different prompts. Deploy all three as separate ads. After 24 hours, the dashboard will show which one has the best CPA. You can add a manual step or build an n8n branch that increases the budget allocation on the winner and pauses the losers.

CRM Integration. Connect the pipeline to HubSpot. When a user clicks the ad and fills a form, the UTM parameters flow into HubSpot. You can then attribute closed deals back to the specific AI generated video that started the journey. For proper attribution, make sure you implement server side tracking so cookie blockers do not eat your data. We wrote a deep guide on how to do that in our article about building a VSL funnel with server side tracking.

Multi Format Content. Seedance and Kling generate high quality standard videos. For specific placements like Instagram Stories or TikTok, experiment with Pika or Runway. The pipeline is modular. Just swap the HTTP Request node and prompt template. The rest of the workflow stays identical.

Turning it into a SaaS. If you build this for your own business and it works, consider packaging it. n8n supports multi tenant setups. You can white label the Metabase dashboard. Offer "AI Video Ad Automation" as a service to ecommerce brands. They provide the product link. You handle the generation, deployment, and reporting.

Common Pitfalls

  • Bad prompts produce bad videos. The video generator is only as good as the prompt. Test prompts manually before automating them. Once you find a prompt structure that works, lock it into a template.
  • UTM parameter corruption. If you use special characters in campaign names, URL encode them. A broken UTM tag means your analytics tool cannot parse the traffic.
  • Meta ad review delays. You can build the fastest pipeline in the world, but Meta still takes 15 minutes to 4 hours to review an ad. Account for that delay in your expectations. The ad is not live the instant you hit deploy.
  • Forgetting to join tables. Your ad_metrics table has ad_id. Your videos table has ad_id. You must join them in Metabase to see which prompt generated the video that drove the conversion.

Next Steps

You now have a fully functional AI video ad automation pipeline. It generates videos, deploys them with perfect tracking, and shows you performance in real time. That puts you miles ahead of teams still downloading videos and typing UTM strings by hand.

Do not stop here. Start A/B testing prompts aggressively. If you need help structuring your landing pages to convert better, read our guide on how to A/B test landing pages for higher Meta ad conversions. The combination of automated ad generation and optimized landing pages is where the real ROI lives.

Also review our list of proven Meta ad hooks to inject into your prompt templates. Great infrastructure amplifies great creative. Bad creative deployed perfectly is still bad.

If you want to go deeper into n8n, our guide on building an AI powered newsletter automation with n8n covers similar patterns for a different use case. The logic of triggers, HTTP calls, and database storage transfers directly. And if you are curious about how this fits into your overall team structure, the philosophy is the same as our case study on how to replace a $1,700/month team with AI. Build the system once. Let it run forever.

Cover photo by photoGraph on Pexels.