Sitemaps & Robots.txt

Create a Sitemap

Let's create our sitemap. To create it, we are going to use a Next.js API route. So, create a file called pages/api/sitemap.js and add the following content:

import { getPostList } from '../../lib/data'

const hostname = ""

function getSitemapEntry({pathname, priority = 0.5}) {
    return `

export default async function sitemap(req, res) {
    const posts = await getPostList()
    const entries = => getSitemapEntry({
        pathname: `/post/${post.slug}`
        pathname: '/',
        priority: 1

    const sitemap = `
        <?xml version="1.0" encoding="UTF-8"?>
        <urlset xmlns="">

    res.writeHead(200, {
        'Content-Type': 'application/xml'
    return res.end(sitemap);

Here's what's happening:

  • First we get the post list
  • Then we create partial strings of sitemap URL entries for these posts
  • After that, we add the home page with a priority of 1
  • Then we create the final XML file and send it
šŸ‘‹ Replace const hostname = "" with your real website address. It'll be great if you can use an environment variable.

Now, visit http://localhost:3009/api/sitemap to view the sitemap.

Q: This sitemap has an issue, what's that?

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: