3

I'm trying to use NextJS to generate the sitemap of my website. But it does have a lot of links. I would like to avoid processing all the links every sitemap.xml is accessed.

I have something like this:

import { GetServerSideProps } from "next";
import React from "react";

const Sitemap = () => {
  return null;
};

export const getServerSideProps: GetServerSideProps = async ({ res }) => {
  const BASE_URL = "http://localhost:3000";

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{generateSitemap()}
</sitemapindex>`;

  res.setHeader("Content-Type", "text/xml");
  res.write(sitemap);
  res.end();

  return {
    props: {},
  };
};

export default Sitemap;

I would like to have something like this:

export const getStaticProps: GetStaticProps<PageProps> = async () => {
  try {
    const sitemap = await generateSiteMap();

    return {
      props: {
        sitemap,
        revalidate: 3600, // caches the current sitemap and builds a new version every 1h
      },
    };
  } catch (error) {
    console.log(error);
  }
};

Is this possible? Does anyone know other ways to achieve a similar result? A cached sitemap.xml that is rebuilt every hour.

One possible way is to make everything at build time with nezt-sitemap and deploy a new version every hour. But I was wondering if there are better solutions.

Felipe César
  • 1,234
  • 2
  • 16
  • 34
  • 1
    I ran into a similar issue - I wanted to use ISR since the site maps change fairly frequently but not frequently enough to recalculate on every request. In reading the `getStaticProps` documentation it appears that it forces generation of an HTML/JSON combination which precludes an XML page from functioning, though. I've ended up resorting to just using `getServerSideProps` and eating the performance hit unfortunately, but I'll keep watching this question in case some wizard comes along. – bsplosion May 25 '23 at 18:51

0 Answers0