Publish Posts via the dev.to API Without Duplicates
By: Evgeny Padezhnov
One POST request publishes an article on dev.to. The trouble starts with the second request.
Developers who cross-post from a personal blog often write a quick script, run it twice, and end up with two identical articles. Others lose search traffic because the copy on dev.to outranks the original. And some find out too late that the API has no image upload endpoint.
This guide covers the full publishing loop. It starts with getting a key, then covers creating drafts, updating instead of duplicating, setting a canonical URL, and running it from CI. The API is part of Forem, the open-source platform behind dev.to. Its reference lives at developers.forem.com.
Why automate dev.to publishing at all
Manual cross-posting means copy, paste, fix formatting, re-add tags, and set the canonical link. It takes only a few minutes per post. Teams that publish weekly repeat it often enough to make mistakes.
According to Sourcegraph's guide on automating repetitive tasks, the first step is identifying the repetitive task. The second is choosing a tool that fits. Cross-posting passes both tests. The task is identical every time, and the dev.to API is a small, stable surface.
A breakdown of blog automation tools on YouTube splits a blog post into six stages: ideation, research, drafting, optimization, publishing, and distribution. Most tools only touch drafting, by that video's account. Publishing and distribution stay manual. A short script against the dev.to API closes exactly that gap.
In plain terms: the original stays on the site the author owns, and dev.to gets a synced copy. The script keeps both in step.
Step 1: Get an API key and store it safely
The key is generated in the dev.to account settings. Open Settings, then Extensions, and find the "DEV Community API Keys" section. Give the key a name and generate it.
The key grants write access to the account. Treat it like a password.
- Store it in an environment variable, for example
DEVTO_API_KEY. - Keep it out of the repository. Add
.envto.gitignore. - In CI, use the platform's secret storage, not a plain variable.
- Revoke and regenerate the key if it ever lands in a log or a commit.
Common mistake: printing the full request headers while debugging. The key travels in the api-key header, so a verbose log leaks it.
A quick check that the key works:
curl -s https://dev.to/api/articles/me/all \
-H "api-key: $DEVTO_API_KEY" \
-H "Accept: application/vnd.forem.api-v1+json" | head -c 300
A JSON array means the key is valid. A 401 means the key is wrong or revoked.
The Accept header selects version 1 of the Forem API. Older examples online omit it. Sending it explicitly protects the script from silent behavior changes.
Step 2: Create the article as a draft
The endpoint is POST https://dev.to/api/articles. The body wraps all fields in an article object.
curl -s -X POST https://dev.to/api/articles \
-H "api-key: $DEVTO_API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/vnd.forem.api-v1+json" \
-d '{
"article": {
"title": "Publishing via the dev.to API",
"body_markdown": "## Intro\n\nArticle text in Markdown.",
"published": false,
"tags": ["devto", "api", "automation"],
"canonical_url": "https://example.com/blog/devto-api/",
"description": "Short summary for previews."
}
}'
The response contains the new article's id and url. Save the id. Every later update depends on it.
The fields that matter most:
| Field | Purpose |
|---|---|
title |
Article title |
body_markdown |
Full body in Markdown |
published |
false creates a draft, true publishes immediately |
tags |
Up to four tags, lowercase, no spaces |
canonical_url |
Link to the original post |
main_image |
Cover image URL |
series |
Groups related posts into a series |
description |
Preview text in feeds and link cards |
Key point: start with "published": false. A draft can be reviewed in the dev.to editor. A published post is visible in feeds at once, and deleting it afterwards does not unsend notifications to followers.
Front matter inside body_markdown
dev.to also accepts Jekyll-style front matter at the top of body_markdown:
---
title: Publishing via the dev.to API
published: false
tags: devto, api, automation
canonical_url: https://example.com/blog/devto-api/
cover_image: https://example.com/img/cover.png
---
## Intro
This is convenient when the source files already have front matter. But mixing both styles causes confusion. A field in the front matter and a different value in the JSON leaves it unclear which one wins.
Pick one source of truth. For scripts, JSON fields are easier to control. Strip the original blog's front matter before sending, since its keys rarely match dev.to's names.
Step 3: Update instead of creating twice
The duplicate problem comes from re-running the script. Each POST creates a new article. dev.to does not deduplicate by title or canonical URL.
The fix is to keep a mapping from the local post to the dev.to id. Then the script chooses between create and update.
- No stored
id: sendPOST /api/articles. - Stored
id: sendPUT /api/articles/{id}with the same body shape.
Where to store the mapping depends on the setup:
- Add a
devto_idfield to the post's front matter and commit it back. - Keep a small JSON file such as
devto-map.jsonin the repository. - Look the article up on each run via
GET /api/articles/me/alland match bycanonical_url.
Option 3 needs no state. It costs an extra request, and the list is paginated (page and per_page parameters). Option 1 is the most transparent, since the link between files is visible in the file itself.
Here is a dependency-free Node.js script (Node 18 or newer, built-in fetch). It uses option 3, so it is safe to run repeatedly.
// publish-devto.mjs
const API = "https://dev.to/api";
const headers = {
"api-key": process.env.DEVTO_API_KEY,
"Content-Type": "application/json",
"Accept": "application/vnd.forem.api-v1+json",
};
async function findByCanonical(canonical) {
for (let page = 1; page <= 20; page++) {
const res = await fetch(`${API}/articles/me/all?page=${page}&per_page=100`, { headers });
if (!res.ok) throw new Error(`List failed: ${res.status}`);
const items = await res.json();
if (items.length === 0) return null;
const hit = items.find((a) => a.canonical_url === canonical);
if (hit) return hit;
}
return null;
}
export async function upsert(article) {
const existing = await findByCanonical(article.canonical_url);
const url = existing ? `${API}/articles/${existing.id}` : `${API}/articles`;
const method = existing ? "PUT" : "POST";
const res = await fetch(url, { method, headers, body: JSON.stringify({ article }) });
if (res.status === 429) throw new Error("Rate limited: retry later");
if (!res.ok) throw new Error(`${method} failed: ${res.status} ${await res.text()}`);
const data = await res.json();
console.log(`${method} ok: id=${data.id} ${data.url}`);
return data;
}
The script has no external packages, which keeps the attack surface small. A publishing script that holds a write key is a poor place for a dependency tree.
Try it: run the script twice with the same canonical_url. The first run should log POST ok, the second PUT ok. Only one article should appear in the dashboard.
Handling errors and rate limits
The API returns standard HTTP codes. The common ones in practice:
401: missing or invalid key.422: validation error. Typical causes are too many tags, a tag with spaces, or an empty title.429: too many requests. Wait and retry with backoff.
Do not retry 422 automatically. The request will fail the same way every time. Print the response body. It usually names the offending field.
Step 4: Canonical URL and images
canonical_url protects the original
When the same text exists on two domains, search engines pick one as the primary version. Without a hint, a large platform like dev.to can win over a personal blog.
Setting canonical_url adds a <link rel="canonical"> tag to the dev.to page. It points search engines at the original. The dev.to copy still gets readers from the platform's own feed.
Common mistake: setting the canonical URL to a page that redirects or returns 404. Publish the original first, check that it loads, and only then cross-post.
Images must be hosted elsewhere
The public API has no upload endpoint. main_image and images inside body_markdown must be absolute URLs that already work.
Practical rules:
- Host images on the original blog or a CDN.
- Rewrite relative paths like
./img/chart.pngto fullhttps://URLs before sending. - Check that each URL returns
200and an image content type.
dev.to fetches and caches images on its side. A broken URL at publish time can leave a broken image in the post. A pre-flight check in the script catches this cheaply.
Step 5: Run it from CI
A natural trigger is a push to the blog's main branch. A GitHub Actions job can run the script for new or changed posts.
name: Cross-post to dev.to
on:
push:
branches: [main]
paths: ["content/blog/**"]
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@<full-commit-sha>
- uses: actions/setup-node@<full-commit-sha>
with:
node-version: "20"
- run: node scripts/crosspost.mjs
env:
DEVTO_API_KEY: ${{ secrets.DEVTO_API_KEY }}
Pin actions by full commit SHA, not by tag. A tag can be moved to different code later. A SHA cannot.
According to the Zenhub overview of automation tools, Jenkins is the long-standing open-source automation server for build and deploy pipelines. It suits the same job for teams already running it. For visual workflows, Collect's roundup describes n8n as a node-based tool where each service or action is a connectable node. An HTTP request node can call the dev.to API without writing a script.
For a single blog, a 40-line script in the existing CI is usually enough. A separate automation platform adds another system to maintain.
For readers building this with an AI coding agent, the guide on installing Claude Code covers the setup. The AI IDE stack review compares editors for tasks like this. Either way, review generated code before giving it a write key.
What did not work
A few approaches looked fine and failed in use:
- Publishing directly with
published: truefrom CI. One formatting bug went live to followers before anyone saw it. Drafts first, then a manual or scheduled flip. - Matching existing articles by title. Titles change during editing. The match broke and created a duplicate.
canonical_urlor a storedidis stable. - Sending the original Markdown unchanged. Site-specific shortcodes and relative image paths rendered as raw text. A small transform step is required.
Frequently Asked Questions
How do you handle images when publishing posts via the dev.to API?
The API does not accept file uploads. Host images on the original site or a CDN, and use absolute https:// URLs in body_markdown. Rewrite relative paths in the script before sending.
How do you set a cover image for a post using the dev.to API?
Pass a public image URL in the main_image field of the article object. If front matter is used instead, the equivalent key is cover_image. Verify the URL returns 200 before publishing.
Should you create posts as drafts first before publishing?
Yes. Create with published: false, check the rendered draft on dev.to, then send a PUT with published: true. A good signal to publish is a clean preview with working images and a canonical URL that resolves.
How do you use canonical_url when cross-posting?
Set canonical_url to the live URL of the original post. dev.to then marks the original as the primary version for search engines. Publish the original first so the link never points to a missing page.
How do you schedule posts to publish at a specific time?
The documented API offers no dependable scheduling field, so scheduling is handled outside dev.to. Create the post as a draft, then run a scheduled job (cron or a scheduled GitHub Actions workflow) that sets published: true at the chosen time.
What to try right now
Generate an API key, export it as DEVTO_API_KEY, and run the curl command from Step 2 with "published": false. Open the draft in the dev.to dashboard. If it renders correctly with the canonical URL set, the basic pipeline works. Everything else in this guide builds on that single request.
Information is accurate as of the publication date. Terms, prices, and regulations may change — verify with relevant professionals.