Next.js

Sitemap in Next.js

A sitemap file in Next.js helps search engine crawlers index your site more efficiently. It follows the Sitemaps XML format and can be created statically or generated dynamically using code.

Creating a Sitemap

You can create a sitemap in Next.js using two methods:

  1. Using a static XML file
  2. Generating the sitemap using code (.js or .ts)

Both methods require placing the file in the root of the app directory.

Static Sitemap File

For smaller applications, you can create a sitemap.xml file in the root of your app directory:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://acme.com</loc>
    <lastmod>2023-04-06T15:02:24.021Z</lastmod>
    <changefreq>yearly</changefreq>
    <priority>1</priority>
  </url>
  <url>
    <loc>https://acme.com/about</loc>
    <lastmod>2023-04-06T15:02:24.021Z</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>
  <url>
    <loc>https://acme.com/blog</loc>
    <lastmod>2023-04-06T15:02:24.021Z</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
</urlset>

Generate a Sitemap Using Code

You can use the sitemap.(js|ts) file convention to programmatically generate a sitemap:

// app/sitemap.ts
import type { MetadataRoute } from 'next'

export default function sitemap(): MetadataRoute.Sitemap {
  return [
    {
      url: 'https://acme.com',
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 1,
    },
    {
      url: 'https://acme.com/about',
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.8,
    },
    {
      url: 'https://acme.com/blog',
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.5,
    },
  ]
}

Good to know: sitemap.js is a special Route Handler that is cached by default unless it uses dynamic functions or dynamic config options.

Advanced Sitemap Features

Image Sitemaps

You can include image information in your sitemap:

export default function sitemap(): MetadataRoute.Sitemap {
  return [
    {
      url: 'https://example.com',
      lastModified: '2021-01-01',
      changeFrequency: 'weekly',
      priority: 0.5,
      images: ['https://example.com/image.jpg'],
    },
  ]
}

Localized Sitemaps

For multilingual sites, you can specify alternate language versions:

export default function sitemap(): MetadataRoute.Sitemap {
  return [
    {
      url: 'https://acme.com',
      lastModified: new Date(),
      alternates: {
        languages: {
          es: 'https://acme.com/es',
          de: 'https://acme.com/de',
        },
      },
    },
    // ... more URLs
  ]
}

Generating Multiple Sitemaps

For large websites, you might need to split your sitemap into multiple files:

// app/product/sitemap.ts
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,
  }))
}

Sitemap Object Structure

The sitemap function should return an array of objects with the following structure:

type Sitemap = Array<{
  url: string
  lastModified?: string | Date
  changeFrequency?:
    | 'always'
    | 'hourly'
    | 'daily'
    | 'weekly'
    | 'monthly'
    | 'yearly'
    | 'never'
  priority?: number
  alternates?: {
    languages?: Languages<string>
  }
}>

Best Practices

  1. Keep it up-to-date: Regularly update your sitemap to reflect changes in your site structure.

  2. Include all important pages: Make sure all significant pages of your site are included in the sitemap.

  3. Use appropriate change frequencies: Set realistic change frequencies for different types of content.

  4. Set priorities correctly: Use the priority attribute to indicate the relative importance of pages within your site.

  5. Don't exceed size limits: If your sitemap exceeds 50,000 URLs or 50MB, split it into multiple sitemaps.

  6. Submit your sitemap: After creating your sitemap, submit it to search engines through their webmaster tools.

By properly configuring your sitemap, you can help search engines better understand and index your Next.js application, potentially improving your site's visibility in search results.

Previous
Open Graph