Creating a Sitemap File for a Next.js Project
Tags: nextjs, webdev, javascript
Published: 2023-01-01 21:49:59

> original blog post: [Creating a Sitemap File for a Next.js Project](https://aykadev.vercel.app/post/creating-a-sitemap-file-for-a-next-js-project)


If you have a Next.js project and want to improve your website's SEO, one important step is to create a sitemap. A sitemap is an XML file that lists the URLs of the pages on your website, along with additional information such as the last time each page was updated and how frequently it changes. This information helps search engines like Google crawl and index your website more efficiently.

There are a couple of different ways to create a sitemap for a Next.js project. If your website is relatively small and static, you can create a manual sitemap by creating an `sitemap.xml` file in the public directory of your project and listing the URLs of the pages you want to include. However, if your website is dynamic and has many pages, it's often more practical to use the `getServerSideProps` function to generate a sitemap on demand.


To use `getServerSideProps` to create a dynamic sitemap, you'll need to create a new page in the pages directory of your Next.js project called `sitemap.xml.js`. This page will be responsible for generating the sitemap.
First, import any dependencies you'll need to fetch the data you need to build the sitemap. In this example, we'll use the `axios` library to make an HTTP request to a third-party API:

```javascript
import axios from 'axios';

const EXTERNAL_API_URL = 'https://example.com/api/blog-posts';
```

> make sure to define and export the page as a function (in nextjs each page is a function/component):

```javascript
[...]

function SiteMap() {
  // leave it empty! getServerSideProps will do the heavy lifting
}

// getServerSideProps
[....]

export default SiteMap;
```

Next, define the `getServerSideProps` function and use it to fetch the data you need to build the sitemap. In this example, we'll make an HTTP request to the `EXTERNAL_API_URL` to retrieve a list of blog posts:

```javascript
export async function getServerSideProps({ res }) {
  // Fetch the data from the API
  const response = await axios.get(EXTERNAL_API_URL);
  const posts = response.data;

  // Use the data to generate the sitemap XML
  const sitemapXML = generateSiteMap(posts);

  // Set the response headers and status code
  res.setHeader('Content-Type', 'text/xml');
  res.statusCode = 200;

  // Write the sitemap XML to the response
  res.write(sitemapXML);

  // End the response
  res.end();
}
```
The `getServerSideProps` function should return an object with a props property that contains the data you want to pass to the component. In this case, we're not passing any data to a component, so we can just return an empty object.

Finally, you'll need to define a function to generate the sitemap XML from the data you've fetched. In this example, we've defined a `generateSiteMap` function that takes the list of blog posts as an argument and returns a string of XML representing the sitemap.

```javascript
function generateSiteMap(posts) {
  return `<?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <!-- Add static URLs -->
     <url>
       <loc>https://example.com</loc>
     </url>
     <url>
       <loc>https://example.com/about</loc>
     </url>
     <!-- Add dynamic URLs -->
     ${posts
       .map(({ id }) => {
         return `
       <url>
           <loc>${`https://example.com/posts/${id}`}</loc>
       </url>
     `;
       })
       .join('')}
   </urlset>
 `;
}
```
This function generates an XML string that includes static URLs (such as the homepage and an "about" page) as well as dynamic URLs for each of the blog posts in the posts array.
To use this function, you'll need to import it at the top of the `sitemap.xml.js` file and then call it from the `getServerSideProps` function.


With these steps, you should now have a dynamic sitemap for your Next.js project that updates automatically as you add new content. This will help search engines like Google crawl and index your website more efficiently, improving your website's SEO.