Bird
Raised Fist0
NextJSframework~10 mins

Sitemap.xml generation in NextJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Sitemap.xml generation
Start Request for sitemap.xml
↓
Next.js API Route or Server Component
↓
Fetch or Define URLs to include
↓
Generate XML string with URLs
↓
Set Response Headers (Content-Type: application/xml)
↓
Send XML Response
↓
Browser or Crawler receives sitemap.xml
The flow starts with a request for sitemap.xml, Next.js code generates XML with URLs, sets headers, and sends it back.
Execution Sample
NextJS
export async function GET() {
  const urls = ['/', '/about', '/contact'];
  const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n${urls.map(url => `<url><loc>https://example.com${url}</loc></url>`).join('')}\n</urlset>`;
  return new Response(xml, { headers: { 'Content-Type': 'application/xml' } });
}
This Next.js server function generates a sitemap.xml with three URLs and returns it with the correct XML content type.
Execution Table
StepActionData/VariableResult
1Function GET calledNo inputStart sitemap generation
2Define URLs arrayurls = ['/', '/about', '/contact']URLs ready for XML
3Map URLs to XML <url> tagsurls.map(...) <url><loc>https://example.com/</loc></url> etc.
4Create full XML stringxml = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">...</urlset>'Complete sitemap XML
5Return Response with XML and headerResponse(xml, headers)Sends sitemap.xml with content-type application/xml
6Browser or crawler receives responseResponse with XMLSitemap.xml loaded successfully
7EndNo further actionProcess complete
💡 All URLs processed and XML response sent, sitemap.xml generation complete
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
urlsundefined['/', '/about', '/contact']SameSameSame
xmlundefinedundefinedPartial XML string from mapFull XML string with header and urlsetFull XML string ready to send
Key Moments - 3 Insights
Why do we set the Content-Type header to 'application/xml'?
Because the browser or crawler needs to know the response is XML, not HTML or JSON. See execution_table step 5 where the header is set.
What happens if we forget to include all URLs in the XML string?
The sitemap will be incomplete and crawlers might miss pages. Step 3 and 4 show how URLs are mapped and included in the XML string.
Why do we use a server function (GET) instead of a client component?
Because sitemap.xml must be served as a static or server-generated file, not rendered on the client. Step 1 shows the server function handling the request.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'urls' after Step 2?
A['/', '/about', '/contact']
Bundefined
CComplete XML string
DResponse object
💡 Hint
Check variable_tracker row for 'urls' after Step 2
At which step is the Content-Type header set to 'application/xml'?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
See execution_table step 5 description about headers
If we add a new URL '/blog' to the urls array, what changes in the execution_table?
ANo change, sitemap.xml stays the same
BStep 2 urls array includes '/blog', Step 3 maps it to XML
CStep 5 header changes to 'text/html'
DStep 4 XML string is removed
💡 Hint
Adding URLs affects steps 2 and 3 where URLs are defined and mapped
Concept Snapshot
Sitemap.xml generation in Next.js:
- Use a server function (GET) to handle sitemap.xml requests
- Define URLs array to include in sitemap
- Map URLs to XML <url> tags inside <urlset>
- Return XML string with header 'Content-Type: application/xml'
- This serves sitemap.xml dynamically for crawlers
Full Transcript
This visual execution trace shows how to generate sitemap.xml in Next.js. When a request comes for sitemap.xml, the server function GET runs. It defines an array of URLs to include. Then it maps each URL to an XML <url> tag and wraps all in a <urlset> tag with XML header. The function returns this XML string as a Response with the content-type set to application/xml. The browser or crawler receives this XML sitemap. Variables like 'urls' and 'xml' change step by step as the code runs. Key moments include why the content-type header is needed and why this runs on the server. The quizzes test understanding of variable values and steps where headers are set or URLs added.

Practice

(1/5)
1. What is the main purpose of generating a sitemap.xml in a Next.js application?
easy
A. To help search engines find and index your pages faster
B. To improve the visual design of your website
C. To add client-side routing capabilities
D. To store user session data securely

Solution

  1. Step 1: Understand sitemap.xml role

    A sitemap.xml file lists URLs of your website to guide search engines.
  2. Step 2: Connect sitemap.xml to Next.js usage

    In Next.js, sitemap.xml helps search engines find pages faster by providing URL info.
  3. Final Answer:

    To help search engines find and index your pages faster -> Option A
  4. Quick Check:

    Sitemap.xml purpose = Help search engines [OK]
Hint: Remember sitemap.xml is for search engines, not UI [OK]
Common Mistakes:
  • Confusing sitemap.xml with styling or UI files
  • Thinking sitemap.xml stores user data
  • Assuming sitemap.xml adds client-side routing
2. Which of the following is the correct way to set the response header for a sitemap.xml in a Next.js API route?
easy
A. res.setHeader('Content-Type', 'text/html')
B. res.setHeader('Content-Type', 'text/plain')
C. res.setHeader('Content-Type', 'application/json')
D. res.setHeader('Content-Type', 'application/xml')

Solution

  1. Step 1: Identify correct content type for sitemap.xml

    Sitemap.xml is an XML file, so the content type must be 'application/xml'.
  2. Step 2: Match header setting in Next.js API route

    Use res.setHeader('Content-Type', 'application/xml') to set correct header.
  3. Final Answer:

    res.setHeader('Content-Type', 'application/xml') -> Option D
  4. Quick Check:

    Content-Type for sitemap.xml = application/xml [OK]
Hint: Always use 'application/xml' for sitemap responses [OK]
Common Mistakes:
  • Using 'text/html' instead of 'application/xml'
  • Setting content type to 'application/json'
  • Forgetting to set content type header
3. Given this Next.js API route code snippet for sitemap.xml generation, what will be the output content type header?
export async function GET(req, res) {
  res.setHeader('Content-Type', 'application/xml');
  return new Response(`<urlset></urlset>`);
}
medium
A. 'application/json'
B. 'text/html'
C. No content type header set
D. 'application/xml'

Solution

  1. Step 1: Understand Next.js 13+ GET handler response

    In Next.js 13+, the GET function returns a Response object; setting headers on 'res' does not affect it.
  2. Step 2: Check if content type header is set on Response

    The Response constructor here lacks headers, so no content type header is sent.
  3. Final Answer:

    No content type header set -> Option C
  4. Quick Check:

    Setting header on 'res' ignored, Response lacks headers [OK]
Hint: Set headers inside Response, not on 'res' in Next.js GET [OK]
Common Mistakes:
  • Assuming res.setHeader affects Response output
  • Not adding headers inside Response constructor
  • Confusing old API routes with new app router
4. Identify the bug in this Next.js sitemap.xml route code and how to fix it:
export async function GET() {
  const sitemap = `<urlset><url><loc>/home</loc></url></urlset>`;
  return new Response(sitemap);
}
medium
A. Missing 'Content-Type' header; add it in Response headers
B. Incorrect XML tags; use <html> instead of <urlset>
C. Function must be named 'getSitemap' instead of 'GET'
D. Response must return JSON, not XML string

Solution

  1. Step 1: Check response headers for sitemap.xml

    The code returns XML string but does not set 'Content-Type' header to 'application/xml'.
  2. Step 2: Fix by adding headers in Response constructor

    Add { headers: { 'Content-Type': 'application/xml' } } to Response to fix the bug.
  3. Final Answer:

    Missing 'Content-Type' header; add it in Response headers -> Option A
  4. Quick Check:

    Set 'Content-Type' header for XML response [OK]
Hint: Always add 'Content-Type' header when returning XML [OK]
Common Mistakes:
  • Forgetting to set content type header
  • Using wrong XML tags for sitemap
  • Misnaming the GET function
5. You want to generate a dynamic sitemap.xml in Next.js that includes URLs from a database. Which approach correctly combines fetching data and returning a valid sitemap response?
hard
A. Fetch URLs, return JSON array directly without headers
B. Fetch URLs, build XML string, then return new Response with XML and 'application/xml' header
C. Fetch URLs, set res.setHeader('Content-Type', 'application/json'), return JSON string
D. Fetch URLs, build XML string, return plain string without Response object

Solution

  1. Step 1: Fetch URLs from database asynchronously

    Use async function to get URLs from database or API.
  2. Step 2: Build XML string with URLs and return Response with correct header

    Create XML sitemap string, then return new Response(xmlString, { headers: { 'Content-Type': 'application/xml' } }).
  3. Final Answer:

    Fetch URLs, build XML string, then return new Response with XML and 'application/xml' header -> Option B
  4. Quick Check:

    Dynamic sitemap = fetch + XML + Response with header [OK]
Hint: Build XML string and return Response with XML header [OK]
Common Mistakes:
  • Returning JSON instead of XML for sitemap
  • Not setting content type header
  • Returning plain string without Response object
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard