Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Best Practice to fetch globals in Next Application

default discord avatar
chrispy.q2 years 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 };
};
  • default discord avatar
    jessrynkar2 years ago

    Hey

    @690590499202924574

    - 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
    chrispy.q2 years 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 🙂

    @854377910689202256
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.