import { NextResponse } from 'next/server'; export async function GET() { const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n <url>\n <loc>https://example.com/</loc>\n <changefreq>daily</changefreq>\n </url>\n</urlset>`; return new NextResponse(sitemap, { headers: { 'Content-Type': 'application/xml' } }); }
The code returns a NextResponse with the sitemap XML string and sets the Content-Type header to application/xml. This means the browser or crawler receives a proper XML sitemap.
Option B is wrong because the response is not JSON. Option B is wrong because the Content-Type is correctly set to application/xml, not text/plain. Option B is wrong because NextResponse is valid in Next.js server components for custom responses.
Option A correctly uses the standard Response constructor with the XML string and sets the Content-Type header to application/xml.
Option A returns a string without headers, so the content type defaults to text/html, which is incorrect for sitemap.xml.
Option A calls Response as a function without new, causing a runtime error.
Option A uses NextResponse without importing it, and NextResponse is not always necessary; also, it lacks headers.
Next.js app router does not support dots in route file names except for the extension. Naming a file sitemap.xml.js creates an invalid route, causing 404.
Option C is wrong because GET is a named export, which is correct. Option C is wrong because Response is a global in Next.js runtime, no import needed. Option C is wrong because the XML string is valid.
import { NextResponse } from 'next/server'; const pages = ['/', '/about', '/contact']; export async function GET() { const urls = pages.map(page => ` <url><loc>https://example.com${page}</loc></url>`).join('\n'); const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>`; return new NextResponse(sitemap, { headers: { 'Content-Type': 'application/xml' } }); }
The code maps each page path to a <url> XML element with the full URL, joins them with newlines, and wraps them in <urlset> tags with XML declaration. The response is served with application/xml content type.
Option D is wrong because the response is XML, not JSON. Option D is wrong because pages array is not empty. Option D is wrong because pages is a synchronous array, no await needed.
Using a server component with NextResponse lets you generate sitemap.xml dynamically on the server with proper XML content and headers. This ensures search engines get fresh, accurate sitemaps improving SEO.
Option A is wrong because indefinite caching is not automatic and can cause stale data. Option A is wrong because sitemap.xml should not be client-rendered; it must be server-generated. Option A is wrong because minification is not automatic.