N
Nuxt2y ago
SunTzu

Generate Sitemap on server side of nuxt

Is it possible to generate the sitemap for the public directory on the server side of nuxt?
2 Replies
SunTzu
SunTzuOP2y ago
Create a file (and directories if needed) /server/routes/sitemap.xml.ts
No description
SunTzu
SunTzuOP2y ago
Add the sitemap library yarn add sitemap Then here is the code to go into sitemap.xml.ts
import { SitemapStream, streamToPromise } from "sitemap";
// Import whatever database client

export default defineEventHandler(async (event) => {
try {
const config = useRuntimeConfig(); // Needed for access to .env

const { data } = (insert your database client
const sitemap = new SitemapStream({
hostname: "https://domain.com",
});
sitemap.write({
url: `/`,
changefreq: "weekly",
});
sitemap.write({
url: `/info`,
changefreq: "daily",
});

for (let c = 0; c < data?.length; c++) {
let page = data[c];
if (page.hidden == false) {
sitemap.write({
url: `/info/${page.url_path}`,
changefreq: "monthly",
lastmod: page.updated_at,
});
}
}

sitemap.end();
return streamToPromise(sitemap);
} catch (e) {
console.log(e);
}
});
import { SitemapStream, streamToPromise } from "sitemap";
// Import whatever database client

export default defineEventHandler(async (event) => {
try {
const config = useRuntimeConfig(); // Needed for access to .env

const { data } = (insert your database client
const sitemap = new SitemapStream({
hostname: "https://domain.com",
});
sitemap.write({
url: `/`,
changefreq: "weekly",
});
sitemap.write({
url: `/info`,
changefreq: "daily",
});

for (let c = 0; c < data?.length; c++) {
let page = data[c];
if (page.hidden == false) {
sitemap.write({
url: `/info/${page.url_path}`,
changefreq: "monthly",
lastmod: page.updated_at,
});
}
}

sitemap.end();
return streamToPromise(sitemap);
} catch (e) {
console.log(e);
}
});
Want results from more Discord servers?
Add your server