XML sitemap for Next Js


Posted 3 months ago by Ryan Dhungel

Category: Next JS

Viewed 923 times

Estimated read time: 1 minute

Course of the day!

REACT - Up and Running with React ES6 and Open Source API

REACT - Up and Running with React ES6 and Open Source API

Generate XML sitemap for your next js app using online tool and serve as static file. This is the easiest way of getting the sitemap for your next js app. So what exactly you need to do?

  • Go to xml-sitemaps.com and enter your site's url
  • Download the ZIP file and copy the sitemap.xml
  • Copy the sitemap.xml into static/sitemap folder like so:
  • /static/sitemap/sitemap.xml

Write sitemap config options

In your server.js put the following code:

 

const sitemapOptions = {
    root: __dirname + '/static/sitemap/',
    headers: {
        'Content-Type': 'text/xml;charset=UTF-8'
    }
};

 

Then whenever your app gets a request to the url domain.com/sitemap.xml serve that sitemap.xml file that you generated online.

// serve sitemap
    server.get('/sitemap.xml', (req, res) => res.status(200).sendFile('sitemap.xml', sitemapOptions));

// the the rest of your code
    server.get('*', (req, res) => {
        return handle(req, res);
    });

 

Now you can visit domain.com/sitemap.xml and see your sitemap. You can submit this url to google as your sitemap.