Most Markdown blogs can publish a feed and a sitemap with one small script. The feed lets readers and feed readers find new posts. The sitemap tells search engines which URLs exist and when they changed. Both files come from the same front matter, so they stay in sync when you add a post.

I'll walk through a Node.js script that reads posts from content/posts, skips drafts, sorts by date, and writes feed.xml and sitemap.xml into public/. Then I'll wire it into the build on Vercel.

1. Front matter for each post

Each post is a Markdown file with a small YAML block at the top. Use ISO dates (2025-03-04). They are the easiest format to parse reliably.

--- title: "Why my scraper keeps getting blocked" date: 2025-03-04 description: "Rate limits, headers and the three things I check first." slug: scraper-blocked draft: false --- The post body goes here. 

The slug is optional. If you leave it out, the script uses the file name. updated is also optional. When it's set, the sitemap uses it as lastmod. draft: true keeps a post out of both files.

2. Install the parser

npm install gray-matter 

gray-matter splits the front matter from the body and returns the fields as an object. You don't need the body for the feed, so the script ignores it.

3. The script

Save this as scripts/build-feeds.mjs. The only dependency is gray-matter from step 2. I build the XML by hand because the structure is small and easy to read.

// scripts/build-feeds.mjs import fs from "node:fs/promises"; import path from "node:path"; import matter from "gray-matter"; const SITE_URL = (process.env.SITE_URL || "").replace(/\/+$/, ""); if (!/^https?:\/\//.test(SITE_URL)) { throw new Error("SITE_URL must be an absolute URL, e.g. https://example.com"); } const SITE_TITLE = "My Blog"; const SITE_DESCRIPTION = "Notes on building web apps, scrapers and bots."; const POSTS_DIR = path.resolve("content/posts"); const OUT_DIR = path.resolve("public"); const postUrl = (slug) => `${SITE_URL}/blog/${slug}`; function escapeXml(value = "") { return String(value) .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&apos;"); } async function loadPosts() { const files = (await fs.readdir(POSTS_DIR)).filter((f) => f.endsWith(".md")); const seen = new Set(); const posts = []; for (const file of files) { const raw = await fs.readFile(path.join(POSTS_DIR, file), "utf8"); const { data } = matter(raw); if (data.draft === true) continue; const slug = String(data.slug || file.replace(/\.md$/, "")); const date = new Date(data.date); const updated = data.updated ? new Date(data.updated) : date; if (!data.title || Number.isNaN(date.getTime())) { throw new Error(`${file}: needs a title and a valid date`); } if (seen.has(slug)) { throw new Error(`Duplicate slug "${slug}" in ${file}`); } seen.add(slug); posts.push({ title: String(data.title), description: String(data.description || ""), slug, date, updated, }); } posts.sort((a, b) => b.date - a.date); return posts; } function buildRss(posts) { const items = posts .map((p) => { const url = escapeXml(postUrl(p.slug)); return ` <item> <title>${escapeXml(p.title)}</title> <link>${url}</link> <guid isPermaLink="true">${url}</guid> <pubDate>${p.date.toUTCString()}</pubDate> <description>${escapeXml(p.description)}</description> </item>`; }) .join("\n"); return `<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>${escapeXml(SITE_TITLE)}</title> <link>${escapeXml(SITE_URL)}</link> <description>${escapeXml(SITE_DESCRIPTION)}</description> <language>en-us</language> <lastBuildDate>${new Date().toUTCString()}</lastBuildDate> <atom:link href="${escapeXml(SITE_URL)}/feed.xml" rel="self" type="application/rss+xml" /> ${items} </channel> </rss> `; } function buildSitemap(posts) { const entries = [ ` <url>\n <loc>${escapeXml(SITE_URL + "/")}</loc>\n </url>`, ...posts.map( (p) => ` <url> <loc>${escapeXml(postUrl(p.slug))}</loc> <lastmod>${p.updated.toISOString().slice(0, 10)}</lastmod> </url>` ), ]; return `<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> ${entries.join("\n")} </urlset> `; } const posts = await loadPosts(); await fs.mkdir(OUT_DIR, { recursive: true }); await fs.writeFile(path.join(OUT_DIR, "feed.xml"), buildRss(posts), "utf8"); await fs.writeFile(path.join(OUT_DIR, "sitemap.xml"), buildSitemap(posts), "utf8"); console.log(`Wrote feed.xml and sitemap.xml with ${posts.length} posts`); 

Three details matter here. toUTCString() produces a string like Tue, 04 Mar 2025 00:00:00 GMT, which is the RFC 822 style RSS 2.0 expects. toISOString().slice(0, 10) gives the YYYY-MM-DD form the sitemap protocol accepts. The script throws on a missing title, a bad date or a duplicate slug, so a broken post fails the build instead of producing a broken feed.

4. Make it run before every build

Add the script as a prebuild step. npm runs prebuild automatically before build, so you don't have to change anything else.

{ "scripts": { "prebuild": "node scripts/build-feeds.mjs", "build": "vite build" } } 

Replace vite build with whatever your project uses, such as next build. For local testing, run the script with the site URL set. On Windows PowerShell, set the variable with $env:SITE_URL="http://localhost:3000" first.

SITE_URL=http://localhost:3000 npm run build 

On Vercel, open the project settings, find the environment variables section, and add SITE_URL with your real domain, such as https://example.com. Set it for Production. The build script reads it, not the browser, so it doesn't need a VITE_ or NEXT_PUBLIC_ prefix. Then push a commit so Vercel rebuilds.

5. Link the feed from the HTML head

Put this tag inside the <head> of your base layout or index.html. Feed readers and browsers use it to find the feed from any page.

<link rel="alternate" type="application/rss+xml" title="My Blog" href="https://example.com/feed.xml" /> 

Use the absolute URL here too.

6. Check the output

Start with a quick well-formedness check on your own machine. If xmllint is installed, run it on both files.

xmllint --noout public/feed.xml && xmllint --noout public/sitemap.xml 

Then deploy and open https://example.com/feed.xml in the browser. Paste the live URL into the W3C Feed Validation Service at validator.w3.org/feed. It catches date formats, missing required channel fields and bad escaping. For the sitemap, submit the URL in Google Search Console under the Sitemaps report.

Things that bit me

The most common problem was a feed that never updated. I had set the Vercel build command in the dashboard to vite build directly. Vercel ran that command, so prebuild never ran and the old feed stayed live. Keep the build command as npm run build, or put the script call inside the command itself.

Dates in front matter caused the next problem. The date check in loadPosts only catches values JavaScript can't parse. A value like March 4, 2025 gets through and is read in local time, which can shift the date. I switched every post to ISO dates. Keep the dates in the same format across all posts.

On a Vite single page app, a missing feed.xml can look like success. The app's rewrite rule sends unknown paths to index.html, so the URL returns HTML with a 200 status. Open the file in the deployed build output to confirm it exists. If the browser shows HTML instead of XML, check your rewrite rules.

Last, a SITE_URL with a trailing slash or a localhost value leaks into every link. The script strips the trailing slash, and the throw catches a missing scheme. It won't catch localhost with a valid scheme, so check the live feed for localhost after your first production deploy.

If you want help wiring something like this into an existing site, you can see other things I build.

FAQ

Why does my RSS feed show an invalid pubDate error?

RSS 2.0 expects the RFC 822 date format, such as Tue, 04 Mar 2025 00:00:00 GMT. Calling toUTCString() on a JavaScript Date produces that format. Writing the date as 2025-03-04 in the feed will fail validation.

How do I stop draft posts from appearing in the sitemap?

Add draft: true to the post's front matter. The script skips any post with that flag before it builds either file. Draft posts are then missing from both feed.xml and sitemap.xml.

Why isn't my feed updating after I add a new post?

The feed is written during the build, so a new post only shows up after a new deploy. Check that your build command runs npm run build so that prebuild runs first. If the build command skips the script, the old feed.xml stays live.

Originally published at watershowdigital.com/blog/generate-rss-feed-sitemap-markdown-blog-nodejs. Need a hand with your app or automation? WaterShow Digital fixes and builds it, fixed quote first.