Raddy Website Design & Development Tutorials

NextJs 14 Dynamic XML Sitemap

By Raddy in NextJs ·

In this video I want to share how I made a dynamic XML sitemap using NextJS 14. To illustrate this, I will be using MongoDB as a local data source and I will go thru setting up the re-validation of the sitemap to ensure that fresh data is fetched at specific intervals of our choosing.

Example code:

import { connectToDatabase } from "@/utils/connectMongo";

export const revalidate = 3600 // one hour

export default async function sitemap() {
  
  const client = await connectToDatabase();
  const db = client.db("database");
  let data = await db.collection("product").find({}).toArray();

  const products = data.map((item) => ({
    url: `${process.env.NEXT_WEBSITE_URL}/product/${item.slug}`,
    lastModified: item.updated_at || item.created_at,
    changefreq: "monthly",
    priority: 0.6,
  })); 

  return [
    {
      url: "https://website.com/",
      lastModified: new Date(),
      changefreq: "daily",
      priority: 1,
    },
    {
      url: "https://website.com/about",
      lastModified: new Date(),
      changefreq: "weekly",
      priority: 1,
    },
    ...products,
  ];
}
  1. jaya says:

    can you share me the above repo url,as i want to generate dynamic sitemap.xml file but after building sitemap.xml is not creating

    1. Raddy says:

      I pasted the code in the article above. Just change your database query and fields and it should work

Leave a Reply

Your email address will not be published. Required fields are marked *