Skip to content

Instantly share code, notes, and snippets.

@danielkhoo
Created December 10, 2023 08:00
Show Gist options
  • Save danielkhoo/9608f6906a912ae99cbf2a78168ff7e3 to your computer and use it in GitHub Desktop.
Save danielkhoo/9608f6906a912ae99cbf2a78168ff7e3 to your computer and use it in GitHub Desktop.
NextJS Sitemap Handler
export default function handler(req, res) {
// getPosts is a fn that returns all the posts, you should already have this for a markdown/mdx site
const posts = getPosts();
res.statusCode = 200
res.setHeader('Content-Type', 'text/xml')
// Instructing the Vercel edge to cache the file
res.setHeader('Cache-control', 'stale-while-revalidate, s-maxage=3600')
// generate sitemap here
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${posts.map(({ slug, data }) => `
<url>
<loc>${`https://yoursitename.com/${slug}`}</loc>
<lastmod>${new Date(data.date).toISOString()}</lastmod>
</url>` ).join('')}
</urlset>`
res.end(xml)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment