Make sitemap.xml markdown blog | A script to create sitemap.xml

Tue Jan 05 2021

- D. K. Dhabale

Cover Image

Script buildTools/buildSitemap.mjs

Read the comments and place your data where required. Dependencies - fs, path, gray-matter

import fs from "fs"
import { join } from "path"
import matter from "gray-matter"
;(() => {
// NOTE: Replace with your site's url
const site = ""
// NOTE: The directory where you store your posts, w.r.t. project root
const data = fs.readdirSync("./src/mdx/posts")
// NOTE: The posts directory, but without ./ in the beginning
const postsDirectory = join(process.cwd(), "src/mdx/posts")
const siteMapData = => {
//NOTE: Use the extension that you use in your blogs, md or mdx
const realSlug = slug.replace(/\.mdx$/, "")
const fullPath = join(postsDirectory, `${realSlug}.mdx`)
const fileContents = fs.readFileSync(fullPath, "utf8")
const { data } = matter(fileContents)
return { url: site + realSlug, date: }
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="">
.map((blog) => {
return `
<lastmod>${new Date(}</lastmod>
// NOTE: The output location
fs.writeFileSync("./public/sitemap.xml", sitemap)

Adding script to package.json

Add this script to package.json scripts object,

"prebuild":"node ./src/buildTools/buildSitemap.mjs",

This will run your script before running build.

Bonus: SEO Tip

You can submit your sitemap to the Google search console and request google to index it. Google Search Console


NPM Scripts docs -