如何使用 NextJs getStaticProps 创建站点地图

Fel*_*sar 5 javascript sitemap next.js vercel getstaticprops

我正在尝试使用 NextJS 生成我网站的站点地图。但它确实有很多链接。我想避免处理每个访问 sitemap.xml 的所有链接。

我有这样的事情:

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;

Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

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);
  }
};

Run Code Online (Sandbox Code Playgroud)

这可能吗?有谁知道其他方法可以达到类似的结果?每小时重建一次的缓存 sitemap.xml。

一种可能的方法是在构建时制作所有内容并nezt-sitemap每小时部署一个新版本。但我想知道是否有更好的解决方案。