On Demand Revalidation with NextJS 13 / App Directory?

1.6k views Asked by At

I am trying to get on-demand revalidation working with next13 / the app directory. I know how to use the app-directory to recreate what previously required getServerSideProps or getStaticProps.

But there is one page on our site, that requires a rebuild (of that page) whenever a trigger / webhook is fired. I know I can do a

export const revalidate = XXXX;
```

...but it's not the same, I don't need to rebuild the site every `X` seconds.

Any ideas?
2

There are 2 answers

2
Ahsan Khan On

We need revalidation when we are working with nextjs static build, generated with the help of getStaticProps and getStaticPaths. All of our pages will be build as html files. We can also make our application as an hybrid model some pages will be statically generated and some are server side rendered.

For revalidation firstly you need to create a revalidation api in /pages/api directory.

exec("npm run build", (error, stdout, stderr) => {
if (error) {
  console.error(`Error during build: ${error.message}`);
  return res.status(500).json({
    message: "Failed to trigger revalidation",
    data: error.message,
    code: 422,
  });
}
return res
  .status(200)
  .json({ message: "Published Successfully", code: 200 });

With the the help of child process you can trigger a build that will re generate all pages with new data which is being fatched at build time.

Now to trigger a revalidation call this api, you can also add secret token to validate weather request is valid or not.

0
ILDAR Nasyrov On

You can use revalidateTag or revalidatePath, for example

export default async function Page() {
  const user = await fetch("/user", {next: { tag: "user" }} )
  return <div>i am {user.name} my page beautifull</div>
}

and revalidate cache for prev page by tag in some form

export default async function FormPage() {
  const addUser = async() => {
    "use server";
    await fetch("/user/update", {data: {name: "other"}});
    revalidateTag("user") //whatever path you are calling it from
  };

  return(
    <>
      <form action={ addUser }>
        <input
          ...
        />
      </form>

      <div>{ ...up to date user data }</div>
    </>
  );
}

correct me if I'm wrong