代码之家  ›  专栏  ›  技术社区  ›  Lorenzo

NextJS-按需重新验证不适用于ISR

  •  0
  • Lorenzo  · 技术社区  · 2 年前

    我正在NextJS中使用他们的Pages路由器构建一个多租户应用程序。使用中间件函数,我们重写页面,使其在URL中显示帐户名或子域,如username.company.com或mysubdomain.company..com。这一切都很好。

    显示用户生成内容的页面结构如下:

    - Pages  
    ---- _sites  
    -------- [site]
    ------------ index.tsx
    ------------ [slug].tsx 
    

    [slug.tsx]和index.tsx页面使用 getStaticPaths getStaticProps 为了在构建时在服务器上呈现所有内容,它们不会自动重新验证,因为我只希望它们在用户更新内容时清除缓存。

    因此,我遵循文档通过API重新验证路径( https://nextjs.org/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation )

    import type { NextApiRequest, NextApiResponse } from "next";
    
    export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse
    ) {
      // Check for secret to confirm this is a valid request
      if (req.body.secret !== process.env.REVALIDATE_TOKEN) {
        return res.status(401).json({ message: "Invalid token" });
      }
    
      try {
        // this should be the actual path not a rewritten path
        // e.g. for "/blog/[slug]" this should be "/blog/post-1"
        await res.revalidate(req.body.url);
        return res.json({ revalidated: true });
      } catch (err) {
        return res.status(500).send("Error revalidating");
      }
    }
    

    这是我使用的代码,我知道你需要在这里提供确切的路径,比如 /_网站/公司/全栈开发人员/

    文档中关于此函数的信息不多,我尝试了在本地和服务器上使用不同的路径类型调用它,但它一直不刷新缓存,因此在我再次构建之前,它总是返回相同的过时内容。

    该项目托管在Vercel上,但使用NextJS v13.4.13时,本地和服务器上的手动重新验证似乎都无法正常工作

    ======== 编辑:

    显然,当使用NextJS中间件函数时,您需要在您希望更改明显的主机名上调用API函数。

    通过获得解决方案 https://github.com/vercel/next.js/discussions/35968

    0 回复  |  直到 2 年前