Generating Dynamic Sitemaps for Next.js 14 - App router
Tags: nextjs, sanity, sitemap, webdev
Published: 2024-01-27 05:49:25

In this post, we'll guide you on adding a dynamic XML sitemap to your Next.js website using the "app" directory in Next.js version 14. The goal is to create a sitemap that updates automatically as you add or remove pages, benefiting SEO for sites with regularly updated content like blogs or products. Let's get started!


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxbmfye8apnv36f3llaw.png)

Before we jump into the details, let's briefly explore the world of sitemaps — what they are, their purpose, and the key differences between static and dynamic versions. As we progress, our aim is to help you establish a fully functional dynamic sitemap for your Next.js 14 website.

By the end of this post, you'll have a clear understanding of sitemaps and the tools to enhance your site's navigation.

## What is a Sitemap?
Imagine a map of your website, leading search engines and visitors to every page. That's a sitemap! It's a file listing all your website's pages and their connections. It's handy for search engines to understand your site's structure.

## Why do you need it?

If your website is large or has a complex layout, having a sitemap is crucial. It makes it easier for search engines to find and index all your pages. Google recommends sitemaps, especially for new sites or those with limited links.

**SEO booster**: Helps search engines find and understand your site, potentially improving your search ranking.
**Navigation buddy**: Makes it easier for visitors to find what they're looking for on your website.

## Static vs Dynamic Sitemaps

There are two types: static and dynamic.

**Static Sitemaps**: Like a printed map - These are manually created and submitted to search engines. They list all pages.
**Dynamic Sitemaps**: Automatically generated and updated whenever you add or remove pages. Great for larger websites, such as blogs

## Why Dynamic Sitemaps Matter

For efficiency, we're focusing on dynamic sitemaps in this guide. They save you from manual updates and adapt automatically when you add new content, like publishing a blog post on your Next.js website. This boosts SEO and improves site navigation. Let's make your website smarter!

## Integrating a Sitemap in the App Directory

Next.js version 13.3  introduced developers with a file-based metadata API, streamlining page metadata management and simplifying both static and dynamic sitemap creation. This powerful feature eliminates the need for manual sitemap generation, saving time and effort.

To leverage this functionality, we'll create a dedicated sitemap.js file within the app directory. This file will serve as the command center, orchestrating the sitemap generation process and automating repetitive tasks.

```
blog/
  app/
    sitemap.js
```

In the sitemap.js file, our main task is to map the posts and static URLs to the properties of a `Sitemap` object, and then return this object.

```
import { sanityFetch } from "@/lib/sanity.client";
import { postsQuery } from "@/lib/sanity.query";

const URL = "https://blog.alsiam.com";

export default async function sitemap() {
    const blog = await sanityFetch({
        query: postsQuery,
        tags: ["post"],
    });

    const posts = blog.map(({ slug, _updatedAt }) => ({
        url: `${URL}/blog/${slug}`,
        lastModified: _updatedAt,
    }));

    const routes = ["", "/blog", "/about",].map((route) => ({
        url: `${URL}${route}`,
        lastModified: new Date().toISOString(),
    }));

    return [...routes, ...posts];
}

```

## Summary
In this article, we highlighted the significance of adding a sitemap for SEO, particularly beneficial for large websites. The focus was on integrating a dynamic sitemap into a Next.js 14 website, ensuring automatic updates when pages change.

The tutorial covered creating dynamic sitemaps using "app" directories. Dynamic sitemaps, especially for sizable websites, prove more efficient than static ones. By implementing these techniques, your website becomes easily discoverable by search engines, enhancing overall SEO performance.