Dynamic SEO Files
Generating XML sitemaps programmatically.
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
Compiled sitemap.xml
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
sitemap.tsautomatically generates asitemap.xmlroute.robots.tsautomatically generates arobots.txtroute.- 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.