Skip to content

Instantly share code, notes, and snippets.

@MaikelVeen
Last active February 28, 2021 11:18
Show Gist options
  • Save MaikelVeen/bcc9794dd3991c41097be41be99bfe50 to your computer and use it in GitHub Desktop.
Save MaikelVeen/bcc9794dd3991c41097be41be99bfe50 to your computer and use it in GitHub Desktop.
Sitemap generation GetServerSideProps
import { GetServerSideProps } from 'next';
import fs from 'fs';
import path from 'path';
export default function Sitemap() {}
type Url = {
host: string;
route: string;
date?: Date;
};
const excludedRoutes: Array<string> = ['/sitemap', '/404'];
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
const basePath: string = process.cwd();
const routes_manifest: object = ReadManifestFile(basePath);
const host: string = "https://example.com"
let routes: Array<Url> = GetPathsFromManifest(routes_manifest, host);
const pagesPath = path.join(basePath + '/.next/server/pages/');
routes = routes.concat(GetPathsFromBuildFolder(pagesPath, [], host, pagesPath));
routes = routes.filter((el) => !excludedRoutes.includes(el.route));
const sitemap: string = GetSitemapXml(routes);
res.setHeader('Content-Type', 'text/xml');
res.write(sitemap);
res.end();
return { props: {} };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment