Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create XML sitemap for Next.js projects
#! /usr/bin/env node
const path = require('path');
const glob = require('glob');
const fs = require('fs');
const SITE_ROOT = 'https://example.com';
const SOURCE = path.join(__dirname, '..', 'pages', '/**/*.js');
const DESTINATION = path.join(__dirname, '..', 'static', 'sitemap.xml');
let diskPages = glob.sync(SOURCE);
let xml = '';
xml += '<?xml version="1.0" encoding="UTF-8"?>';
xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
diskPages.forEach((page) => {
let stats = fs.statSync(page);
let mod = new Date(stats.mtime);
let lastMod = `${mod.getFullYear()}-${('0' + (mod.getMonth() + 1)).slice(-2)}-${('0' + mod.getDate()).slice(-2)}`;
page = page.replace(path.join(__dirname, '..', 'pages'), '');
page = page.replace(/.js$/, '');
if (page !== '/_app' && page !== '/_document') {
const priority = page === '/index' ? '1.0' : '0.5';
page = `${SITE_ROOT}${page}`;
if (page.match(/.*\/index$/)) {
page = page.replace(/(.*)index$/, '$1');
}
xml += '<url>';
xml += `<loc>${page}</loc>`;
xml += `<lastmod>${lastMod}</lastmod>`;
xml += `<changefreq>always</changefreq>`;
xml += `<priority>${priority}</priority>`;
xml += '</url>';
}
});
xml += '</urlset>';
fs.writeFileSync(DESTINATION, xml);
console.log(`Wrote sitemap for ${diskPages.length} pages to ${DESTINATION}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.