DEV Community

Paulund
Paulund

Posted on • Originally published at paulund.co.uk

NextJS Add XML Sitemap

An XML sitemap is a file that lists all the URLs for your site, it helps search engines discover and index your content. In this post, we'll add an XML sitemap to our NextJS blog.

There are 2 ways you can add an XML sitemap to your blog, you can either add it manually to the public folder or you can generate it dynamically.

As we're working with a NextJS blog that is going to change content from markdown files we don't want to manually change the sitemap every time we add a new post. Instead, we'll generate the sitemap dynamically.

To do this create a sitemap.tsx file inside your app directory. First we need to import the Next MetadataRoute type. This will allow us to define the sitemap route.

Then we'll need to fetch all the posts for the blog and return the slugs for them.

import { MetadataRoute } from 'next'
import { getPosts } from "@/lib/blog/api";
import { SITE_URL } from "@/lib/constants";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = getPosts();

  const home = {
    url: SITE_URL,
    lastModified: new Date().toString(),
  };

  const postUrls = posts.map(({ slug, createdAt }) => ({
    url: `${SITE_URL}/${slug}`,
    lastModified: createdAt,
  }));

  return [home, ...postUrls]
}
Enter fullscreen mode Exit fullscreen mode

This will generate a sitemap with the home page and all the blog posts. To test this is working you can run the following command:

npx next start
Enter fullscreen mode Exit fullscreen mode

Then navigate to http://localhost:3000/sitemap.xml and you should see the sitemap.

Next we can make sure that search engines can find the sitemap by adding it to the robots.txt file. Create a robots.txt file in the public directory and add the following:

User-agent: *
Allow: /

Sitemap: http://localhost:3000/sitemap.xml
Enter fullscreen mode Exit fullscreen mode

Top comments (0)