Next.js on-demand revalidation is here! 🚀
Tags: nextjs, javascript, tutorial
Published: 2022-02-22 17:53:01

[Next.js](https://nextjs.org/) on-demand static regeneration is finally here! 😍

This is a super cool feature that makes possible to refresh statically generate pages.

Think about an heandless cms with a product catalog. With this option you can statically generate your catalog pages and “invalidate” the cache programmatically when the user edit the content.

In this article I’ll just try the new API (still in beta) with a little next app, nothing more of what you can find in the documentation so feel free to skip it and take a look directly at the [nextjs docs](https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#on-demand-revalidation-beta).

Keep reading if you want to have a minimal example. Here you can find a repo with the code.

## Setup

```jsx
npx create-next-app@latestnpx
```

Move to your app folder and run

```jsx
npm run dev
```

Visiting **[http://localhost:3000](http://localhost:3000)** you should see the following:

![Nextjs starter page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alcetc4wcu83uhfxbg9n.png)
 

Now you are ready to start.

We are going to build a very basic app that shows a timestamp, a button that triggers the revalidate api and a link that refresh the page.

Basically the following:

![Next.js on-demand revalidation demo pulbasso](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/br7ap2jf4on59v0zztjj.png)
 

For this quick example it’s fine to call the **revalidate** api from the client but in a real world application the logic should be triggered from a trusted backend since you should use a secret token to authorize the request.

The timestamp is generated at build time and if you keep refreshing the page you should see always the same value until you click the “Revalidate” button, then at the next refresh you should see a new value.

## Code it

We can replace the code in the **index.js** class adding the **getStaticProps** method in order to generate the timestamp. Here is the code:

```jsx
import {useState} from "react";

function Home({ timestamp }) {

  const [result, setResult] = useState("");

  const revalidate = async () => {
    await fetch("/api/revalidate?secret=supersecret");
    setResult("Done. Try to refresh the page");
  }

  return (
    <div className="root">
      <div className="timestamp">{timestamp}</div>
      <div>{result}</div>
      <div className="actions">
        <button onClick={() => { revalidate()}}>Revalidate</button>
        <a href="">Refresh</a>
      </div>
            
    </div>
  );
}

// This function gets called at build time
export async function getStaticProps() {
  return {
    props: {
      timestamp: new Date().toISOString()
    },
  }
}

export default Home
```

The revalidate logic is in the **revalidate function** under the api folder:

```jsx
// pages/api/revalidate.js

export default async function handler(req, res) {
    // Check for secret to confirm this is a valid request
    if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
      return res.status(401).json({ message: 'Invalid token' })
    }
  
    try {
      await res.unstable_revalidate('/')
      return res.json({ revalidated: true })
    } catch (err) {
      // If there was an error, Next.js will continue
      // to show the last successfully generated page
      return res.status(500).send('Error revalidating')
    }
  }
```

In order to revalidate the page you just need to provide the path of the page you want to reload.

As you can see from the code above you have to include a secret token to call the api.

This token is provided in the request (that’s why is not a good idea to call the revalidate from the client side 😅) and should match with the one configured as environment variable

We can add the token variable to a **.env.local** file next will read it at start time (More options [here](https://nextjs.org/docs/basic-features/environment-variables))
```
MY_SECRET_TOKEN=supersecret
```
## Run it

In order to see the result you have to make a production build and serve the app using the following:

```jsx
npm run build && npm run start
```

## Conclusion

In this quick post we saw how to use the new on-demand revalidate feature of Next.js 12.1.

It’s a very simple api and I think there are many use cases, I can’t wait the stable release to use it in my projects!! 🚀