0
votes

I am buiding a website using next.js and I am trying to wrap my head around the following "problem". I have some static data (website text) that needs to be fetched from an API endpoint (Headless CMS).

For individual pages I use getInitialProps to fetch the required data. However I also have a Footer component in my main layout. Both layout and the Footer component have no getInitialProps solution, so how to deal with this in a "nice" way?

Some solutions I thought of:

  1. I can use componentDidMount to do a client side fetch for the data in the footer component (But I really want to server fetch / make it static).
  2. Move the footer to each page and have getInitialProps available, adding some HOC to prevent rewriting all the code.
  3. As I said the data is static so make it available globally through server.js or _document.js (I don't know how to accomplish this though).

Anyone that can point me in the right direction?

1

1 Answers

2
votes

You can put your Header and Footer components in your _app.js.

First, in App.getInitialProps, fetch any data or perform any actions you need to happen server side. Then, this data you return can be returned as props, combined with the result of Component.getInitialProps (your page component's getInitialProps).

static async getInitialProps({ Component, ctx }) {
  let pageProps = {};

  // Make any initial calls we need to fetch data required for SSR
  const isAuthed = await ctx.reduxStore.dispatch(checkAuth());

  // Load the page getInitiaProps
  if (Component.getInitialProps) {
    pageProps = await Component.getInitialProps({ isAuthed, ...ctx });
  }

  return { pageProps: { ...pageProps, isAuthed } };
  // Or, if the async data is separate from your page props:
  // { pageProps, data: { isAuthed } };
}

In your render function you have access to this.props.pageProps (or this.props.data if you separated it). You can then pass that along to your header and footer.

<Header {...pageProps} />
  <main>
    <Component {...pageProps} />
  </main>
<Footer {...pageProps} />