1

As a NextJS newbie, I want to know the correct place for a dynamic header that's common in all pages. Seems to me the right location for it is in Layout that wraps all pages.

import Header from "../Header/Header";
import Footer from "../Footer/Footer";

export default function Layout({children}) {
    return (
        <>
            <Header/>

            { children }
        
        </>
    )
}


export default function MyApp({ Component, pageProps })
{
    return (

        <Layout>
            <Component {...pageProps} />
        </Layout>
    )
}

But in this approach, we won't be able to fetch data and generate the HTML for header and footer in the server side as only pages can make server side requests. So we must fetch header and footer data in client side which has two cons:

  1. Page body loads first and when ready, then header data is fetched which is bad UX.
  2. Header won't leverage the benefit of Next's SEO.

To solve this, we could place header in each page. This solves the SEO problem but there are cons in this approach:

  1. We would need to fetch and populate header data on each new SSR request increasing number of requests to API server.
  2. Any header data in memory, for example, value in a search input would be lost.

What is the correct approach to this?

anonym
  • 4,460
  • 12
  • 45
  • 75
  • Regarding your cons about having the header on each page: 1) caching would minimize the requests made to the backend; 2) You could use React context to persist the state. Also, you could still have the header in `Layout` inside `MyApp` and still fetch the data server-side with `getInitialProps` in your custom `_app`, as mentioned in [Persistent navigation in a NextJs _app](https://stackoverflow.com/a/65628271/1870780). – juliomalves Aug 24 '21 at 15:37
  • Won't this render SSG useless? Or pages with no blocking data? Throwing perf gains out the window? – james emanon Mar 12 '22 at 06:47

0 Answers0