Next.js Discord

Discord Forum

sitemap.ts file works in dev, but not in production

Unanswered
Champagne D’Argent posted this in #help-forum
Open in Discord
Champagne D’ArgentOP
I've generated the following sitemap.ts file, which I placed in the app directory, following the example (https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps).

import { MetadataRoute } from 'next'

async function renderPosts() {
    const articlesEndpoint = `/api/articles`;
    const strapiUrl = 'http://localhost:1337';

    let articles = []
    const response = await fetch(`${strapiUrl}${articlesEndpoint}`, {
        headers: {
          'Authorization': `Bearer ${process.env.STRAPI_API_KEY}`,
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0'
        },
        cache:'no-store'
    });
    if (response.ok) {
        let json = await response.json();
        if(json.data)
            articles = json.data
    }
    const postArray: any = []
    articles
    .map(({ id }: { id: number }) => {
        postArray.push({
            url: `https://site.com/articles/${id}`,
            lastModified: new Date()
        })
    })
    return postArray
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
    
    const posts = await renderPosts()
    const additionalPosts = [
        {
          url: 'https://site.com',
          lastModified: new Date(),
        },
        {
          url: 'https://site.com/blog',
          lastModified: new Date(),
        }
    ]
    return additionalPosts.concat(posts);
}


However, in production this file causes the following error:

Error occurred prerendering page "/sitemap.xml". Read more: https://nextjs.org/docs/messages/prerender-error

TypeError: fetch failed

1 Reply

Masai Lion
In prod ya still fetching from localhost 1337 ? Or is this down?