How to Create a Custom Sitemap.ts in Next.js (App Router) for Better SEO

One of the most overlooked but powerful SEO tools is your sitemap. A sitemap.xml helps Google and other search engines discover and crawl your pages more efficiently — improving visibility, crawlability, and indexing speed.
In this guide, I’ll walk you through how to create a custom sitemap.ts in Next.js 13+ (App Router) — with support for both static and dynamic pages (like blog articles).
Why You Need a Sitemap
A sitemap.xml tells search engines:
What pages your site contains
When each page was last updated
Which pages are most important
Combined with a robots.txt, it's an SEO essential.
🛠️ Step 1: Create the sitemap.ts File
In your Next.js App Router project, create a file:
app/sitemap.ts or src/app/sitemap.ts
Then, paste the following code:
import { MetadataRoute } from 'next';
// You can replace this with a fetch call to your CMS or database
const getDynamicRoutes = async (): Promise<string[]> => {
const res = await fetch('https://your-api.com/api/blogs');
const data = await res.json();
return data?.data?.map((item: any) => `/blog/${item.attributes.slug}`) || [];
};
export async function GET(): Promise<MetadataRoute.Sitemap> {
const baseUrl = 'https://www.yourdomian.com';
const staticRoutes = [
'/',
'/about',
'/contact',
'/blog',
'/services',
];
const dynamicRoutes = await getDynamicRoutes();
const allRoutes = [...staticRoutes, ...dynamicRoutes];
return allRoutes.map((route) => ({
url: `${baseUrl}${route}`,
lastModified: new Date().toISOString(),
}));
}
Step 2: Dynamic Blog Slugs (Optional)
If you're using a CMS like Strapi, your getDynamicRoutes() function will look like this:
const getDynamicRoutes = async (): Promise<string[]> => {
const res = await fetch('https://your-strapi-api.com/api/blogs?pagination[limit]=100');
const json = await res.json();
return json.data.map((item: any) => `/blog/${item.attributes.slug}`);
};
Step 3: Test the Sitemap
https://yourdomain.com/sitemap.xml
You should see valid XML output like:
<url>
<loc>https://yourdomain.com/blog/nextjs-seo-guide</loc>
<lastmod>2025-06-01T08:00:00Z</lastmod>
</url>
Step 4 : Submit to Google Search Console
Go to Google Search Console
Click your property (domain)
Open “Sitemaps”
Submit:
https://yourdomain.com/sitemap.xml