Skip to main content

Sitemap

This code is used to dynamically generate a sitemap using data fetched from an API or database via the fetchSitemap hook. To use this, you must create menu items on your cockpit CMS.

The sitemap contains a list of URLs and the last modified time of the pages within the web application.

Function getData​

The getData function is an asynchronous function responsible for fetching the sitemap data via the fetchSitemap hook.

import { fetchSitemap } from "@/lib/hook";

export async function getData() {
const data = await fetchSitemap(); // Fetch the sitemap data
return data; // Return the fetched data
}
  • fetchSitemap: A function that accesses data from a specific source (API, database, etc.) containing route and modification time information for the pages.
  • getData: Fetches the data and returns it to the caller.

Function sitemap​

The sitemap function is the sitemap generator that uses the data from getData. It processes the data and returns an array of objects in the format required for a sitemap XML.

export default async function sitemap() {
const data = await getData(); // Retrieve the sitemap data

// Mapping the data into the sitemap format
const listmain = data.map(item => ({
url: process.env.NEXT_PUBLIC_UR_DOMAIN + item.routes.default, // Construct the URL based on the route
lastModified: item.lastmod, // Add the last modification time
}));

return [...listmain]; // Return the list of URLs and last modified times
}

Explanation:​

  • getData: Calls the function that fetches the sitemap data.
  • listmain: An array generated by mapping each item from the data to an object containing the URL and the last modification time (lastModified).
    • url: Constructed from the domain, retrieved from the environment variable (process.env.NEXT_PUBLIC_UR_DOMAIN), and appended with the route from the data.
    • lastModified: The last modification time of the page.
  • Return Value: Returns an array containing the sitemap objects for each page.

Example Sitemap Output​

The output of this function is a list of objects with the following format:

https://yourdomain.com/sitemap.xml
[
{
"url": "https://domain.com/page1",
"lastModified": "2024-08-17"
},
{
"url": "https://domain.com/page2",
"lastModified": "2024-08-16"
}
]

Environment Requirements​

  • process.env.NEXT_PUBLIC_UR_DOMAIN: This environment variable must be set to identify the main domain of the site.