Next.js Course
Next.js
/
Intermediate

Sitemaps

Definition

An XML file (`sitemap.xml`) that acts as a roadmap of your website for search engines, listing all public URLs so Google doesn't have to guess where your pages are.

Explain Like I'm New

If your site has 5,000 blog posts, Google's bot might miss some if it just clicks around randomly. A sitemap is a list you hand directly to Google saying: 'Here are the exact 5,000 URLs I want you to rank in search results.'

Real World Example

Creating a dynamic `sitemap.ts` file in Next.js that queries your database, gets all 5,000 blog post slugs, and automatically generates the XML file for Google.

Common Use Cases

  • •Technical SEO
  • •Large e-commerce catalogs
  • •Content-heavy blogs

Interactive Example

// app/sitemap.ts
import { MetadataRoute } from 'next';
import db from '@/lib/db';

// Google will visit /sitemap.xml and Next.js will execute this function!
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  // 1. Fetch dynamic URLs from database
  const posts = await db.post.findMany();
  
  const postUrls = posts.map((post) => ({
    url: `https://mywebsite.com/blog/${post.slug}`,
    lastModified: post.updatedAt,
    changeFrequency: 'weekly',
    priority: 0.8,
  }));

  // 2. Combine with static URLs
  return [
    {
      url: 'https://mywebsite.com',
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 1,
    },
    ...postUrls,
  ];
}

Interview Questions

basic

  • If you just have a 3-page portfolio site, do you strictly need a complex dynamic sitemap?

intermediate

  • How does Next.js automatically generate a sitemap using code?

Flash Cards

Question

Strictly need it?

Click to reveal answer
Answer

No. Google's crawlers are incredibly smart and will easily find 3 pages just by following the links in your Navbar. Sitemaps are critical for massive, dynamic sites with thousands of URLs.

Question

How to generate?

Click to reveal answer
Answer

By creating a special `sitemap.ts` file at the root of the `app` directory that exports a default async function returning an array of URL objects.