Persistent navigation in a NextJs _app

You can add getInitialProps to your custom _app page (getServerSideProps and getStaticProps are not supported).

// _app.jsx

// Other imports..
import NextApp, { AppProps } from 'next/app';

interface WithNavProps extends AppProps {
  navigation: any;
}

const App = ({ Component, pageProps, navigation }: WithNavProps) => {
  console.log(navigation); // Will print your nav contents
  return (
    <AppLayout>
      <Header />
      <Component {...pageProps} />
    </AppLayout>
  );
};

App.getInitialProps = async (appContext) => {
  const appProps = await NextApp.getInitialProps(appContext);
  const navigation = ["nav"]; // Add your own logic to retrieve the data here
  return { ...appProps, navigation };
};

export default App;

Keep in mind that doing so will disable Automatic Static Optimization in pages without Static Generation.

Leave a Comment