5

I'm in the middle of building a Next.js app, and I need to make a request for the navigation content to my Prismic API server-side, get the results, and pass them to my Header component so that I can have a persistent navigation menu. I don't want to include the header in every page component, nor do I want to have to query the document in every page.

Is there a way that I'm able to access getServerSideProps, getStaticProps, or getInitialProps within my _app.js so that I can have that persistent nav?

Here is my _app component, as well as my Prismic client, and my index page component, so you have an idea of the code I'm working with.

_app.js

import React from 'react';

import { AppLayout } from 'components/app-layout/AppLayout';
import { client } from 'lib/prismic';
import { GetServerSideProps } from 'next';
import { AppProps } from 'next/app';

interface WithNavProps extends AppProps {
  navigation: any;
}

const App = ({ Component, pageProps }: WithNavProps) => {
  return (
    <AppLayout>
      <Header />
      <Component {...pageProps} />
    </AppLayout>
  );
};

export default App;

prismic-client.ts

import Prismic from 'prismic-javascript';

export const apiEndpoint = process.env.PRISMIC_API_ENDPOINT as string;
export const accessToken = process.env.PRISMIC_ACCESS_TOKEN;

export const client = Prismic.client(apiEndpoint, { accessToken });

export const linkResolver = (doc: any) => {
  switch (doc.type) {
    case 'homepage':
      return `/`;

    case 'landing':
      return `/${doc.uid}`;

    case 'legal':
      return `/${doc.uid}`;

    case 'locator':
      return `/${doc.uid}`;

    case 'promos':
      return `/${doc.uid}`;

    case 'product':
      return `/products/${doc.uid}`;

    default:
      return `/`;
  }
};

index.tsx

import React from 'react';

import { Header } from 'components/header/Header';
import { SEO } from 'components/seo/SEO';
import { SliceZone } from 'components/slice-zone/SliceZone';
import { client } from 'lib/prismic';
import { RichText } from 'prismic-reactjs';

const Index = ({ document }: any) => {
  const slices = document;
  if (!slices) return null;

  return (
    <>
      <SEO
        title={RichText.asText(document.page_title)}
        description={document.meta_description}
        banner={document.social_image.url}
      />

      <SliceZone slices={slices} />
    </>
  );
};

export const getServerSideProps = async () => {
  const options = {
    lang: 'en-us',
  };
  const { data: document } = await client.getSingle('homepage', options);

  return {
    props: {
      document,
    },
  };
};

export default Index;
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Jesse Winton
  • 568
  • 10
  • 33

1 Answers1

3

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.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 2
    Wonderful, that worked for me. Does `getInitialProps` work at all similarly to `getServerSideProps` i.e. is it rendered server-side? – Jesse Winton Jan 08 '21 at 15:54
  • It is similar in that it also renders server-side on initial load, but will then run on the client when navigating to a different route (client-side transition), unlike `getServerSideProps`. – juliomalves Jan 08 '21 at 16:00
  • For further details: https://github.com/vercel/next.js/discussions/11211. – juliomalves Jan 08 '21 at 16:03
  • 1
    Just keep this from the docs in mind- For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router. However, if getInitialProps is used in a custom _app.js, and the page being navigated to implements getServerSideProps, then getInitialProps will run on the server. Source- https://nextjs.org/docs/api-reference/data-fetching/get-initial-props – Kisho Dec 22 '22 at 14:26