Skip to content

Instantly share code, notes, and snippets.

@treckstar
Created April 11, 2023 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treckstar/bc45bf33c86377818afd02e6b3c85787 to your computer and use it in GitHub Desktop.
Save treckstar/bc45bf33c86377818afd02e6b3c85787 to your computer and use it in GitHub Desktop.
Sitemap.xml Generator using next-sitemap, uniformdev, & contentful
// Import required packages and functions
const fs = require('fs');
const { SitemapStream, streamToPromise } = require('sitemap');
const { createGzip } = require('zlib');
const { getSiteMapUrls } = require('@uniformdev/next-jss/server');
// Set up Uniform and Contentful credentials
const UNIFORM_API_KEY = process.env.UNIFORM_API_KEY;
const CONTENTFUL_SPACE_ID = process.env.CONTENTFUL_SPACE_ID;
const CONTENTFUL_ACCESS_TOKEN = process.env.CONTENTFUL_ACCESS_TOKEN;
// Set up Next.js config
const nextConfig = require('./next.config.js');
// Set up sitemap options
const options = {
changefreq: 'weekly',
priority: 0.5,
lastmod: new Date(),
hostname: nextConfig.env.NEXT_PUBLIC_SITE_URL,
};
// Create sitemap stream and gzip it
const sitemapStream = new SitemapStream(options);
const pipeline = sitemapStream.pipe(createGzip());
// Get site map urls using Uniform's getSiteMapUrls function
(async () => {
const siteMapUrls = await getSiteMapUrls(
UNIFORM_API_KEY,
CONTENTFUL_SPACE_ID,
CONTENTFUL_ACCESS_TOKEN
);
// Add each URL to the sitemap stream
siteMapUrls.forEach((url) => {
sitemapStream.write({
url: `${options.hostname}${url}`,
changefreq: options.changefreq,
priority: options.priority,
lastmod: options.lastmod,
});
});
// End sitemap stream and gzip it
sitemapStream.end();
await streamToPromise(pipeline).then((sm) => {
// Write the sitemap file to the public directory
fs.writeFileSync('./public/sitemap.xml.gz', sm);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment