DEV Community

GreggHume
GreggHume

Posted on

4 3

Nuxt 2 dynamic sitemap with data from an api

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more