Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Last active February 16, 2023 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewIngram/2518476b05c61201434e912f9dbb7ad4 to your computer and use it in GitHub Desktop.
Save AndrewIngram/2518476b05c61201434e912f9dbb7ad4 to your computer and use it in GitHub Desktop.
Next.js Sitemap route handler
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