Next.js sitemap.xml returns 404 on Vercel production with dynamic data

Hey! The issue is that your sitemap.ts is trying to fetch dynamic data at build time, which might be failing on Vercel. Here’s how to fix it:

Option 1: Force Dynamic Rendering
Add this to the top of your sitemap.ts file to make it render at request time:

export const dynamic = 'force-dynamic'

Option 2: Add Error Handling
Wrap your data fetching in try/catch to prevent build failures:

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const domain = process.env.NEXT_PUBLIC_SITE_URL;
  
  try {
    const audioList = await getBayaanSlug();
    const audioSitemap = audioList?.items?.map((audio: any) => ({
      url: `${domain}/audio/${audio?.slug}`,
      lastModified: audio?.sys?.publishedAt,
      changeFrequency: 'yearly' as const,
      priority: 0.8,
    })) || [];
    
    return [
      {
        url: domain || '',
        lastModified: new Date(),
        changeFrequency: 'monthly',
        priority: 1,
      },
      ...audioSitemap,
    ];
  } catch (error) {
    console.error('Failed to fetch audio data for sitemap:', error);
    // Return at least the homepage
    return [{
      url: domain || '',
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 1,
    }];
  }
}

Also check that your getBayaanSlug() function works correctly in production - it might need environment variables or API endpoints that aren’t available during build time.