-
-
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment