How to create a sitemap.xml file for Next.js

I have found Next.js to be an incredibly productive development tool when building content-rich websites that need a focus on Search Engine Optimisation (SEO). There is, however, one area that Next.js doesn't perform so well in - and that's automatically generating a sitemap for Statically Generated (SG) pages.

As a result, I am sharing a quick and hacky way around this which will allow you to generate a sitemap everytime you rebuild and export your Next.js application using Static Generation.

How to create a sitemap file for Next.js Statically Generated websites

Step 1: Create a new script within your package.json file and call it postexport.

...
"postexport": "node scripts/post-export.script.js"
...

In case you didn't know already, appending the name of your script within post makes it automatically run after the command is executed with npm. So in this example, the postexport command will run automatically once npm run export completes.

Step 2: Now create a script file in the scripts/ directory and call it post-export.script.js. It's unlikely you already have this folder, so create it if you don't already.

Step 3: Next, you need a list of your statically generated pages and URLs. For smaller projects, you might have this as a list. Or you may choose to traverse the filesystem using Node.js' fs package to read the filenames.

For larger projects, you are most likely retrieving content from an API or database. Your implementation for this step will vary, but to keep things simple for this guide I will use a hard-coded list of pages.

In the new file you have created (scripts/post-export.script.js) add the following code:

// base URL for your website
const baseUrl = "https://www.technouz.com"

// hardcoded URLs for static pages
const SG_PAGES = [
    "about-us",
    "contact-us",
    "find-out-more",
    "pricing"
];

// this function uses SG_PAGES to create the sitemap file
function createSitemap() {
    xml += '<?xml version="1.0" encoding="UTF-8"?>';
    xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

    SG_PAGES.forEach(page => {
        xml += "<url>";
        xml += `<loc>${baseUrl}/${page}</loc>`;
        xml += `<priority>0.5</priority>`;
        xml += "</url>";
    });

    xml += "";


    // write the sitemap.xml file
    // directory MUST be `out/`
    fs.writeFile("out/sitemap.xml", xml);
}

// execute the createSitemap() function
createSitemap();

module.exports = createSitemap;

Step 4: Now everytime you run npm run export to build a statically generated version of your Next.js app a sitemap.xml file will also be included in the out/ directory.

In a later post, I'll show you how you can build the sitemap automatically using pages in the pages/ directory. Send me a tweet if this is something you'd like to see.