Challenges

Next.js Incremental Static Regeneration

Force Invalidation

Like in the previous step, sometimes users might get the same page if the traffic is low. If that breaks the functionality of your app, you can add a force invalidation. Here's how to do it:

This is the code of the pages/index.js after the change:

import { findSong } from '../lib/find-song'
import { Container } from '../components/Container';
import { useEffect } from 'react';

export default function Home({ song }) {
    useEffect(() => {
        const handler = setTimeout(() => {
            fetch('/')
        }, 3500)

        return () => clearTimeout(handler)
    }, [])

    return (
        <Container>
            <div className="music">
                <div className="name">{song.name}</div>
                <div className="artist">by {song.artist}</div>
                <div className="image">
                    <a href={song.trackUrl} target="_blank">
                        <img src={song.artwork} />
                    </a>
                </div>
                <audio controls loop>
                    <source src={song.preview} type="audio/mpeg" />
                </audio>
                <div className="reload">
                    <a href="/">Try Another One</a>
                </div>
            </div>
        </Container>
    )
}

export async function getStaticProps() {
    const song = await findSong();

    return {
        props: {
            song
        },
        revalidate: 3
    }
}

Have a look at the useEffect hook. What we are doing here is pretty simple. We fetch the page again in the background after 3500 milliseconds.

So, Next.js will start generating a new page. Then when we reload the page again, we will get a new page.

Replace your pages/index.js with the above code.

Now close the already running app. Then run the app with the following commands:

yarn build
yarn start

Let's do a simple experiment. This time, click "Try Another One" multiple times quickly for about 10 seconds.

Q: How do you describe the situation?
authenticating...