Dynamic SEO Files

Generating XML sitemaps programmatically.

Next.js2 min readConcept 57 of 66

sitemap.ts & robots.ts

Instead of manually maintaining static .xml or .txt files in your public folder, Next.js allows you to create special .ts files directly in your app directory.

For example, placing a sitemap.ts file at the root of your app directory tells Next.js to execute that function, take the returned array, and output a valid sitemap.xml file for search engines.

Automating SEO

If you run a blog, you don't want to manually edit an XML file every time you publish a new article.

By using sitemap.ts, you can connect directly to your database, fetch all published articles, and map them into the required sitemap format. Next.js handles the XML generation.

Implementation

tsx

import { MetadataRoute } from 'next';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {

const posts = await fetchPosts();

const postUrls = posts.map((post) => ({

url: https://acme.com/blog/${post.slug},

lastModified: post.updatedAt,

}));

return [

{ url: 'https://acme.com', lastModified: new Date() },

...postUrls,

];

}

TypeScript to XML

Examine how a standard TypeScript array of objects is automatically transformed into a valid XML sitemap by the Next.js compiler.

The Absolute URL Trap

Unlike standard React components where you can use relative paths like /about, sitemaps are read by external crawlers. You must provide the full absolute URL including the protocol and domain.

sitemap.ts

import type { MetadataRoute } from 'next';
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: "https://acme.com",
lastModified: new Date('2024-01-01'),
},
{
url: "https://acme.com/blog",
lastModified: new Date('2024-02-15'),
}
];
}

Compiled sitemap.xml

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org...">
<url>
<loc>https://acme.com</loc>
<lastmod>2024-01-01T00:00:00.000Z</lastmod>
</url>
<url>
<loc>https://acme.com/blog</loc>
<lastmod>2024-02-15T00:00:00.000Z</lastmod>
</url>
</urlset>

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is a strict requirement for the URLs returned by `sitemap.ts`?

Remember this

  • sitemap.ts automatically generates a sitemap.xml route.
  • robots.ts automatically generates a robots.txt route.
  • You MUST use absolute URLs (https://...) in sitemaps.
  • You can dynamically fetch from your database inside these files.

Done with this concept?

Mark it complete to track your progress. No login needed.