XML sitemap for Next Js


Posted 4 years ago by Ryan Dhungel

Category: Next JS Node

Viewed 12338 times

Estimated read time: 3 minutes

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.

 

Here is the complete steps and code to implement XML Sitemap in next js

Create server.js in the root of your project with the following code

const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const cors = require('cors');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();


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

app.prepare().then(() => {
    const server = express();
    server.use(bodyParser.json());

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

    server.get('*', (req, res) => {
        return handle(req, res);
    });

    server.listen(3000, err => {
        if (err) throw err;
        console.log('> Read on http://localhost:3000');
    });
});

 

Update your package.json file with the code below.

In production first run npm run build then run pm2 start npm -- start. In local development run npm run dev

  "scripts": {
    "dev": "NODE_ENV=development node server.js",
    "build": "next build",
    "start": "NODE_ENV=production node server.js",
  },

 

Conclusion

Sitemap is not the most important thing for SEO. But if your domain is new its better to have sitemap and submit to google and also submit URL's individually until you find yourself in google search results. Afterwards you can just foucs on creating great content and not worry so much about sitemap. You can let google handle the rest of the work.

Thanks for reading.