next.js: Cannot read properties of undefined (reading 'getInitialProps')

Verify canary release

  • 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.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 12
  • Comments: 57 (14 by maintainers)

Most upvoted comments

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?

FYI I also came across this error, straight after I added Sentry to my Next.js v12 project. I didn’t had a custom 404 page yet, but Sentry created a custom _error.js, which triggered the warning about a missing 404 page. I quickly added one and got that error.

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

After digging around a bit, I realized that I didn’t had a default export in my 404.js 🤦🏼 . After changing the export function Custom404() to a default export, the error went away.

tl;dr: Verify, that your 404.js (and of course all other pages) export the component as a default export 💡

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

This is occurring for us with next 12.3.4:

Debugging has lead me to:

https://github.com/vercel/next.js/blob/4ca12bd5443cb124a97ab803a89b58cf4e8728b9/packages/next/shared/lib/utils.ts#L362

App is undefined and as such is unsafe to call getInitialProps on, maybe the check should assert that App is defined before calling getInitialProps on it?

Looking at it - this may be related to the async to generator transformations somehow…

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.

In my case the problem is fixed defining an export default in all .tsx files

It still occurs in the following environments.

I tried upgrading to the latest version of @sentry/nextjs 7.53, but it didn’t help much.

I don’t think we’ve figured out exactly what the problem is yet. Is there anyone who can clarify why this issue occurs and how to solve it? If anyone leave a comment, it’ll be a big help to everyone. Thanks.

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… 😦

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?

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

Not completely familiar with how sentry boostraps in Next but renaming my /pages-components folder into something else (that doesn’t start with pages) resolved the issue in my case.

I also experienced this, but my project contained a /pagesComponents folder. Renaming the folder to something else did the trick. Thanks @korac.

Leaving this comment for all those still experiencing the issue.

Same as stated in this comment, I started to experience the issue right after adding Sentry to my Next v12 project. The issue started to appear with @sentry/nextjs: 7.17.1.

Changelog report for v7.17.1 lead me to this PR and specifically this line:

test: new RegExp(`^${escapeStringForRegex(pagesDirectory)}.*\\.(${pageExtensionRegex})$`),

This change was significant in my case since my project contained both /pages and /pages-components folders. Previously, given regex was matching only /pages folder but the new change included /pages-components as well.

Not completely familiar with how sentry boostraps in Next but renaming my /pages-components folder into something else (that doesn’t start with pages) resolved the issue in my case.

ps. after this renaming, my projects is ok even with latest @sentry/nextjs version 7.57.0.

I got same issues as above. Downgrading Sentry to 7.12.1 fixed. Was on 7.37.2 so not fixed there.

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

@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?

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.

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