NextJS: TypeError: Cannot read property 'headers' of undefined

Viewed 1017

I am receiving this error in getInitialProps function attached to my page:

const getInitialProps = async ({ req, query }: NextPageContext) => {
  let isValidReferenceQuery = true;

  const { path } = absoluteUrl(req as IncomingMessage);
  try {
    await policyService.getPolicyByReference(
      path,
      query.referenceQuery as string
    );
  } catch (error) {
    isValidReferenceQuery = false;
  }

  return {
    referenceQuery: (query.referenceQuery as string) ?? null,
    isValidReferenceQuery,
  };
};

Page.getInitialProps = getInitialProps;

The function absoluteUrl determines if the API call was made server-side or client-side and adjusts the path accordingly:

export default function absoluteUrl(
  req: IncomingMessage
): Record<string, string> {
  const protocol = req.headers.referer?.split('//')[0] ?? 'http:';
  const host = req
    ? req.headers['x-forwarded-host'] || req.headers.host
    : window.location.host;
  const path =
    host === 'localhost:3000'
      ? `${protocol}//localhost:8080`
      : `${protocol}//${host}${axios.defaults.baseURL}`;
  return {
    path,
  };
}

I have updated my _document.tsx & _app.tsx to include getInitialProps as described to opt-out of automatic static generation in development mode so req should be defined. We also need all pages to be SSR for localisation:

import React from 'react';
import App, { AppContext } from 'next/app';
import { ReactQueryCacheProvider, QueryCache } from 'react-query';
import { Hydrate } from 'react-query/hydration';
import { appWithTranslation } from '@/localisation/i18n';
import { AppPageProps } from '@/models/page';

const TextMiningApp = ({ Component, pageProps }: AppPageProps) => {
  const queryCache = new QueryCache();
  const Layout = Component.Layout ? Component.Layout : React.Fragment;

  return (
    <ReactQueryCacheProvider queryCache={queryCache}>
      <Hydrate state={pageProps.dehydratedState}>
          <Layout>
            {/* eslint-disable-next-line react/jsx-props-no-spreading */}
            <Component {...pageProps} />
          </Layout>
      </Hydrate>
    </ReactQueryCacheProvider>
  );
};

TextMiningApp.getInitialProps = async (appContext: AppContext) => ({
  ...(await App.getInitialProps(appContext)),
});

export default appWithTranslation(TextMiningApp);

I cannot see why if i have opted out of automatic static generation that req is undefined?

0 Answers
Related