reactjsnext.jsgraphqlsitemap

Next js Sitemap static export


I need help building a Sitemap for my NextJs project. I build a headless cms using graphql and next, however, everything is statically generated. I'm having a lot of issues creating a sitemap. I tried using the npm next-sitemap but all the info I find (youtube and forums) are for projects containing "serversideprops", when my project only contains "getStaticProps" and getStaticPaths. In addition to that I also require the map to handle dynamic paths [slug].js. ** I'm not using typescript

Here is what part of my [slug].js looks like:

graphql query....

export async function getStaticPaths() {   
    const { posts } = await graphcms.request(SLUGLIST);   
    return {
        paths: posts.map((post) => ({ params: { slug: post.slug } })),
        fallback: false,   
    }; 
}
     
export async function getStaticProps({ params }) {   
    const slug = params.slug;   
    const data = await graphcms.request(QUERY, { slug });  
    const { posts } = await graphcms.request(QUERY2);   
    const post = data.post;   
    return {
        props: {
            post,
            posts,
        },   
    }; 
}

Solution

  • next-sitemap also creates the routes based on the static pages you generate. The thing is you have to run it after you generated your project.

    Typically, you should have a configuration file like this at the base of your project:

    next-sitemap.config.js

    /** @type {import('next-sitemap').IConfig} */
    module.exports = {
      siteUrl: process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : 'https://my-fallback-url.com/',
      generateRobotsTxt: true,
      trailingSlash: true,
      targetDirectory: `${__dirname}/public`,
      // Wherever are your pages stored
      pagesDirectory: `${__dirname}/src/pages`,
    };
    

    and on your package.json

      "scripts": {
        ... other configurations
        "postbuild": "next-sitemap"
      },
    

    Which will trigger next-sitemap after your build is complete. You should then find all the generated xml files containing your sitemap.