next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Cannot read properties of undefined (reading 'getInitialProps')

Open silentim opened this issue 3 years ago • 37 comments

Verify canary release

  • [x] I verified that the issue exists in Next.js canary release

Provide environment information

next: 12.1.1-12.1.6-canary.2 react: 17.0.2 or 18.0.0 node: 14.19.1 system: windows

What browser are you using? (if relevant)

chrome 100.0.4896.88

How are you deploying your application? (if relevant)

next start

Describe the Bug

error

Expected Behavior

no error in console and display page content

To Reproduce

//app.ts

const MyApp = ({ Component, pageProps }: AppProps) => {
    return <Component {...pageProps} />;
};

MyApp.getInitialProps = async (appContext: AppContext) => {
    const some = await fetch('....');

    const appProps = await App.getInitialProps(appContext);
    return { ...appProps, pageProps: { ...appProps.pageProps, some } };
};

export default MyApp;
//index.ts

export default function Home(){
    return (
        <div>some text</div>
    )
}

export const getStaticProps: GetStaticProps = async () => {
    return { props: { } };
}

Then npm run build, everything is ok and built successfully. Now npm run start, get error like this in console (see image attached) and there is nothing displaying in browser, just blank:

A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred Error rendering page: TypeError: Cannot read properties of undefined (reading 'getInitialProps')

No error if next 12.1.0 and more lower version.

silentim avatar Apr 17 '22 02:04 silentim

I found, if some function uses 'zlib' module in app.ts, and swcMinify=true in next.config.js, this error comes like above; If swcMinify=false, page is ok and no error. So then zlib will not be supported after next 12.1.0?

silentim avatar Apr 19 '22 05:04 silentim

No, it's a bug of swc minifier. As there are so many minification rules, there are some bugs. It's a huge project.

image

I'll add this to my private task list

kdy1 avatar Apr 21 '22 08:04 kdy1

Seeing the same. Setting swcMinify=false as recommended by @silentim fixed it.

C-E-Rios avatar Jun 15 '22 04:06 C-E-Rios

@silentim 🙏 thank you, fixed my issues with opensea-js failing to build nextjs on vercel, also @C-E-Rios swcMinify=false is the solution

KatFishSnake avatar Jul 07 '22 19:07 KatFishSnake

Is this issue still the case? As there's no repro it's too hard for me to verify it

kdy1 avatar Sep 26 '22 09:09 kdy1

Is this fixed in next 12.3?

davidhanlonJCM avatar Oct 10 '22 16:10 davidhanlonJCM

@davidhanlonJCM I think so, but I can't verify as there's no input nor repro case.

kdy1 avatar Oct 11 '22 07:10 kdy1

@kdy1 upgrading to next 12.3 appears to have solved the issue for me. In my case the issue appeared when using next 12.1 with swcMinify:true in the next.config file. It only showed up when running a full build or deployed to a vercel domain

davidhanlonJCM avatar Oct 11 '22 16:10 davidhanlonJCM

in version v13, if I run production (npm run build && npm run start) version I get these errors. if dev - all fine :|

DonikaV avatar Oct 27 '22 09:10 DonikaV

@DonikaV Can you provide a repro?

kdy1 avatar Oct 27 '22 09:10 kdy1

i've been getting the same errors in my sentry report.

using next 12.3.1

I've already tried to disable swcMinify.

i use getInitialProps once only in _document.js to setup styled-components basead on with-styled-components

import Document, { DocumentContext } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: [initialProps.styles, sheet.getStyleElement()],
      }
    } finally {
      sheet.seal()
    }
  }
}

My sentry report:

TypeError
Cannot read property 'getInitialProps' of undefined

./node_modules/next/dist/shared/lib/utils.js in call at line 66:18

                throw new Error(message);
            }
        }
        // when called from _app `ctx` is nested in `ctx`
        const res = ctx.res || ctx.ctx && ctx.ctx.res;
        if (!App.getInitialProps) {
            if (ctx.ctx && ctx.Component) {
                // @ts-ignore pageProps default
                return {
                    pageProps: yield loadGetInitialProps(ctx.Component, ctx.ctx)
                };




ReferenceError: globalThis is not defined
console
A client-side exception has occurred, see here for more info: 

Consequently seems like some users are getting and others not. any ideas?

rossignolli avatar Oct 27 '22 15:10 rossignolli

@rossignolli Can you try 12 canary?

kdy1 avatar Oct 27 '22 16:10 kdy1

@DonikaV Can you provide a repro?

No, the problem that I don't use anywhere any functions like getInitiallProps. I only use env vars. maybe it because of that, but in version 12* all works fine. In 13 no :|

DonikaV avatar Oct 27 '22 21:10 DonikaV

@rossignolli Can you try 12 canary?

Same :/

rossignolli avatar Oct 27 '22 23:10 rossignolli

Oh if disabling swcMinify does not work it's a different issue

kdy1 avatar Oct 28 '22 04:10 kdy1

after I disabled swcMinify works well. But is weird why it is happening :) @kdy1 I don't use anywhere this function getInitialProps...

DonikaV avatar Nov 03 '22 14:11 DonikaV

@DonikaV I can't debug without a repro

kdy1 avatar Nov 03 '22 15:11 kdy1

@rossignolli have you already resolved your problem? I faced the same :(

karolina-szlenk avatar Nov 04 '22 15:11 karolina-szlenk

Analyzing my sentry report I notice that most of errors come from outdated or unsupported browsers versions.

But i still trying to figure out a solution.

rossignolli avatar Nov 04 '22 17:11 rossignolli

Also having this issue with 13.0.2

Production Builds using getStaticProps are failing on Vercel are failing with the error:

TypeError: Cannot read properties of undefined (reading 'getInitialProps')
--
17:47:51.855 | at Object.41888 (/vercel/path0/.next/server/chunks/2843.js:3024:43)
17:47:51.855 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)
17:47:51.856 | at /vercel/path0/.next/server/chunks/2843.js:3294:94
17:47:51.856 | at Function.__webpack_require__.a (/vercel/path0/.next/server/webpack-runtime.js:89:13)
17:47:51.856 | at Object.34008 (/vercel/path0/.next/server/chunks/2843.js:3259:21)
17:47:51.856 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)
17:47:51.856 | at /vercel/path0/.next/server/chunks/2843.js:3219:93
17:47:51.856 | at Function.__webpack_require__.a (/vercel/path0/.next/server/webpack-runtime.js:89:13)
17:47:51.856 | at Object.6817 (/vercel/path0/.next/server/chunks/2843.js:3205:21)
17:47:51.856 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)

...but I can do production builds locally.

swcMinify: false does not fix the error.

I am also using a custom _document to inject serverside styles, but using Emotion.

My _document file:

class MyDocument extends Document {
  render() {
    return (
      <Html>
        {...}
      </Html>
    );
  }
}


MyDocument.getInitialProps = async (ctx) => {
 
  const originalRenderPage = ctx.renderPage;

  const cache = createEmotionCache();
  const { extractCriticalToChunks } = createEmotionServer(cache);

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) =>
        function EnhanceApp(props) {
          return <App emotionCache={cache} {...props} />;
        },
    });

  const initialProps = await Document.getInitialProps(ctx);
  // This is important. It prevents Emotion rendering invalid HTML.
  // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153

  const emotionStyles = extractCriticalToChunks(initialProps.html);
  const emotionStyleTags = emotionStyles.styles.map((style) => (
    <style
      data-emotion={`${style.key} ${style.ids.join(' ')}`}
      key={style.key}
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML={{ __html: style.css }}
    />
  ));

  return {
    ...initialProps,
    emotionStyleTags,
  };
};

Is the custom _document the common theme?

tomgreeEn avatar Nov 04 '22 17:11 tomgreeEn

Also having this issue with 13.0.2

Production Builds using getStaticProps are failing on Vercel are failing with the error:

TypeError: Cannot read properties of undefined (reading 'getInitialProps')
--
17:47:51.855 | at Object.41888 (/vercel/path0/.next/server/chunks/2843.js:3024:43)
17:47:51.855 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)
17:47:51.856 | at /vercel/path0/.next/server/chunks/2843.js:3294:94
17:47:51.856 | at Function.__webpack_require__.a (/vercel/path0/.next/server/webpack-runtime.js:89:13)
17:47:51.856 | at Object.34008 (/vercel/path0/.next/server/chunks/2843.js:3259:21)
17:47:51.856 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)
17:47:51.856 | at /vercel/path0/.next/server/chunks/2843.js:3219:93
17:47:51.856 | at Function.__webpack_require__.a (/vercel/path0/.next/server/webpack-runtime.js:89:13)
17:47:51.856 | at Object.6817 (/vercel/path0/.next/server/chunks/2843.js:3205:21)
17:47:51.856 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)

...but I can do production builds locally.

swcMinify: false does not fix the error.

I am also using a custom _document to inject serverside styles, but using Emotion.

My _document file:

class MyDocument extends Document {
  render() {
    return (
      <Html>
        {...}
      </Html>
    );
  }
}


MyDocument.getInitialProps = async (ctx) => {
 
  const originalRenderPage = ctx.renderPage;

  const cache = createEmotionCache();
  const { extractCriticalToChunks } = createEmotionServer(cache);

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) =>
        function EnhanceApp(props) {
          return <App emotionCache={cache} {...props} />;
        },
    });

  const initialProps = await Document.getInitialProps(ctx);
  // This is important. It prevents Emotion rendering invalid HTML.
  // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153

  const emotionStyles = extractCriticalToChunks(initialProps.html);
  const emotionStyleTags = emotionStyles.styles.map((style) => (
    <style
      data-emotion={`${style.key} ${style.ids.join(' ')}`}
      key={style.key}
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML={{ __html: style.css }}
    />
  ));

  return {
    ...initialProps,
    emotionStyleTags,
  };
};

Is the custom _document the common theme?

UPDATE: Having disabled the part of _document with getInitialProps, and removed the other reference to getInitialProps in my app (inside the Sentry Error Handler), I still get this error.

tomgreeEn avatar Nov 04 '22 18:11 tomgreeEn

Also having this issue with 13.0.2 Production Builds using getStaticProps are failing on Vercel are failing with the error:

TypeError: Cannot read properties of undefined (reading 'getInitialProps')
--
17:47:51.855 | at Object.41888 (/vercel/path0/.next/server/chunks/2843.js:3024:43)
17:47:51.855 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)
17:47:51.856 | at /vercel/path0/.next/server/chunks/2843.js:3294:94
17:47:51.856 | at Function.__webpack_require__.a (/vercel/path0/.next/server/webpack-runtime.js:89:13)
17:47:51.856 | at Object.34008 (/vercel/path0/.next/server/chunks/2843.js:3259:21)
17:47:51.856 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)
17:47:51.856 | at /vercel/path0/.next/server/chunks/2843.js:3219:93
17:47:51.856 | at Function.__webpack_require__.a (/vercel/path0/.next/server/webpack-runtime.js:89:13)
17:47:51.856 | at Object.6817 (/vercel/path0/.next/server/chunks/2843.js:3205:21)
17:47:51.856 | at __webpack_require__ (/vercel/path0/.next/server/webpack-runtime.js:25:42)

...but I can do production builds locally. swcMinify: false does not fix the error. I am also using a custom _document to inject serverside styles, but using Emotion. My _document file:

class MyDocument extends Document {
  render() {
    return (
      <Html>
        {...}
      </Html>
    );
  }
}


MyDocument.getInitialProps = async (ctx) => {
 
  const originalRenderPage = ctx.renderPage;

  const cache = createEmotionCache();
  const { extractCriticalToChunks } = createEmotionServer(cache);

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) =>
        function EnhanceApp(props) {
          return <App emotionCache={cache} {...props} />;
        },
    });

  const initialProps = await Document.getInitialProps(ctx);
  // This is important. It prevents Emotion rendering invalid HTML.
  // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153

  const emotionStyles = extractCriticalToChunks(initialProps.html);
  const emotionStyleTags = emotionStyles.styles.map((style) => (
    <style
      data-emotion={`${style.key} ${style.ids.join(' ')}`}
      key={style.key}
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML={{ __html: style.css }}
    />
  ));

  return {
    ...initialProps,
    emotionStyleTags,
  };
};

Is the custom _document the common theme?

UPDATE: Having disabled the part of _document with getInitialProps, and removed the other reference to getInitialProps in my app (inside the Sentry Error Handler), I still get this error.

For me, the issue was @sentry/nextjs v 7.13+. Downgrading to 7.12.1 has fixed it for now.

tomgreeEn avatar Nov 07 '22 23:11 tomgreeEn

@rossignolli I've noticed the same. Any progress? Many issues come from old browsers. Maybe a reason is that the old browsers do not support 'globalThis'? What do you think? Can you reproduce it somehow, or only see it in Sentry issues?

karolina-szlenk avatar Nov 08 '22 11:11 karolina-szlenk

In v13 I get the same error after yarn build and yarn start. As I didn't use any getInitialProps in my project swcMinify=false solved this one for me... :(

ShahriarDhruvo avatar Nov 09 '22 09:11 ShahriarDhruvo

@ShahriarDhruvo Can you create a repro? Also, does it happen only for old browsers?

kdy1 avatar Nov 09 '22 09:11 kdy1

I was having a similar error after updating from Next.js 12 to Next.js 13, and the error only appeared on production, development worked great.

This was the error I was getting:

TypeError: Cannot read properties of undefined (reading 'getInitialProps') at Object.<anonymous>

but adding swcMinify: false, to next.config.js fixed it

jerocosio avatar Nov 10 '22 07:11 jerocosio

Can someone provide a repro?

kdy1 avatar Nov 10 '22 07:11 kdy1

In my case error happens also only in production mode, and all browsers are up so date. Can not show repo, sorry :(

DonikaV avatar Nov 10 '22 09:11 DonikaV

I mean reproduction case, not repo

kdy1 avatar Nov 10 '22 09:11 kdy1

@kdy1 Where can I send you a URL of my past deployments that had the issue? It's not a public project yet so I can't share it here.

jerocosio avatar Nov 10 '22 23:11 jerocosio