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

4.6k views Asked by At

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!

3

There are 3 answers

0
Guilherme Samuel On BEST ANSWER

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} };
}
0
Put Suthisrisinlpa On

I have found a way to get around this by using getServerSideProps and setting Cache-Control header in the getServerSideProps Doc.

0
Guy Dumais On

Next.js recommends using getStaticProps or getServerSideProps instead of getInitialProps to get the best performance from Next.js.

If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps.

The reason why Next.js recommends this is that getInitialProps disables Automatic Static Optimization and uses Server-side Rendering.

Using getInitialProps in your _app.js will disable automatic static optimization for all pages in your application. In addition, it will force all your pages to be generated on every request, as they use server-side rendering, which will lead to a bad Time to First Byte (TTFB).

I've made a cheat sheet about Next.js page rendering with live demo and code examples on Github to help understand quickly how it works. This will help you choose the right page rendering strategy with Next.js depending on your use case.