Challenges

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 = "https://yourapp.com"

function getSitemapEntry({pathname, priority = 0.5}) {
    return `
        <url>
            <loc>${hostname}${pathname}</loc>
        </url>
    `
}

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

    const sitemap = `
        <?xml version="1.0" encoding="UTF-8"?>
        <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
            ${entries.join('\n')}
        </urlset>      
    `.trim()

    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 = "https://yourapp.com" 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?
authenticating...

šŸ™ We need your help

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