Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot read properties of undefined (reading 'getInitialProps') #36221

Closed
1 task done
silentim opened this issue Apr 17, 2022 · 57 comments
Closed
1 task done

Cannot read properties of undefined (reading 'getInitialProps') #36221

silentim opened this issue Apr 17, 2022 · 57 comments

Comments

@silentim
Copy link

silentim commented Apr 17, 2022

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.

@silentim silentim added the bug Issue was opened via the bug report template. label Apr 17, 2022
@silentim
Copy link
Author

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?

@kdy1
Copy link
Member

kdy1 commented Apr 21, 2022

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 kdy1 self-assigned this Apr 21, 2022
@balazsorban44 balazsorban44 added kind: bug and removed bug Issue was opened via the bug report template. labels Apr 29, 2022
@C-E-Rios
Copy link

C-E-Rios commented Jun 15, 2022

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

@KatFishSnake
Copy link

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

@kdy1
Copy link
Member

kdy1 commented Sep 26, 2022

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

@davidhanlonJCM
Copy link

Is this fixed in next 12.3?

@kdy1
Copy link
Member

kdy1 commented Oct 11, 2022

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

@davidhanlonJCM
Copy link

@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

@kdy1 kdy1 removed their assignment Oct 12, 2022
@DonikaV
Copy link

DonikaV commented Oct 27, 2022

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

@kdy1
Copy link
Member

kdy1 commented Oct 27, 2022

@DonikaV Can you provide a repro?

@rossignolli
Copy link

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?

@kdy1
Copy link
Member

kdy1 commented Oct 27, 2022

@rossignolli Can you try 12 canary?

@DonikaV
Copy link

DonikaV commented Oct 27, 2022

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

@rossignolli
Copy link

rossignolli commented Oct 27, 2022

@rossignolli Can you try 12 canary?

Same :/

@kdy1 kdy1 self-assigned this Oct 27, 2022
@kdy1
Copy link
Member

kdy1 commented Oct 28, 2022

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

@kdy1 kdy1 removed their assignment Oct 28, 2022
@DonikaV
Copy link

DonikaV commented Nov 3, 2022

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

@kdy1
Copy link
Member

kdy1 commented Nov 3, 2022

@DonikaV I can't debug without a repro

@karolina-szlenk
Copy link

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

@rossignolli
Copy link

rossignolli commented Nov 4, 2022

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.

@tomgreeEn
Copy link

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
Copy link

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.

@paulmuenzner
Copy link

paulmuenzner commented Nov 13, 2022

@JoBurg007 Can you provide a repro?

@kdy1 Sorry, don't have this anymore. I meanwhile checked the web and implemented a solution that works for me now without making compromises and by using getInitialProps in _app without any error: https://jools.dev/server-side-auth-with-nextjs-context-and-hooks.
Again: I did not set swcMinify to false anymore. My Next version: 13.0.0, with react 18.2.0
I guess I did not use the correct import - "import App from "next/app"" - which I need inside my getInitialProps (check the above link). But I am not sure. I am happy that it works now finally after spending half of my Sunday.

@DonikaV
Copy link

DonikaV commented Nov 17, 2022

I removed
swcMinify: false,
from my config and in new version of nextjs I don't have anymore this error.

  "loader-utils": "^3.2.1",
    "next": "^13.0.3",
    "next-transpile-modules": "^10.0.0",

@t-moennich
Copy link

t-moennich commented Nov 17, 2022

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 💡

@admmasters
Copy link

admmasters commented Dec 1, 2022

This is occurring for us with next 12.3.4:

Debugging has lead me to:

if (!App.getInitialProps) {

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

@Leo1212
Copy link

Leo1212 commented Dec 8, 2022

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.

Thanks, this solved my issue. I downgraded @sentry/nextjs to 7.12.1
I got the following error:

TypeError: this.getNonce is not a function
    at getInitialProps (file:///pathToMyApp/node_modules/@rest-hooks/ssr/lib/nextjs/RestHooksDocument.js:29:19)
    at async getInitialProps (webpack-internal:///./pages/_document.page.tsx?__sentry_wrapped__:27:30)
    at async pathToMyApp\node_modules\@sentry\nextjs\cjs\config\wrappers\wrapperUtils.js:34:14
    at async pathToMyApp\node_modules\@sentry\nextjs\cjs\config\wrappers\wrapperUtils.js:113:14

@majid-amiri
Copy link

Hey everyone, any updates on this?

@tomgreeEn
Copy link

Not sure if this is a related issue or not, but I recently upgraded node 14->18 and the various issues I had went away - see #45052 (comment)

@gavinharris-dev
Copy link

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

@pckilgore
Copy link

Can't confirm yet, but believe my case will be addressed by getsentry/sentry-javascript#6572 (comment)

@FrancoAguzzi
Copy link

I was facing the same issue, tested the different fix approaches mentioned in this thread but none of them worked... So I started debugging branch commits one by one and found out the root cause of this error triggering in Cypress CI process was related to a code change I made to a index.ts file in the project.

Basically, this index.ts file does the following inside the folder it is inserted:

export * from './component-1'
export * from './component-2'
export * from './component-3'

My error was updating the order of this exports, after undoing the order changes I made, the error was gone.
Hope it helps someone going through de same.

@dlvx
Copy link

dlvx commented Mar 21, 2023

I have tried everything posted in this discussion and I still get the error. I last tried to downgrade from Next 13 to 12 and from @sentry/next 7.43 to 7.12.1. I hoped this one would solve it but the error still shows in Sentry. This not only affects older browsers as some people have pointed out, but I've also seen users in the latest MacOS and Safari version having this issue and it doesn't allow them to navigate in the app. Is anyone still having this issue after trying out all the options?

@JClackett
Copy link
Contributor

Still having this issue, seeing it sentry affect users using the below:


Chrome Mobile
Version:87.0.4280

Android
Version:8.0

Pixel 2
Model:Pixel 2

@Jay-flow
Copy link

It still occurs in the following environments.

  • "@sentry/nextjs": "^7.34.0"
  • "next": "13.2.4",

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.

@jt561
Copy link

jt561 commented May 29, 2023

Is anyone having the same issue with TRPC as a wrapper around their app?

@iscekic
Copy link

iscekic commented Jun 23, 2023

Any update? Seems like a simple ?. as this comment says: #36221 (comment)

@jt561
Copy link

jt561 commented Jun 23, 2023

Turns out my issue was related to import statements. I am using a mono repo which had a lot of circular dependencies causing the build to have problems but everything works fine after creating a dependency graph and moving things around

@korac
Copy link

korac commented Jul 11, 2023

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.

@surbina
Copy link

surbina commented Jul 13, 2023

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.

@frattaro
Copy link

This started in one of our projects. I found a colleague had added (most likely auto-added on accident):

import { NextRouter } from "next/router"

removing that fixed it

@lsaavedr
Copy link

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

@kevinrobert3
Copy link

kevinrobert3 commented Oct 11, 2023

@dlvx , @JClackett and @rossignolli do any of you have an update on this or a workaround? My issue affects ios devices on browser "Mobile Safari UI/WKWebView"

@kevinrobert3
Copy link

Turns out I needed just enough time and headache to troubleshoot this.
For those that this affects iOS users, you need to debug on your phone (iOS), run local, and connect your phone browser.
All that same address and same network stuff.
Then the error that usually occurs (in production) will be thrown, by nextjs. This will be easier for you to debug now since you even get the line it occurs from.
For me, it was

  1. A service worker for messaging that was not registering and throwing an error
  2. A Firebase messaging error since I guess (firebase messaging) was not yet supported by iOS devices then and on old browsers

@samcx
Copy link
Member

samcx commented Jan 4, 2024

Hi everyone,

I will be moving this to :nextjs: Discussions since there seems to be a variety of solutions that remedied this issue and a variety of issues that was/is causing this issue.

Thank you for all the different solutions and reports!

If the issue continues to arise, I encourage folks to create a separate bug report for their issue. :blob_bowing:

@vercel vercel locked and limited conversation to collaborators Jan 4, 2024
@samcx samcx converted this issue into discussion #60234 Jan 4, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests