Skip to content

Instantly share code, notes, and snippets.

@mjurincic
Forked from henninghall/sitemap.xml.tsx
Created March 18, 2020 11:48
Show Gist options
  • Save mjurincic/93ffb9c514d799cb9c58d297220cda5a to your computer and use it in GitHub Desktop.
Save mjurincic/93ffb9c514d799cb9c58d297220cda5a to your computer and use it in GitHub Desktop.
sitemap.xml in next.js which is easy to extend with dynamic routes
// place in pages/sitemap.xml.tsx
const fs = require('fs')
import { endpoint } from '../config'
const Sitemap = () => null
Sitemap.getInitialProps = async ({ res }) => {
if (!res) return {}
const folder = 'pages'
res.setHeader('content-type', 'application/xml')
let content = fs
.readdirSync(folder)
.map(f => (f === '_app.tsx' ? '' : f))
.filter(f => !f.startsWith(`_`))
.filter(f => !f.startsWith(`[`))
.filter(f => f !== `sitemap.xml.tsx`)
.map(f => ({
filename: f,
updatedAt: fs
.statSync(`${folder}/${f}`)
.mtime.toISOString()
.substr(0, 10)
}))
.map(f => ({ ...f, filename: f.filename.replace('.tsx', '') }))
.map(f => ({ ...f, filename: `${endpoint}/${f.filename}` }))
.map(f => `<url><loc>${f.filename}</loc><lastmod>${f.updatedAt}</lastmod></url>`)
.join()
res.end(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${content}</urlset>`)
return {}
}
export default Sitemap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment