2

I tried this post XML sitemap for Nextjs but it didn't help me out.

How to create a sitemap and robots.txt dynamically add it to nextjs project is my question. I have built a blog using nextjs and mongodb and express js. This is my project structure frontend(nextjs)

--.next
-- components
-- node_modules
-- pages
-- static
-- config.js
-- next.config.js
-- package.json
-- package-lock.json

jarivak
  • 828
  • 13
  • 28
  • You could take the approached mentioned in [Generating a dynamic /robots.txt file in a Next.js app](https://stackoverflow.com/a/67398847/1870780) for both sitemap and robots.txt - API route with rewrite. – juliomalves Sep 17 '21 at 20:57

1 Answers1

2

You can add an express route inside your server.js:

const sitemapString = '<?xml version="1.0" encoding="UTF-8"?>\n' +
    '<urlset\n' +
    // ...
    '</urlset>';

expressServer.get( "/sitemap.xml", function( req, res ){
    res.end( sitemapString );
});

Or create a file /pages/sitemap.xml.ts:

// -- dummy exported default, if necessary
export default function Dummy(props){
    return null;
};

export const getServerSideProps = async (context) => {
    const { res } = context;
    const sitemapString = createSitemap();

    res.setHeader("Content-Type", "text/xml");
    res.write(sitemapString);
    res.end();

    return {
        props: {},
    };
};

Or you can create the sitemap.xml statically and put it into the /public folder.

kca
  • 4,856
  • 1
  • 20
  • 41
  • In new Next.js versions (12 / 13) it is also possible to add a ["middleware"](https://nextjs.org/docs/advanced-features/middleware), and serve the sitemap from there. – kca Feb 22 '23 at 18:26