How to Generate an XML Sitemap in Astro

How to Generate an XML Sitemap in Astro

Master enterprise XML sitemaps in Astro: dynamic chunking, SSR endpoints, i18n hreflang automation, and edge-cached delivery at scale.

In high-concurrency enterprise web architectures, Search Engine Optimization (SEO) is not merely a marketing concern—it is a distributed systems and data engineering challenge. When managing content ecosystems spanning tens or hundreds of thousands of dynamic URLs across multiple locales, search engine crawlers face distinct constraints: finite crawl budgets, connection timeouts, and index fragmentation.

The XML Sitemap Protocol serves as the contract between your application infrastructure and search indexing engines (Googlebot, Bingbot, etc.). A naive sitemap strategy can lead to stale indexation, severe crawl budget exhaustion, or server degradation during high-frequency spider sweeps.

While Astro delivers industry-leading frontend performance out of the box through its Island Architecture and static generation engine, configuring production-grade XML sitemaps for complex, multi-tenant, or hybrid (SSG + SSR) applications requires deliberate architectural design.

This guide explores the patterns, performance trade-offs, and implementation strategies required to engineer enterprise-grade sitemaps in Astro.


The Enterprise Sitemap Architecture

At scale, a monolithic sitemap.xml file is an anti-pattern. The official Sitemaps XML protocol enforces two non-negotiable boundaries:

  1. A single sitemap file must not exceed 50,000 URLs.
  2. A single uncompressed sitemap file must not exceed 50 megabytes.

In an enterprise environment with high-velocity product launches, localization, and CMS updates, reaching these ceilings happens quickly. Furthermore, serving dynamic SSR content necessitates fresh, decoupled sitemap indexes rather than monolithic static rebuilds.

                              [ Search Engine Crawler ]
                                         │
                                         ▼
                             [ CDN / Edge Cache Layer ]
                        (stale-while-revalidate / TTL: 1h)
                                         │
                                         ▼
                         ┌──────────────────────────────┐
                         │   GET /sitemap-index.xml     │
                         └──────────────┬───────────────┘
                                        │
           ┌────────────────────────────┼────────────────────────────┐
           ▼                            ▼                            ▼
┌───────────────────────┐   ┌───────────────────────┐   ┌───────────────────────┐
│ sitemap-core.xml (SSG)│   │sitemap-p1.xml (Hybrid)│   │sitemap-p2.xml (Hybrid)│
│ Core static pages     │   │ Dynamic product batch │   │ Dynamic product batch │
│ Generated at build    │   │ Paginated SSR / Edge  │   │ Paginated SSR / Edge  │
└───────────────────────┘   └───────────────────────┘   └───────────────────────┘

To support this model, your Astro application must decouple static pages from dynamic, high-churn content and leverage Sitemap Index Files along with structured sub-sitemaps.


Strategy 1: The Official Integration (@astrojs/sitemap)

For standard content-driven setups using Static Site Generation (SSG), Astro provides an official integration: @astrojs/sitemap. It hooks directly into the build pipeline, traversing Astro’s resolved route graph to compile the XML tree.

1. Installation and Configuration

Install the package alongside your Astro dependencies:

npm install @astrojs/sitemap

Configure your astro.config.mjs. Notice that the site property is strictly required; without an absolute canonical origin, relative URLs cannot be resolved to the fully qualified domain names (FQDNs) mandated by the XML schema.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';

export default defineConfig({
  site: 'https://platform.enterprise.com',
  integrations: [
    sitemap({
      filter: (page) => {
        // Exclude internal API routes, staging pages, and private tenant paths
        const excludedPaths = [
          '/api/',
          '/admin/',
          '/preview/',
          '/drafts/',
          '/cdn-cgi/'
        ];
        return !excludedPaths.some((excluded) => page.includes(excluded));
      },
      changefreq: 'daily',
      priority: 0.7,
      lastmod: new Date(),
      // Advanced configuration hooks
      serialize(item) {
        // Apply differential indexing policies based on URI patterns
        if (item.url === 'https://platform.enterprise.com/') {
          item.priority = 1.0;
          item.changefreq = 'hourly';
        } else if (item.url.includes('/blog/')) {
          item.priority = 0.8;
          item.changefreq = 'weekly';
        }
        return item;
      },
    }),
  ],
});

2. Limitations in Enterprise Environments

While elegant, @astrojs/sitemap has critical architectural constraints:

  • Build-Time Evaluation Only: It relies on the Astro route manifest computed during astro build. If your application operates in SSR mode (output: 'server'), dynamic routes reliant on runtime query parameters or backend APIs cannot be inferred at compile time.
  • Memory Pressure on Massive Route Trees: On monorepos or platforms with 200,000+ statically mapped content files, processing the entire route array in-memory during build time can exhaust Node.js heap allocations unless fine-tuned via max-old-space-size.
  • Coupled Deployments: A content update in your headless CMS requires a complete Astro rebuild just to refresh the static sitemap.xml.

Strategy 2: Dynamic Endpoint Generation (Hybrid & SSR)

To overcome the build-time limitations of the static plugin, you can implement Astro API Endpoints (.ts files inside src/pages). This allows you to stream or render XML sitemaps dynamically at runtime, sourcing directly from your database, cache, or Headless CMS, while fully controlling HTTP response headers.

Here is an enterprise-grade dynamic sitemap endpoint capable of handling dynamic routes in Hybrid or Server mode.

// src/pages/sitemap-dynamic.xml.ts
import type { APIRoute } from 'astro';

interface RouteMetadata {
  loc: string;
  lastmod: string;
  changefreq: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
  priority: number;
}

// Enterprise content service simulation
async function fetchPublishedEntitySlugs(): Promise<RouteMetadata[]> {
  const backendApiUrl = import.meta.env.ENTERPRISE_CMS_API;
  const token = import.meta.env.CMS_AUTH_TOKEN;

  try {
    const response = await fetch(`${backendApiUrl}/v1/catalog/urls`, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch entities: ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Critical: Failed to generate dynamic sitemap routes', error);
    // Return empty array to fail gracefully rather than blowing up the worker
    return [];
  }
}

function buildXmlPayload(routes: RouteMetadata[]): string {
  const urlNodes = routes
    .map(
      (route) => `
    <url>
      <loc>${route.loc}</loc>
      <lastmod>${route.lastmod}</lastmod>
      <changefreq>${route.changefreq}</changefreq>
      <priority>${route.priority.toFixed(1)}</priority>
    </url>`
    )
    .join('');

  return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  ${urlNodes}
</urlset>`.trim();
}

export const GET: APIRoute = async ({ site }) => {
  if (!site) {
    return new Response('Astro config is missing the mandatory "site" option.', { 
      status: 500 
    });
  }

  const dynamicRoutes = await fetchPublishedEntitySlugs();
  const xmlContent = buildXmlPayload(dynamicRoutes);

  return new Response(xmlContent, {
    status: 200,
    headers: {
      'Content-Type': 'application/xml; charset=utf-8',
      // Edge Caching Strategy: Serve stale while fetching update asynchronously
      'Cache-Control': 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=43200',
      'X-Content-Type-Options': 'nosniff',
    },
  });
};

When deploying internationalized enterprise applications, generating independent URL nodes without linking relationships causes indexing problems: search engines cannot determine geographic or linguistic equivalence, leading to internal cannibalization.

The official standard mandates using the xhtml:link attribute inside each <url> node, creating a bidirectional link between every alternate localized version of a page, as well as an x-default fallback.

                  ┌──────────────────────────────────────────────┐
                  │                 Canonical:                   │
                  │   https://enterprise.com/en/products/sku-99  │
                  └──────────────┬───────────────────────────────┘
                                 │
           ┌─────────────────────┴─────────────────────┐
           ▼                                           ▼
┌─────────────────────────┐                 ┌─────────────────────────┐
│ hreflang="es"           │                 │ hreflang="de"           │
│ .../es/productos/sku-99 │                 │ .../de/produkte/sku-99  │
└─────────────────────────┘                 └─────────────────────────┘

Implementing Localized Multi-Tenant Sitemaps

Below is an Astro API endpoint that generates dynamic sitemap nodes adhering to the W3C/Google hreflang XML specification:

// src/pages/sitemap-i18n.xml.ts
import type { APIRoute } from 'astro';

interface LocalizedSlugMap {
  [locale: string]: string;
}

interface LocalizedEntity {
  id: string;
  lastmod: string;
  locales: LocalizedSlugMap;
}

const SUPPORTED_LOCALES = ['en', 'es', 'de', 'fr', 'ja'];
const DEFAULT_LOCALE = 'en';

export const GET: APIRoute = async ({ site }) => {
  const origin = site?.toString().replace(/\/$/, '') || 'https://platform.enterprise.com';
  
  // Example dataset representing database or CMS pull
  const contentItems: LocalizedEntity[] = [
    {
      id: 'platform-governance',
      lastmod: new Date().toISOString(),
      locales: {
        en: '/en/solutions/platform-governance',
        es: '/es/soluciones/gobernanza-de-plataforma',
        de: '/de/loesungen/plattform-governance',
        fr: '/fr/solutions/gouvernance-de-plateforme',
      },
    },
  ];

  let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`;
  xml += `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" `;
  xml += `xmlns:xhtml="http://www.w3.org/1999/xhtml">\n`;

  for (const item of contentItems) {
    for (const [locale, path] of Object.entries(item.locales)) {
      xml += `  <url>\n`;
      xml += `    <loc>${origin}${path}</loc>\n`;
      xml += `    <lastmod>${item.lastmod}</lastmod>\n`;

      // Generate the bidirectional alternates (including self-reference)
      for (const [altLocale, altPath] of Object.entries(item.locales)) {
        xml += `    <xhtml:link rel="alternate" hreflang="${altLocale}" href="${origin}${altPath}" />\n`;
      }

      // Append x-default mapping to designate default regional experience
      const defaultPath = item.locales[DEFAULT_LOCALE] || path;
      xml += `    <xhtml:link rel="alternate" hreflang="x-default" href="${origin}${defaultPath}" />\n`;
      xml += `  </url>\n`;
    }
  }

  xml += `</urlset>`;

  return new Response(xml, {
    status: 200,
    headers: {
      'Content-Type': 'application/xml; charset=utf-8',
      'Cache-Control': 'public, max-age=7200, s-maxage=86400',
    },
  });
};

Strategy 4: Sitemap Chunking and Index Aggregation (>50k Records)

When catalog sizes exceed single-sitemap parameters, your architecture must implement Sitemap Chunking.

The approach relies on a master Sitemap Index File pointing to chunked subsets (sitemap-products-1.xml, sitemap-products-2.xml, etc.).

1. The Sitemap Index Generator

// src/pages/sitemap-index.xml.ts
import type { APIRoute } from 'astro';

export const GET: APIRoute = async ({ site }) => {
  const origin = site?.toString().replace(/\/$/, '') || 'https://platform.enterprise.com';
  
  // Query our database abstraction to compute pagination bounds
  const totalItems = 125000;
  const CHUNK_SIZE = 40000; // Well safely within the 50,000 threshold
  const totalChunks = Math.ceil(totalItems / CHUNK_SIZE);
  
  const staticSubmaps = [
    `${origin}/sitemap-core.xml`,
    `${origin}/sitemap-i18n.xml`,
  ];

  let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`;
  xml += `<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n`;

  // Register static assets and pages
  for (const sitemapUrl of staticSubmaps) {
    xml += `  <sitemap>\n`;
    xml += `    <loc>${sitemapUrl}</loc>\n`;
    xml += `    <lastmod>${new Date().toISOString()}</lastmod>\n`;
    xml += `  </sitemap>\n`;
  }

  // Register dynamic chunks
  for (let page = 1; page <= totalChunks; page++) {
    xml += `  <sitemap>\n`;
    xml += `    <loc>${origin}/sitemaps/products-${page}.xml</loc>\n`;
    xml += `    <lastmod>${new Date().toISOString()}</lastmod>\n`;
    xml += `  </sitemap>\n`;
  }

  xml += `</sitemapindex>`;

  return new Response(xml, {
    status: 200,
    headers: {
      'Content-Type': 'application/xml; charset=utf-8',
      'Cache-Control': 'public, max-age=86400',
    },
  });
};

2. The Chunk Processing Route

Using dynamic routing via src/pages/sitemaps/[chunk].xml.ts, you extract the query segment, apply SQL LIMIT and OFFSET clauses, and construct the paginated document:

// src/pages/sitemaps/[chunk].xml.ts
import type { APIRoute, GetStaticPaths } from 'astro';

const PAGE_SIZE = 40000;

export const GET: APIRoute = async ({ params, site }) => {
  const { chunk } = params;
  const origin = site?.toString().replace(/\/$/, '') || 'https://platform.enterprise.com';
  
  // Extract index from format: "products-1"
  const match = chunk?.match(/^products-(\d+)$/);
  if (!match) {
    return new Response('Not Found', { status: 404 });
  }

  const pageNumber = parseInt(match[1], 10);
  const offset = (pageNumber - 1) * PAGE_SIZE;

  // Execute database query with bounded pagination
  // const records = await db.query('SELECT slug, updated_at FROM products LIMIT ? OFFSET ?', [PAGE_SIZE, offset]);
  
  // Mock representative record
  const mockRecord = {
    slug: `product-sku-${offset + 1}`,
    updated_at: new Date().toISOString(),
  };

  let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`;
  xml += `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n`;
  
  xml += `  <url>\n`;
  xml += `    <loc>${origin}/products/${mockRecord.slug}</loc>\n`;
  xml += `    <lastmod>${mockRecord.updated_at}</lastmod>\n`;
  xml += `    <changefreq>weekly</changefreq>\n`;
  xml += `  </url>\n`;

  xml += `</urlset>`;

  return new Response(xml, {
    status: 200,
    headers: {
      'Content-Type': 'application/xml; charset=utf-8',
      'Cache-Control': 'public, max-age=604800, stale-while-revalidate=86400',
    },
  });
};

Edge Delivery and Cache Invalidation Mechanics

Generating XML sitemaps containing 50,000 nodes requires significant CPU cycles to serialize strings and compute XML schemas. Executing this on every crawler hit will exhaust compute units and trigger database connection thrashing.

1. HTTP Cache-Control and Edge Strategies

To guarantee millisecond TTFB (Time to First Byte) for crawlers while preserving fresh data, configure an edge-native caching policy:

Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=43200
  • max-age=3600: Standard browser/client instances hold the content for 1 hour.
  • s-maxage=86400: Shared Edge Caches (Cloudflare, AWS CloudFront, Fastly) persist the compiled sitemap for 24 hours.
  • stale-while-revalidate=43200: If a crawler accesses the resource within a 12-hour window following s-maxage expiration, the edge immediately returns stale XML while asynchronously executing a sub-request to your Astro endpoint to hydrate the edge cache.

2. Informing Search Engines via robots.txt

The entry point of crawler ingestion must point directly to your primary index. Create a static public/robots.txt or an Astro dynamic endpoint src/pages/robots.txt.ts:

# public/robots.txt
User-agent: *
Allow: /

# Sitemap Index Declaration
Sitemap: https://platform.enterprise.com/sitemap-index.xml

CI/CD Verification: Automated XML Schema Validation

Enterprise software requires automated assertions. Deploying a syntactically invalid sitemap can break discovery across your entire domain. Integrating XML schema validation into your CI pipeline catches regressions before code hits production.

Below is an automated validation script using libxmljs2 or fast-xml-parser run during the post-build pipeline.

1. The Validation Script

// scripts/validate-sitemap.ts
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { XMLParser, XMLValidator } from 'fast-xml-parser';

function validateSitemapFile(filePath: string): void {
  console.log(`[Validation] Inspecting: ${filePath}`);
  const absolutePath = resolve(process.cwd(), filePath);
  const rawXml = readFileSync(absolutePath, 'utf-8');

  // Step 1: Syntactic Well-Formedness
  const validationResult = XMLValidator.validate(rawXml, {
    allowBooleanAttributes: false,
  });

  if (validationResult !== true) {
    throw new Error(`XML Malformed Error in ${filePath}: ${validationResult.err.msg}`);
  }

  // Step 2: Semantic and Spec Boundary Verification
  const parser = new XMLParser({ ignoreAttributes: false });
  const parsedData = parser.parse(rawXml);

  if (parsedData.urlset) {
    const urls = Array.isArray(parsedData.urlset.url) 
      ? parsedData.urlset.url 
      : [parsedData.urlset.url];
      
    if (urls.length > 50000) {
      throw new Error(`Scale Ceiling Breached! Found ${urls.length} items (Limit: 50,000) in ${filePath}`);
    }

    // Assert absolute URLs
    for (const entry of urls) {
      if (!entry.loc || !entry.loc.startsWith('https://')) {
        throw new Error(`Insecure or relative URL encountered: ${entry.loc}`);
      }
    }

    console.log(`[Validation PASS] ${urls.length} URLs compliant.`);
  } else if (parsedData.sitemapindex) {
    console.log(`[Validation PASS] Sitemap Index verified.`);
  } else {
    throw new Error(`Invalid root element: File contains neither <urlset> nor <sitemapindex>`);
  }
}

// Execute checks against build output
try {
  validateSitemapFile('./dist/sitemap-index.xml');
  validateSitemapFile('./dist/sitemap-0.xml');
} catch (error) {
  console.error('[CI Failure] Sitemap Validation Engine Encountered Errors:', error);
  process.exit(1);
}

2. GitHub Actions Pipeline Integration

Wire the verification step into your pipeline to block faulty pull requests:

# .github/workflows/deploy.yml
name: Build and Verify Deployment

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build-and-validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install Dependencies
        run: npm ci

      - name: Compile Application (Astro Build)
        run: npm run build
        env:
          ENTERPRISE_CMS_API: ${{ secrets.ENTERPRISE_CMS_API }}
          CMS_AUTH_TOKEN: ${{ secrets.CMS_AUTH_TOKEN }}

      - name: Run Sitemap Spec Verification Engine
        run: npx tsx scripts/validate-sitemap.ts

Architectural Comparison Matrix

Choose the pattern that matches your data requirements:

Operational Dimension @astrojs/sitemap Integration Astro API Endpoints (.ts) Hybrid Multi-Chunk Index
Execution Phase Build-time (SSG) Request-time / Edge Cache Build or Request / Edge Cache
Max Scale Potential ~50,000 routes Unbounded (via paginated endpoints) Arbitrary enterprise scale (Millions of URLs)
Data Freshness Low (Bound to application rebuilds) Real-time (Bound to edge TTL) Real-time / Tiered (Per chunk invalidation)
Memory Overhead Moderate to High (Build pipeline) Zero application build load Distributed across dynamic workers
Complexity to Maintain Minimal (Standard configuration) Moderate (Requires custom code) Advanced (Requires infrastructure management)
Internationalization Basic / Intermediate Complete control via raw XML Complete control via raw XML

Conclusion

At enterprise scale, an XML sitemap is a core component of your distribution architecture. Relying entirely on out-of-the-box build-time generation creates operational bottlenecks as your content footprint expands.

By architecting a layered solution—using Astro’s build integrations for static corporate landing pages, dynamic API endpoints for real-time localized entities, and index chunking across edge-cached infrastructure—you establish a reliable, high-performance SEO pipeline. This protects crawl budgets, accelerates indexation of critical content, and safeguards against performance degradation as your content catalog grows.