Last active
February 16, 2023 22:45
-
-
Save AndrewIngram/2518476b05c61201434e912f9dbb7ad4 to your computer and use it in GitHub Desktop.
Next.js Sitemap route handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SitemapStream, EnumChangefreq, streamToPromise } from "sitemap"; | |
import { getAllPosts } from "~/data"; | |
import { Readable } from "stream"; | |
async function* getSitemapUrls(request: Request) { | |
const url = new URL(request.url); | |
const origin = `${url.protocol}//${url.host}`; | |
const buildUrl = (path: string) => `${origin}${path}`; | |
yield { | |
url: buildUrl("/"), | |
changefreq: EnumChangefreq.DAILY, | |
priority: 0.7, | |
}; | |
for (const post of await getAllPosts()) { | |
yield { | |
url: buildUrl(`/posts/${post.slug}`), | |
changefreq: EnumChangefreq.DAILY, | |
priority: 0.7, | |
}; | |
} | |
} | |
export async function GET(request: Request) { | |
try { | |
const smStream = new SitemapStream(); | |
Readable.from(getSitemapUrls(request)).pipe(smStream); | |
return new Response(await streamToPromise(smStream), { | |
headers: { | |
"Content-Type": "application/xml", | |
}, | |
status: 200, | |
}); | |
} catch (e) { | |
console.error(e); | |
return new Response("", { | |
status: 500, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment