#How to Fetch Data in Custom App with Environment Variables?

2 messages · Page 1 of 1 (latest)

valid sable
#

I've come across an issue that I thought would be quite common across the internet and that there'd be multiple solutions, but I'm coming up short when trying to find one.

Basically I want to fetch some data (site settings) from a GraphQL API that will be used (potentially) on every single page. I have wrapped the GraphQL request into it's own function which creates the endpoint and also applies the necessary authentication headers using environment variables that I do not want exposed to the client.

All of this runs perfectly on the dev server, the getInitialProps is run on the server (confirmed by console logs) and when running the build command the environment variables are available to make the request.

But when I try deploying this to Netlify I get snagged. The build runs correctly, but getInitialProps is now being ran on the client, where the environment variables have been baked in as undefined. The request falls and the site returns a blank screen.

I tried changing this to use an API route, but that has its own issues as there is no BE available when the site is being built.

Has anyone else come across this problem or figured out a solution. Seems like it should be very common.

#

Custom App

const MyApp = ({
  Component,
  pageProps,
  router,
  programmeSettings,
  siteSettings,
}: MyAppProps) => {
  return (
    <SettingsProvider
      programmeSettings={programmeSettings}
      siteSettings={siteSettings}
    >
      <Component {...pageProps} url={router} />
    </SettingsProvider>
  );
};
 
MyApp.getInitialProps = async (context: AppContext) => {
  const appProps = await App.getInitialProps(context);
  const { programmeSettingsCollection, siteSettingsCollection } = await request(
    GetSettings
  );
  const programmeSettings = programmeSettingsCollection.items[0];
  const siteSettings = siteSettingsCollection.items[0];
 
  return { ...appProps, programmeSettings, siteSettings };
};
 
export default MyApp;