Best Practice to fetch globals in Next Application

default discord avatar
Chris_Heinz
5 months ago
2

Hey guys I am struggling a bit to get my head around an elegant way on how to fetch my globals in a Next application. I currently have a custom _app.tsx with getInitialProps where I do some async fetching to the Payload Rest API passing down the data to my global components e.g Header similar to the way it is implemented in the tutorial series

https://www.youtube.com/watch?v=bxWsZTtqs80

. Now I was thinking about fetching the globals in each component in the useEffect hook instead of doing it in the custom app component to avoid passing down props and keep everything more isolated and I wanted to here about common solutions the community is handling globals fetching.



Using getInitialProps also leading to this warning: "Warning: You have opted-out of Automatic Static Optimization due to

getInitialProps

in

pages/_app

." Which concerns me although I am using SSR anyway.



currently in _app.tsx


MyApp.getInitialProps = async (appContext) => {
  [...]

  const getGlobals = (slug: string) => {
    return fetch(
      `${process.env.NEXT_PUBLIC_SERVER_URL}/api/globals/${slug}?locale=${locale}`
    ).then((res) => res.json());
  };

  const [header, footer, social, settings] = await Promise.all([
    getGlobals("header"),
  ]);

  return { ...appProps, header };
};
  • discord user avatar
    jesschow
    Payload Team
    5 months ago

    Hey @Chris_Heinz - have you tried using

    payload.findGlobal()

    ?



    You can see an example of how to use it in the next-payload repo here:

    https://github.com/payloadcms/next-payload-demo/blob/main/app/(site)/layout.tsx
  • default discord avatar
    Chris_Heinz
    5 months ago

    Yes using the local API leads to an error as I am using this template

    https://github.com/payloadcms/nextjs-custom-server

    as a base unfortunately the local API is not available. Actually I think there is no big difference whether I am querying the globals on app level and pass it down or if I am directly querying in the component itself. I just thought there might be a best practice to it. Anyway thanks for replying 🙂 @jesschow

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.