0
0
NextJSframework~30 mins

Sitemap.xml generation in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Sitemap.xml generation
📖 Scenario: You are building a website using Next.js. To help search engines find your pages, you want to create a sitemap.xml file that lists all your website URLs.
🎯 Goal: Create a simple sitemap.xml generator in Next.js that outputs a list of URLs in XML format.
📋 What You'll Learn
Create a list of page URLs as strings
Add a base URL configuration variable
Generate XML sitemap content using the URLs and base URL
Export a Next.js API route that returns the sitemap XML with correct headers
💡 Why This Matters
🌍 Real World
Sitemaps help search engines like Google find and index your website pages faster and better.
💼 Career
Generating sitemaps is a common task for web developers to improve SEO and site visibility.
Progress0 / 4 steps
1
Create the list of page URLs
Create a constant array called pages with these exact strings: "/", "/about", "/contact", "/blog".
NextJS
Need a hint?

Use const pages = ["/", "/about", "/contact", "/blog"] to create the list.

2
Add the base URL configuration
Add a constant string called BASE_URL and set it to "https://example.com".
NextJS
Need a hint?

Use const BASE_URL = "https://example.com" to set the base URL.

3
Generate the sitemap XML content
Create a function called generateSitemap that returns a string. Use pages.map to create XML <url> entries with full URLs by combining BASE_URL and each page. Wrap all entries inside <urlset> tags with the xmlns attribute set to "http://www.sitemaps.org/schemas/sitemap/0.9".
NextJS
Need a hint?

Use template strings and pages.map to build the XML entries, then wrap them in <urlset> tags.

4
Export the Next.js API route for sitemap.xml
Export a default async function called handler that takes req and res. Set the response header Content-Type to application/xml. Use res.send to send the string returned by generateSitemap().
NextJS
Need a hint?

Use res.setHeader to set the content type and res.send to send the XML string.