Search code examples
next.jsdrygetstaticpropsssg

NextJS, _app, SSG, getInitialProps vs getStaticProps and how am I supposed to stick to DRY?


I know that the topic isn't new and I found (and read) a few discussions. What I couldn't find is an answer to my still remaining question.

How do others work around the problem of not being able to use getStaticProps in _app.js ? getInitialProps is not an option for me cause I want to use SSG. Is there a way to force SSG even when using getInitialProps? Or do I really have to fetch all my data from my Headless CMS on every page? Since I want to build a Header (including Navigation) and a Footer, for example. Currently the only option I see is to repeat a lot of code.

Any hints much appreciated and thanks for reading!


Solution

  • Is there a way to force SSG even when using getInitialProps

    No. Although Nextjs team is working to add support for getStaticProps for _app.js, currently it disables static optimizations.

    As nextjs recommends, you should use getStaticProps when "The data comes from a headless CMS."

    So you'll have to have to do the same logic in every page that needs the request. Note that's possible to extract this logic into a function and reutilize it everywhere

    getData.js

    export async function getData({ req, res }) {
      const data = await getData();
    
      return { props: { data: data} };
    }
    

    pages/example.js

    export const getStaticProps = getData
    

    As another option, you can fetch data once in getInitialProps.

    Is easy to setup (but remember that you'll lose static optimization.)

    _app.js

    App.getInitialProps = ({ req, res }) => {
      const data = await getData();
    
      return { props: { data: data} };
    }