How to add a sitemap.xml in Nextjs

Viewed 1023

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

1 Answers

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.

Related