Created
October 13, 2019 15:38
-
-
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
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
// 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 |
Module not found: Can't resolve 'fs' in '/Users/dav/Desktop/dvld-nextjs/pages/sitemap'
'fs' module can only be used on server side.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Module not found: Can't resolve 'fs' in '/Users/dav/Desktop/dvld-nextjs/pages/sitemap'