Next.js - generateSiteMap() Function



The generateSiteMap() Function

The Next.js generateSiteMap() is a utility function that help you to automate generation of sitemap file for your website. This is useful for SEO purposes as it helps search engines to crawl and index your website more effectively.

Syntax

Following is the syntax of generateSiteMap function:

export async function generateSitemaps() {
  // Fetch the total number of products
  return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}

Parameters

The generateSiteMap function does not take any parameters.

Return Value

The generateSiteMap function returns an array of objects, each containing the id of the product. This array can be used to generate the sitemap file for your website.

Key Points

  • The generateSiteMap function is an async function that can be used to automate the generation of sitemap files for your website.
  • The function can be used to fetch the total number of products or pages on your website and return an array of objects, each containing the id of the product or page.
  • The array returned by the function can be used to generate the sitemap file for your website.
  • The generated sitemaps will be available at /.../sitemap/[id].xml. For example, /product/sitemap/1.xml.

Example 1

In this example, we use the generateSiteMap function to fetch the total number of products and return an array of objects, each containing the id of the product. We then use this array to generate the sitemap file for our website.

import { BASE_URL } from '@/app/lib/constants'
 
export async function generateSitemaps() {
  // Fetch the total number of products and calculate the number of sitemaps needed
  return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}
 
export default async function sitemap({
  id,
}: {
  id: number
}): Promise<MetadataRoute.Sitemap> {
  // Google's limit is 50,000 URLs per sitemap
  const start = id * 50000
  const end = start + 50000
  const products = await getProducts(
    `SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}`
  )
  return products.map((product) => ({
    url: `${BASE_URL}/product/${product.id}`,
    lastModified: product.date,
  }))
}
Advertisements