Technical SEO 8 min read 1496 words

Next.js Sitemap: How to Generate and Submit It

Build and validate a dynamic or static Next.js sitemap using app/sitemap.ts so search engines discover new content and priority URLs immediately.

Growth Lab Editorial

Growth Lab Editorial

Head of Digital PR & Outreach

Published: 2026-11-11
Dynamic Next.js sitemap XML generation in App Router

A sitemap serves as a structured roadmap for search engines. It lists your website's essential URLs, informs web crawlers when pages were last modified, and highlights canonical content. In modern web frameworks like Next.js, building a reliable sitemap is critical for fast indexation, especially when handling dynamic routes, content updates, and client-side rendering.

Creating a Next.js sitemap used to require external npm packages, custom build scripts, or manual XML generation. With modern versions of the framework, managing your sitemap has become simpler and natively integrated. Whether you run a portfolio, an enterprise SaaS application, or an e-commerce platform, setting up automated XML files ensures search engines discover your newest URLs without manual intervention.

Why XML Sitemaps Matter for Next.js Applications

Search engine bots discover web pages by following hyperlinks. However, dynamic routing, single-page application hydration, and deeply nested structures can make comprehensive discovery challenging. A well-formatted XML sitemap provides a direct index of canonical URLs, helping search bots allocate crawl budgets efficiently.

Beyond basic URL listing, sitemaps communicate important metadata:

  • Last modification date (lastModified): Signals whether content has changed since the bot's prior visit.


  • Change frequency (changeFrequency): Advises how often a page typically updates, such as daily, weekly, or monthly.

  • Priority (priority): Suggests relative importance across your domain on a scale of 0.0 to 1.0.


While Google treats priority and change frequency primarily as directional hints, the lastModified timestamp plays a key role in efficient recrawling.

Static vs. Dynamic Sitemaps in Next.js

Before generating your file, determine whether your web application requires a static or dynamic setup.

┌────────────────────────────────────────────────────────┐
│                   Next.js Application                  │
└──────────────────────────────────┬─────────────────────┘
                                   │
         ┌─────────────────────────┴─────────────────────────┐
         ▼                                                   ▼
┌─────────────────────────────────┐         ┌─────────────────────────────────┐
│         Static Sitemap          │         │         Dynamic Sitemap         │
│  • Handful of fixed pages       │         │  • Database-driven routes       │
│  • sitemap.xml in /app or       │         │  • Dynamic API / CMS fetches    │
│    sitemap.ts with hardcoded    │         │  • Auto-updates on new content  │
│    URL arrays                   │         │  • Built via sitemap.ts / .js   │
└─────────────────────────────────┘         └─────────────────────────────────┘

A static sitemap works well for marketing websites with a fixed number of pages that change infrequently, such as an About page, Contact form, and Terms of Service.

A dynamic sitemap is necessary for blogs, online stores, programmatic landing pages, and news sites where new content generates new URLs. Next.js can query your database or headless CMS at build time or request time to populate these links automatically.

Generating a Sitemap with the Next.js App Router

The Next.js App Router introduced native file-based metadata conventions. You no longer need third-party tools to output standard XML. By placing a specialized file named sitemap.ts (or sitemap.js) directly in the root of your app/ directory, Next.js automatically outputs a standards-compliant /sitemap.xml route.

1. Basic Static Implementation

For a website with static pages, export a default function returning an array of URL objects:

TypeScript

// app/sitemap.ts
import { MetadataRoute } from 'next';

export default function sitemap(): MetadataRoute.Sitemap {
  const baseUrl = 'https://example.com';

  return [
    {
      url: `${baseUrl}`,
     Last edited: new Date(), 
      changeFrequency: 'weekly',
      priority: 1.0,
    },
    {
      url: `${baseUrl}/about`,
     Last edited: new Date(), 
      changeFrequency: 'monthly',
      priority: 0.8,
    },
    {
      url: `${baseUrl}/contact`,
      Last edited: new Date(), 
      changeFrequency: 'yearly',
      priority: 0.5,
    },
  ];
}

When built, this code automatically serves a valid XML document at /sitemap.xml.

2. Dynamic Implementation Using External Data

When your application handles hundreds or thousands of blog posts or product listings, fetch the dynamic slugs inside the sitemap function:

TypeScript

// app/sitemap.ts
import { MetadataRoute } from 'next';

interface Post {

  slug: string;
  updatedAt: string;
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const baseUrl = 'https://example.com';

  // Fetch slugs from your database, CMS, or API
  const response = await fetch('https://api.example.com/posts');
  const posts: Post[] = await response.json();

  const postEntries: MetadataRoute.Sitemap = posts.map((post) => ({
    url: `${baseUrl}/blog/${post.slug}`,
   Last edited: new Date(), (post.updatedAt),
    changeFrequency: 'weekly',
    priority: 0.7,
  }));

  const staticEntries: MetadataRoute.Sitemap = [
    {
      url: baseUrl,
     Last edited: new Date(), 
      changeFrequency: 'daily',
      priority: 1.0,
    },
  ];

  return [...staticEntries, ...postEntries];
}

This approach regenerates URL records whenever pages are revalidated or rebuilt, keeping your search index synchronized with your content repository.

Handling Large Websites: Generating a Sitemap Index

Search engines enforce strict limits on XML sitemaps: a single sitemap file cannot exceed 50,000 URLs or 50 MB uncompressed. If your web project exceeds these parameters, you must split your entries across multiple files and reference them within a parent sitemap index.

In Next.js, use the generateSitemaps function to distribute entries across indexed files:

TypeScript

// app/sitemap.ts
import { MetadataRoute } from 'next';

export async function generateSitemaps() {
  // Return an array of IDs representing individual sitemap files
  return [{ id: 0 }, { id: 1 }, { id: 2 }];
}

export default async function sitemap({
  id,

}: {

  id: number;

}): Promise<MetadataRoute.Sitemap> {

  const baseUrl = 'https://example.com';
  const start = id * 25000;
  const end = start + 25000;

  const products = await fetchProducts(start, end);

  return products.map((product) => ({
    url: `${baseUrl}/products/${product.id}`,
    lastModified: product.updatedAt,
  }));
}

Next.js automatically coordinates the files into an index route, generating /sitemap.xml as a parent file pointing to /sitemap/0.xml, /sitemap/1.xml, and beyond.

Step-by-Step Guide to Submitting Your Sitemap

Creating your sitemap is only half the task. You must also declare its location so search engine bots can discover and process it.

Search Engine / Channel

Primary Submission Method

Verification Required?

Robots.txt

Direct reference at domain root

No

Google Search Console

Sitemaps dashboard under Indexing

Yes (DNS/HTML tag)

Bing Webmaster Tools

Sitemaps tool or GSC synchronization

Yes

Step 1: Reference the Sitemap in robots.txt

Before submitting to search consoles, declare the sitemap in your robots.txt file. Next.js supports this natively through an app/robots.ts file:

TypeScript

// app/robots.ts
import { MetadataRoute } from 'next';

export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: '*',
      allow: '/',
      disallow: ['/admin/', '/private/'],
    },
    sitemap: 'https://example.com/sitemap.xml',
  };
}

This ensures any compliant web scraper visiting your domain finds your sitemap location immediately.

Step 2: Submit to Google Search Console

  1. Navigate to Google Search Console.


  1. Select your verified domain property.


  1. From the left sidebar, click Indexing > Sitemaps.


  1. In the Add a new sitemap input field, enter sitemap.xml (or your subpath URL).


  1. Click Submit.


Search Console will update the status to Success once the endpoint is fetched and processed. If errors appear, check for syntax issues, redirect loops, or blocked URLs.

Step 3: Submit to Bing Webmaster Tools

  1. Sign in to Bing Webmaster Tools.


  1. Select your property (or import it directly from Google Search Console).


  1. Click Sitemaps in the navigation menu.


  1. Click Submit sitemap, enter the full destination URL (e.g., [https://example.com/sitemap.xml](https://example.com/sitemap.xml)), and submit.


Best Practices and Common Mistakes to Avoid

A poorly configured sitemap can waste crawl budgets and cause indexation conflicts. Keep these guidelines in mind during setup:

  • Include only canonical URLs: Never place redirects (301 or 302), broken endpoints (404), or pages tagged with Noindex inside your sitemap. Only list 200 HTTP status pages.


  • Match your protocol and domain: Always use absolute URLs matching your production domain, including the correct protocol (https://) and preferred subdomains (www or non-www).


  • Update lastModified responsibly: Avoid updating the lastModified timestamp arbitrarily on every build. Only reflect genuine content edits so crawlers can prioritize pages that actually changed.


  • Review edge caching and revalidation: If using dynamic data generation with static export or incremental static regeneration (ISR), confirm your caching headers allow search crawlers to receive fresh sitemap output.


Frequently Asked Questions

Where should the sitemap file be placed in the Next.js App Router?

In the App Router, place sitemap.ts or sitemap.js directly inside the root app/ directory (for example, app/sitemap.ts). Next.js will automatically build and route the output to /sitemap.xml.

Can I generate multiple sitemaps for localized multi-language sites?

Yes. You can return localized URLs using the generateSitemaps function or by formatting alternate language references within the sitemap items. Next.js supports adding alternate language objects to individual entries to inform crawlers of alternate language variants.

How do I verify my sitemap is working locally before deploying?

Run npm run build followed by npm run start in your local development environment. Navigate to http://localhost:3000/sitemap.xml in your browser to inspect the generated XML structure and verify all attributes before pushing your changes to production.


Scaling a Next.js Sitemap Across Large Content Libraries

Whether managing 50 service URLs or 50,000 programmatic pages via generateSitemaps, keeping your next.js sitemap free of redirects and drafts preserves full Search Console trust.

Key Implementation Takeaways for Next.Js Sitemap

When teams audit their next.js sitemap execution regularly, crawl efficiency and commercial keyword stability improve together. Consistent documentation and measurable next.js sitemap workflows ensure every major release strengthens organic search visibility. At Growth Lab, our engineering playbooks treat next.js sitemap as a core architectural discipline rather than an afterthought. Monitoring real Search Console telemetry alongside disciplined next.js sitemap standards prevents silent indexation drops after deployments. Organizations investing early in structured next.js sitemap practices outperform slower competitors in both click-through rate and domain authority. Pairing clean technical foundations with proven next.js sitemap monitoring gives marketing and engineering teams compounding search equity.

Topic Tags:#SEO#Guest Posting#indexing#core web vitals#Technical seo
Growth Lab Editorial
WRITTEN BY

Growth Lab Editorial

Senior practitioner at Growth Lab specializing in high-authority digital PR, technical SEO engineering, and algorithmic organic visibility benchmarks.

EXPAND YOUR DIGITAL AUTHORITY

Ready to Secure High-DR Placements for Your Brand?

Access Growth Lab's verified publisher network and execute data-backed SEO campaigns that move the needle.