Next.js: getStaticProps and getStaticPaths with dynamic routes to generate static files

Viewed 30232

I am finding the docs a little ambiguous. Given a list franchises, I would like to render out the relevant franchise detail pages at build time to avoid hitting the CMS/API at run time, as these don't change frequently.

However, it seems that even if the relevant pages are generated at build time using getStaticPaths, they still require the calls in getStaticProps to be executed at runtime. This defeats the purpose of generating static pages.

import {withLayout} from '../../components/layout';
import {getFranchises} from '../api/franchises';

const Franchise = (props) => {
    console.info(props);

    return (
        <>
            <h1>{props.name}</h1>
        </>
    );
};

export async function getStaticProps({params}) {
    let data = await getFranchises();

    let franchise = data.find(x => x.id === params.id);

    return {
        props: franchise
    }
}

export async function getStaticPaths() {
    let data = await getFranchises();

    // Get the paths we want to pre-render based on posts
    const paths = data.map(post => ({
        params: {id: post.id},
    }));

    // We'll pre-render only these paths at build time.
    return {paths, fallback: false}
}

export default withLayout(Franchise);

Perhaps, I am doing something wrong, but I really am looking for some docs/demo on how to generate static pages at build time using next build that uses data from API at build time and does not require any further calls to populate props at runtime.

1 Answers

Both getStaticProps and getStaticPaths run only at build time. That is the purpose of these functions. You are using it correctly.

In development mode next dev, however, getStaticProps and getStaticPaths run on every request.

getStaticProps (Static Generation)

Related