Automating blog publishing can save repetitive handoffs, but a workflow that sends AI output straight to a live site can also publish duplicates, unsupported claims, or malformed content. A safer design treats publishing as a controlled pipeline: topics enter a queue, n8n coordinates generation and validation, a person reviews the draft, a publishing API creates the post, MongoDB records each state, and email reports the outcome.
This is a reproducible architecture, not a report of measured production results. Any performance or outcome figures in a real deployment should be measured rather than assumed.
Key takeaways
- Use a persistent topic queue and explicit states so work can be resumed and audited.
- Prevent duplicates with database uniqueness constraints and idempotency at the publishing API.
- Validate AI output before it reaches a reviewer or publisher, and require human approval for factual content.
- Retry transient failures carefully; retries alone do not guarantee a request ran only once.
- Keep API credentials in n8n's credential store or an equivalent secret manager, not in workflow data or code.
Architecture: from topic queue to published post
A practical workflow separates orchestration, state, and publishing:
- Topic queue: MongoDB holds topics and their processing state. A topic can include a target audience, primary keyword, brief, and optional source requirements.
- n8n trigger: A Schedule Trigger or a manual trigger starts a run. For a small site, a scheduled run can select one eligible topic at a time.
- Topic claim: The workflow claims a queued topic and marks it
processingso another run does not pick it up concurrently. - OpenAI generation: n8n sends a constrained prompt and requests structured fields such as title, slug, summary, and Markdown body.
- Validation: A Code node or validation service checks required fields, length limits, allowed values, and content-specific rules. Invalid output goes to an error or revision path, not straight to publishing.
- Review gate: The draft is saved with a
needs_reviewstate. A reviewer approves or rejects it through your existing review process before the workflow continues. - Publishing API: After approval, n8n sends the content and a stable idempotency key to an authenticated API that creates the post.
- MongoDB update and email: The workflow records the API result and sends a notification. Email is an alert, not the authoritative record of whether publishing succeeded.
Example document and state model
Keep workflow state explicit. The following document is illustrative; adapt field names and retention policies to your application:
{
"_id": "topic-2025-014",
"topic": "How canonical URLs work",
"keyword": "canonical URL guide",
"status": "queued",
"attempts": 0,
"createdAt": "2025-03-08T12:00:00.000Z",
"draft": null,
"publishedPostId": null,
"lastError": null
}
A useful state progression is queued → processing → needs_review → approved → published. Add rejected and failed states as needed. Store timestamps for transitions and avoid overwriting useful error context when retrying.
Prevent duplicate work and duplicate posts
There are two separate duplicate problems: processing the same topic more than once, and creating the same post more than once after a publishing request is retried.
Deduplicate topic submissions
Choose a stable key based on your editorial rules, such as a normalized topic identifier or a unique content brief ID. Enforce it in MongoDB with a unique index rather than relying only on a search step in n8n:
db.topic_queue.createIndex({ _id: 1 }, { unique: true });
MongoDB already creates a unique index on _id; if you use a separate field such as topicKey, create a unique index on that field instead. Define normalization carefully: two briefs that look similar may still represent distinct articles, while trivial punctuation changes may not.
Claim a topic safely
A workflow that reads a queued record and updates it in separate steps can race with another workflow execution. Prefer an atomic claim operation, such as a conditional find-and-update that changes queued to processing only if the record is still queued. If your n8n MongoDB node does not support the needed atomic operation, use a small authenticated service or database operation that does. Do not assume a workflow-level check prevents concurrent claims.
Make publishing idempotent
If the publisher creates a post but the response times out, n8n may not know whether the post exists. Retrying a normal create request can then create a duplicate. Have the publishing API accept an idempotency key derived from the topic or approved draft ID. The API should store the key and return the original result when it receives the same key again. Also consider a unique constraint on the publisher's external content identifier.
The API's behavior matters: an Idempotency-Key header has no effect unless the receiving service implements it. Record the returned post ID in MongoDB after a successful response, and reconcile uncertain timeouts by checking the API using the stable key before issuing another create request.
Generate structured drafts with OpenAI
Give the model a well-defined brief rather than an unbounded instruction. Specify audience, purpose, required sections, tone, output schema, and what to do when source information is missing. Ask it to distinguish supplied facts from claims that need verification. A structured response makes validation easier, but valid JSON does not make the content factually correct.
A useful draft contract might require:
title: non-empty string within your site's title limit.slug: lowercase letters, digits, and hyphens only.bodyMarkdown: non-empty Markdown string.claimsToVerify: array of factual claims needing editorial checks.sourceNotes: source material supplied by the editor, or an empty array.
Avoid asking the model to invent citations or URLs. If the article requires research, provide trusted source material or require a reviewer to verify each citation against the original source. Treat model output as untrusted input: validate structure, render Markdown safely in your publishing system, and apply your normal content and access controls.
Validate before review or publication
Validation should be deterministic wherever possible. Check that required fields exist, strings are within configured limits, the slug matches an allowed pattern, and the status transition is permitted. You can perform basic checks in a JavaScript validation step:
function validateDraft(draft) {
const errors = [];
if (!draft || typeof draft !== "object") {
return ["Draft must be an object"];
}
if (typeof draft.title !== "string" || draft.title.trim().length === 0) {
errors.push("Title is required");
}
if (typeof draft.slug !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(draft.slug)) {
errors.push("Slug must contain lowercase letters, digits, and single hyphens");
}
if (typeof draft.bodyMarkdown !== "string" || draft.bodyMarkdown.trim().length === 0) {
errors.push("Body Markdown is required");
}
if (!Array.isArray(draft.claimsToVerify)) {
errors.push("claimsToVerify must be an array");
}
return errors;
}
This is a basic shape check, not a complete content policy or security boundary. Add length limits, allowed categories, required metadata, and checks specific to your site. Send validation failures to a review or repair path with the errors attached; do not silently discard them.
Add a human review gate
For a factual blog, approval should be a distinct state transition, not merely an email containing a draft. A reviewer should be able to inspect the complete content, verify claims and sources, edit the draft, and explicitly approve or reject it. Store the reviewer identity, decision, and timestamp.
One straightforward pattern is to stop the generation workflow after saving the draft as needs_review. A separate approval action starts a publishing workflow only after it confirms that the record is still awaiting review. If your review interface uses links in email, make them authenticated and resistant to accidental approval by automated link scanners; an email click should not be the only authorization check.
API authentication, retries, and failure handling
Protect credentials
Use n8n's credential management or a dedicated secrets manager for OpenAI, MongoDB, email, and publishing API credentials. Restrict each credential to the permissions it needs, use HTTPS for API traffic, rotate credentials according to your operational policy, and avoid placing secrets in prompts, execution logs, or error emails. Confirm that access to workflow definitions and execution data is limited to appropriate operators.
For the publishing API, use a dedicated service identity with permission to create or update posts, rather than a broad administrative account. Verify authentication and authorization on the server; hiding a token in the workflow does not make an insecure publishing endpoint safe.
Retry deliberately
Retry transient failures such as rate limits or temporary service errors with a bounded attempt count and backoff. Do not endlessly retry invalid output, rejected content, or authentication failures. Configure an error path that records the failure, updates the topic state, and notifies an operator when automatic recovery is exhausted.
A timeout is an uncertain result, not proof that the request failed. For publishing calls, use the idempotency and reconciliation approach described above. For email, tolerate the possibility that a notification is delayed or duplicated; do not use email delivery as the only indication of publication status.
A step-by-step n8n build
- Create a MongoDB collection for topic records and define the unique key used to identify each brief.
- Add a trigger and a safe topic-claim operation. Make concurrent executions either claim different topics or leave a topic untouched.
- Send only the necessary brief fields to OpenAI. Keep prompt instructions separate from user-supplied topic text so submitted content cannot redefine workflow rules.
- Parse and validate the response. Save a valid draft and its model request metadata according to your privacy and retention requirements.
- Set the record to
needs_reviewand notify the reviewer. End the generation run here. - On approval, verify the current state again, then call the publishing API with an idempotency key.
- Record the publisher's response and post ID in MongoDB. Mark the record
publishedonly after the API confirms success. - Send a concise success or failure notification with a link to the internal record, not secrets or unnecessary personal data.
- Test duplicate triggers, concurrent runs, malformed model output, API timeouts, rejected approvals, and email failures in a staging environment before enabling scheduled production runs.
Common mistakes
- Checking for duplicates only in n8n: Separate lookup and insert steps can race. Use database uniqueness and atomic state transitions.
- Treating retries as exactly-once execution: Networks can fail after a server completes work. Use idempotency at the publishing boundary.
- Publishing when JSON parses: Structured output can still contain false claims, broken Markdown, or unsuitable content. Validate fields and review substance.
- Making approval a notification rather than a gate: The publishing workflow must independently confirm approval before creating a post.
- Marking a post published before the API confirms it: Update the state based on the API response, and reconcile ambiguous outcomes.
- Putting secrets in workflow expressions: Expressions and logs can be exposed to people with workflow access. Use managed credentials and least privilege.
- Assuming AI can verify its own claims: A model's confidence or self-reported source list is not evidence. Check important facts against reliable original sources.
Conclusion
A dependable n8n publishing workflow is more than a prompt connected to a publish button. A persistent topic queue, atomic claims, deterministic validation, a real review gate, authenticated API calls, idempotent publishing, bounded retries, and clear notifications make the process easier to operate and recover. Keep factual verification with an accountable editor, and treat automation as a way to coordinate publishing work—not as proof that generated content is correct.
