Next.js article thumbnail image.

A sitemap.xml file lists a website's important pages to ensure Google, Bing, and other search engines can locate, understand, and crawl them.

In other words, it serves as a roadmap that tells search engines what content is available on your website and how to treat it.

To add a sitemap.xml file to your Next.js website, all you need to do is add the file to your /public directory.

When you place a file inside the /public directory, it will be served at the root URL of your website. Therefore, this file will be accessible at www.example.com/sitemap.xml in the browser.

Let's go over each step to get the sitemap.xml file added to your Next.js website.

On your development machine, navigate to your Next.js project directory.

Advertisement
Find Remote JavaScript Coding Jobs
RemotelyWeCode.com curates the best remote software development jobs from startups and companies around the world.
Find Jobs

If you haven't already created a /public folder, create one in the root of your project's directory with this command:

mkdir public

Then, create a new file in the /public directory named sitemap.xml:

cd public && touch sitemap.xml

Then, you can add your sitemap's content to the /public/sitemap.xml file.

For example, here's a sitemap file that contains a single link:

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.example.com/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
</urlset>

Save the changes you made to the sitemap.xml file and open your browser window to http://localhost:3000/sitemap.xml.

You should see the contents of your sitemap.xml file displayed on the page.

Next.js Sitemap.xml File Contents Shown In The Browser

Then, you need to deploy this change to production to make your sitemap.xml file accessible to the world.

When you've finished your deployment process, visit your website in a browser and verify that the sitemap.xml file is served at this URL: https://example.com/sitemap.xml.

Your sitemap.xml file is now created and configured in your Next.js website.

For a guide on getting your Next.js website indexed on search engines like Google, Bing, DuckDuckGo, and Yahoo, we wrote an article on that here.

About the author

Hey, I'm Nick, a software developer from Wisconsin, USA.

My latest course Build A Hacker News Clone walks you through how to build a clone of Hacker News using React.js, Node.js, MongoDB, & friends.

I also built and run RemotelyWeCode.com, a job board for remote coders.

Picture of Nick Major.