Nuxt 2 dynamic sitemap with data from an api
GreggHume

GreggHume @greggcbs

About: A developer who works with and on some of the worlds leading brands. My company is called Cold Brew Studios, see you out there :)

Joined:
Mar 10, 2021

Nuxt 2 dynamic sitemap with data from an api

Publish Date: May 16 '22
8 0

You want to dynamically build your sitemap off some dataset / api then this is for you.

Whether you have express api enabled in your nuxt project or not, this easy 3 step process will get you there.

// nuxt.config.js
export default {
  serverMiddleware: [
    { path: "/sitemap.xml", handler: "~/api/sitemap/index.js" },
  ],
};
Enter fullscreen mode Exit fullscreen mode
// folder structure
root
└───pages
└───api
  └───sitemap
      │  index.js
Enter fullscreen mode Exit fullscreen mode
// api/sitemap/index.js
const app = require("express")();

app.all("/", (req, res) => {
  try {
    // you can loop through some data and build this up
    let sitemap = `
      <?xml version="1.0" encoding="UTF-8"?>
      <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        <url>
          <loc>http://www.example.com/foo.html</loc>
          <lastmod>2018-06-04</lastmod>
        </url>
      </urlset>
    ` 

    res.set('Content-Type', 'text/html');
    res.status(200).send(Buffer.from(sitemap));
  } catch (error) {
    res.status(500).send(error.message)
  }
})

module.exports = app;
Enter fullscreen mode Exit fullscreen mode

Install express if you havent.

Visit your localhost site map route.

Comments 0 total

    Add comment