Skip to content

Instantly share code, notes, and snippets.

@henninghall
Created October 13, 2019 15:38
Show Gist options
  • Save henninghall/cc284e96ed555f2f09c14422860113a8 to your computer and use it in GitHub Desktop.
Save henninghall/cc284e96ed555f2f09c14422860113a8 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
@Adam-Asatryan
Copy link

Module not found: Can't resolve 'fs' in '/Users/dav/Desktop/dvld-nextjs/pages/sitemap'

@gauravkrp
Copy link

Module not found: Can't resolve 'fs' in '/Users/dav/Desktop/dvld-nextjs/pages/sitemap'

'fs' module can only be used on server side.

@dailytravel
Copy link

how to generate sitemap from JSON data (data from database) like
image

Here: https://leerob.io/blog/nextjs-sitemap-robots

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment