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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay