#next-sitemap with new app based dir

1 messages · Page 1 of 1 (latest)

verbal mulch
#

how can i add all my dynamic pages to sitemap under /sitemaps/ path. there are more than million of data.

north domeBOT
#

Hi @verbal mulch. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To add all your dynamic pages to a sitemap under the /sitemaps/ path, you can use the new file-based Metadata API introduced in Next.js 13.3. This API allows you to generate files dynamically, which is useful when you have a large number of dynamic pages.

You can create a sitemap.js file that returns an array of your dynamic routes. Here's an example:

export default async function sitemap() {
 const res = await fetch('<https://.../posts'>);
 const allPosts = await res.json();
 
 const posts = allPosts.map((post) => ({
 url: `<https://acme.com/blog/${post.slug}`,>
 lastModified: post.publishedAt,
 }));
 
 const routes = ['', '/about', '/blog'].map((route) => ({
 url: `<https://acme.com${route}`,>
 lastModified: new Date().toISOString(),
 }));
 
 return [...routes, ...posts];
}

(Source: Next.js 13.3 Blog (https://nextjs.org/blog/next-13-3))

However, if you have more than a million data, you might want to consider generating your sitemap at runtime. This is especially useful if your SEO-critical pages are highly dynamic or if you need a sitemap that can change over time. Here's an example of how you can do this:

export default function handler(req, res) {
 res.statusCode = 200 
 res.setHeader('Content-Type', 'text/xml')  
 res.setHeader('Cache-control', 'stale-while-revalidate, s-maxage=3600')  
 const xml = `...generate sitemap here...`
 res.end(xml)
}

(Source: Vercel Guide (https://vercel.com/guides/how-do-i-generate-a-sitemap-for-my-nextjs-app-on-vercel))

Lastly, you can use a rewrite rule to map /sitemap.xml to /api/sitemap:

#
module.exports = { 
 async rewrites() { 
  return [ 
   { 
    source: '/sitemap.xml', 
    destination: '/api/sitemap', 
   }, 
  ] 
 },
}

(Source: Vercel Guide (https://vercel.com/guides/how-do-i-generate-a-sitemap-for-my-nextjs-app-on-vercel))

Please note that the Metadata API is not available in the pages directory and is only available for the App Router (app). You can learn more about file-based metadata and view the API reference here (https://nextjs.org/docs/app/api-reference/file-conventions/metadata#file-based-metadata).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: