DEV Community

HassanHabibTahir
HassanHabibTahir

Posted on

Revalidate in nextjs

In the context of Next.js, revalidation refers to the process of updating the cache for a specific page or set of pages when new data becomes available.

When a user visits a page on a Next.js site, the page is typically served from a cache instead of being generated on the server each time. This makes the site faster and more responsive. However, if the data that the page relies on changes frequently, it's important to update the cache so that users see the most up-to-date information.

Next.js provides a few different options for configuring revalidation. One common approach is to use the getStaticProps function, which fetches data at build time and generates static pages. By default, Next.js will revalidate the cache every 10 seconds, but this can be adjusted with the revalidate option.

Another approach is to use the getServerSideProps function, which fetches data at runtime instead of build time. In this case, the cache is updated on each request, so there's no need to specify a revalidation interval.

Overall, revalidation in Next.js ensures that users are always seeing the most up-to-date information, while still taking advantage of the performance benefits of caching.

Example to illustrate how revalidation works in Next.js

Let's say you're building a blog using Next.js, and you have a page that shows a list of the latest posts. You want to make sure that the list is always up-to-date, so you decide to use revalidation.

First, you create a getStaticProps function for the page. This function fetches the latest blog posts from a database and returns them as props:

import Head from 'next/head';
import axios from 'axios';


function Home({ news }) {
  return (
    <div>
      <Head>
        <title>Latest News</title>
      </Head>
      <h1>Latest News Headlines</h1>
      <ul>
        {news.map((headline) => (
          <li key={headline.id}>{headline.title}</li>
        ))}
      </ul>
    </div>
  );
}

export async function getStaticProps() {
const {data} = await axios.get('https://localhost:3000/api/news');
  return {
    props: {
      news:data,
    },
    // - When a request comes in
    // - At most once every 60 seconds
    revalidate: 60, // revalidate every 60 seconds
  };
}

export default Home;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)